Rngd linux ��� ���

Rng-tools

The rng-tools is a set of utilities related to random number generation in kernel. The main program is rngd, a daemon developed to check and feed random data from hardware device to kernel entropy pool.

This is mainly useful to increase the quantity of entropy in kernel to make /dev/random faster. By default, /dev/random is very slow since it only collects entropy from device drivers and other (slow) sources. rngd allows the use of faster entropy sources, mainly hardware random number generators (TRNG), present in modern hardware like recent AMD/Intel processors, Via Nano or even Raspberry Pi.

While Linux itself uses the result from TRNG in /dev/random , if available, they are only used as a XOR after the entropy is collected by kernel. So /dev/random , by default, is slow even if you do have a TRNG. rngd feeds /dev/random itself, increasing the available entropy by far.

Contents

Installation

Configuration

The configuration file is located in /etc/conf.d/rngd . There is only one option though, that is RNGD_OPTS , the parameters to be passed to the daemon when running it with the included rngd.service . The default parameter ( «» , or blank) should work in the majority of cases.

By default, rngd will try to automatically detect your TRNG and use it. This is reported to work for Raspberry Pi and Intel Ivy Bridge CPU using the lastest versions of rng-tools. If this does not work, you may manually pass the device file used by your TRNG, as in the below example:

By default rngd fills the entropy pool until at least 2048 bits of entropy are available. This is to avoid the TRNG to dominate the contents of the pool. You can override this setting if you really trust your TRNG. To do this, pass «—fill-watermark=4096» to RNGD_OPTS , for example (4096 is the maximum size of kernel’s entropy pool by default, you should not pass a value greater than the maximum either). Doing so may increase the performance of /dev/random even further, at the expense of maybe lower random number quality. However, it should be noted that the default setting is already sufficient for the majority of user cases.

Testing and usage

You may test if rngd is working before enabling its service by running:

A simple test to see if everything is working as it should is to run (in another terminal) the following dd command:

Without rngd, the above command will take lots of time to run. With rngd working properly, the result should be almost instantaneous:

A speed of around 50 kB/s in dd‘s output shows that everything is working properly. For comparison, without rngd you probably would get 0.0 kB/s (since the speed is too low).

Another interesting test is to run rngtest, to check the data using FIPS 140-2 tests:

It is normal for any random number generator to fail in a small number of tests in 1000 passes, however if the number of failures is too great (like 10), probably there is something wrong.

Источник

rngd — Man Page

Check and feed random data from hardware device to kernel random device

Synopsis

rngd [-b, —background] [-f, —foreground] [-d, —debug] [-l, —list] [-x, —exclude] [-n, —include] [-O, —option] [-i, —ignorefail] [-o, —random-device=file] [-p, —pid-file=file] [-r, —rng-device=file] [-s, —random-step=nnn] [-t, —test] [-W, —fill-watermark=nnn] [-R, —force-reseed=nnn] [-q, —quiet] [-?, —help] [-V, —version]

Description

This daemon feeds data from a random number generator to the kernel’s random number entropy pool, after first checking the data to ensure that it is properly random.

Читайте также:  Android sdk location mac os

The -f or —foreground options can be used to tell rngd to avoid forking on startup. This is typically used for debugging. The -b or —background options, which fork and put rngd into the background automatically, are the default.

The -r or —rng-device options can be used to select an alternate source of input, besides the default /dev/hwrng. The -o or —random-device options can be used to select an alternate entropy output device, besides the default /dev/random. Note that this device must support the Linux kernel /dev/random ioctl API.

Options

Become a daemon (default)

Do not fork and become a daemon

Enable debug messages

List the indexes and names of available entropy sources. Exit code when listing sources is 0 if at least 1 entropy source was found and initialized, 1 otherwise.

Disable entropy sources based on index or (shortname) reported from —list option

Enable entropy sources based on index or (shortname) reported from —list option

Provide specific config options to individual entropy sources, in the format —option [index|shortname]:key:value. See Entropy Sources section below for indices and source specific options. Note that specifying -O [ | ] will print the available options for that index to the console

File used for recording daemon PID, and multiple exclusion (default: /var/run/rngd.pid)

Ignore repeated fips failures

Kernel device used for random number output (default: /dev/random)

Kernel device used for random number input (default: /dev/hwrng)

Number of bytes written to random-device at a time (default: 64)

Enter test mode. In this mode (which implies -f), all generated entropy is discarded and rngd reports the amount of entropy generated every second

Number of bits to consider random when adding entropy. 1 -W n, —fill-watermark=nnn

Once we start doing it, feed entropy to random-device until at least fill-watermark bits of entropy are available in its entropy pool. By default, this value is set to 75% of the entropy pool size or 2048 bits if the entropy pool size couldn’t be determined. Setting this too high will cause rngd to dominate the contents of the entropy pool. Low values will hurt system performance during entropy starves. Do not set fill-watermark above the size of the entropy pool (usually 4096 bits). A value of 0 to this option will cause no watermark to be set.

For newer kernels which support non-blocking entropy pools, it is still beneficial to periodically add fresh entropy as a reseeding event. —force-reseed defines the number of seconds between which fresh entropy is added to the kernel entropy pool. Defaults to 5 minutes.

Suppress all messages

Give a short summary of all program options.

Print program version

Entropy Sources

Rngd is made up of multiple entropy sources, the data from which is aggregated and fed into the kernels entropy pool. Note that not all entropy sources are available on all systems, and if an entropy source is enabled for a system on which it is not appropriate (or possible) to use, it may fail initialization. It is not fatal to rngd for any single entropy source to fail during startup. Only a single entropy sources is needed for rngd to operate. The following entropy sources are currently defined in rngd

Hardware RNG (hwrng) [Index 0]

The Hardware RNG is a generic entropy source that draws entropy from a hardware rng attached by default to /dev/hwrng

TPM (tpm) [Index 1]

Entropy drawn from on board TPM device. Note this entropy source is deprecated and will be removed soon, as newer tpm devices export entropy via /dev/hwrng, which is collected by the hwrng source above

RDRAND/RDSEED (rdrand) [Index 2]

Entropy drawn from the RDRAND and RDSEED instructions (x86 only)

use_aes — select if rdrand is used to seed a cprng to produce entropy, or if all entropy is drawn directly from rdrand instruction (default 0)

Читайте также:  Ipmi сброс пароля linux

DARN (darn) [Index 3]

Entropy drawn from the DARN instruction (ppc64 only)

use_aes — select if the power darn instruction is used to directly fill the entropy poll, or if it is used as a periodic seed to an aes based cprng (default 1)

RNDR (rndr) [Index 8]

Entropy drawn from the RNDR instruction (aarch64 only)

use_aes — select if the arm rndr instruction is used to directly fill the entropy poll, or if it is used as a periodic seed to an aes based cprng (default 0)

NIST Entropy Beacon (nist) [Index 4]

Entropy gathered from the NIST network entropy beacon. Note that this entropy source is disabled by default as it should never be used for cryptographic purposes, or any use case in which random data should be known only by a single entity.

JITTER (jitter) [Index 5]

Entropy gathered by measuring timing variance of operations on the local cpu

thread_count — Set the number of threads that the jitter entropy source will spawn

buffer_size — Set the size of the buffer cache that each thread maintains

refill_thresh — Set the low watermark for the cache that triggers its corresponding thread to start refill operations

retry_count — If all entropy buffers are empty, retry this many times before giving up. Note that jitterentropy can take several seconds to refill a buffer, and so retries after a delay may be preferable to repeatedly spining on an empty buffer (default 1)

retry_delay — between each retry for retry_count above, sleep for this many seconds. May also be the special value -1, representing adaptive sleep, where each retry delay will be half the recorded execution time of the last entropy gathering round (default -1)

force_soft_timer — on platforms with a hardware timer that is too coarse to sample jitter, we can instead use a software based timer loop. Detection and use of this mechanism is automatic, but this can be useful for testing purposes

PKCS11 (pkcs11) [Index 6]

Entropy gathered via the opensc openssl engine, which can extract entropy from various smart card readers

engine_path — Set the patch for the pkcs11 engine DSO to load

chunk_size — Some pkcs11 engines have restrictions on how much data can be requested at a time, this option allows for the request to be subdivided into smaller chunks to be satisfied

RTLSDR (rtlsdr) [Index 7]

Entropy gathered via the rtl software defined radio library, which can gather entropy using various usb software defined radios listening to random radio static

devid — When multiple devices are available the integer index of the device to use

freq_min — The minimum frequence range to scan in

freq_max — The maximum frequency range to scan in

sample_min — The minimum sample rate of the radio

sample_max — The maximum sample rate of the radio

Источник

Случайные числа в Linux(RNG) или как «наполнить» /dev/random и /dev/urandom

Пожалуй всем пользователям Linux известны такие файлы псевдо-устройств как /dev/random и /dev/urandom. Эти устройства являются интерфейсом к генератору случайных чисел ядра(RNG, random number generator).

Случайные числа(они же — непредсказуемый набор битов) очень важны в криптографии. Они являются базовыми кирпичиками для криптографических протоколов. От качества (неповторимости, непредсказуемости) этих чисел зависит стойкость всевозможных TLS-сертификатов, SSH и GPG ключей, сессионных симметричных TLS-ключей и т.д. Так же случайные числа являются основой для генерации UUID’ов, PID’ов, TCP sequence numbers и многого другого.

RNG генерит случайные числа на основе данных из пула энтропии(entropy pool) в ядре Linux. Наполнением этого пула так же занимается RNG и делается это на основе случайных событий в системе таких как: тайминги клавиатуры и дисков, движения мыши, прерывания(interrupts), сетевой трафик.

Пул энтропии имеет фиксированный объем 4096 bits:

Размер пула нельзя изменить, это захардкожено в ядре.

Посмотреть текущий объем данных в пуле:

Доступный объем энтропии постоянно меняется, в зависимости от скорости пополнения и потребления соответственно.

Читайте также:  Операционная система microsoft windows панель управления

Собственно через /dev/random и /dev/urandom приложения в user space получают эти самые случайные числаданные.

/dev/random является источником случайных данных наивысшего качества которые может предоставить ядро. Но при этом он блокирующийся, что означает, что приложение читающее из /dev/random повиснет в ожидании данных если пул энтропии окажется пустым.

/dev/urandom — unlimited random, не блокирующийся и приложения могут читать из него бесконечно. Предоставляет случайные данные такого же высокого качества что и /dev/random но до тех пор пока пул энтропии не опустеет. Когда пул будет пустым, /dev/urandom продолжит выдавать случайные данные но теоретически сильно меньшего качества.

Настоятельно рекомендуется для любых долго-живущих ключей, например для TLS-сертификатов использовать /dev/random т.к. только он гарантирует качество случайных чисел. Но, большинство приложений таких как Apache, Nginx, sshd и о Боже ssh-keygen, openssl используют /dev/urandom. Тут в принципе понятно Apache, Nginx, sshd не хотят блокироваться при генерации сессионных ключей. Но то, что ssh-keygen и openssl используют по умолчанию /dev/urandom меня поразило. Причем для openssl можно задать устройство при генерации ключей(ниже пример) а вот для ssh-keygen я возможности переопределить поведение не нашел.

В общем не важно откуда читают ваши приложения, нельзя допускать опустошение этого самого пула энтропии и тогда счастье будет и с /dev/urandom.

Прежде чем начать “майнить” энтропию, пара слов о ее корректном использовании из man /dev/random:

The amount of seed material required to generate a cryptographic key equals the effective key size of the key. For example, a 3072-bit RSA or Diffie-Hellman private key has an effective key size of 128 bits (it requires about 2^128 operations to break) so a key generator only needs 128 bits (16 bytes) of seed material from /dev/random.

Например openssl для генерации RSA ключа длиной 10240 bit использует всего 2048 исходного материала из /dev/random:

Как заполнить пул энтропии?

Лучшее решение это использование специальных аппаратных средств(TPM, Trusted Platform Module) или инструкций процессора типа RDRAND(есть в Intel IvyBridge и Haswell процессорах).

Проверить наличие подобных устройств на сервере поможет утилита rngd из пакета rng-tools

Если rngd обнаружит поддерживаемые средства то вам повезло и вы можете запустить сервис rngd. В моем случае их нет)

Собственно задача rngd читать энтропию из аппаратных средств и наполнять ей пул энтропии ядра. Делается это через специальный ioctl вызов(RNDADDENTROPY) интерфейса /dev/random.

Если нет аппаратной поддержки

В интернете можно встретить рекомендации, где предлагают указывать /dev/urandom как источник энтропии для rngd. То есть источником энтропии для ядра по сути будет само ядро). Это довольно сомнительная идея, и я бы не стал так делать и вам не советую. Но ради эксперимента я провел тесты и результаты(которые ниже) тоже довольно не плохие.

Havegd

В основе лежит алгоритм HAVAGE который генерирует энтропию на основе счётчиков и состояний процессора. В силу сложного, многоуровневого устройства процессоров, один и тот же код всегда выполняется за разное время и это не постоянство является основой для алгоритма HAVAGE.

На практике, это user space демон который как и rngd наполняет пул энтропии ядра через ioctl интерфейс /dev/random. при этом не нуждается в источнике энтропии как rngd.

Для centos пакет доступен из epel.

После установки нужно просто запустить сервис. С параметрами по умолчанию haveged будет стараться держать пул энтропии ядра на уровне не ниже 1024.

Тестирование

Без rngd и haveged, команда(ниже будет понятно, что она делает):

Не завершилась за сутки!

rngd с /dev/urandom в качестве источника энтропии

(то, что я вам не рекомендовал)

Тест(худший из 3-х результат):

Тут нужно смотреть на successes, failures, и на input channel speed.

При этом утилизация CPU процессом rngd: 57%

haveged

Тест(худший из 3-х результат):

При этом утилизация CPU процессом haveged:12%

Виртуальные машины

Не рекомендуется использовать haveged внутри ВМ, т.к. там вроде как счетчики CPU не такие точные(типа округляются) и это сказывается на качестве энтропии.
Тру путь это использовать virt-ioRNG(qemu-kvm) — паравиртуальное устройство которое будет брать энтропию из пула хоста. Но, это уже совсем другая история…)

Источник

Оцените статью