History log of /openbsd-current/sys/dev/rnd.c
Revision (<<< Hide revision tags) (Show revision tags >>>) Date Author Comments
# 1.228 14-Jun-2024 claudio

Make arc4random() depend on less subsystems by decoupling extract_entropy()
from the enqueue_randomness() logic.

Add add_event_data() which just enqueues some data into the event buffer
which can be used by extract_entropy(). On top of this remove the
timeout_del() call in dequeue_randomness() it does serve any meaningful
reason.
OK kettenis@ deraadt@ mpi@


# 1.227 04-Jun-2024 claudio

In dequeue_randomness() use an atomic instruction to increase the
rnd_event_cons. This way even concurrent calls to dequeue_randomness()
will use some different events.
OK deraadt@ djm@


Revision tags: OPENBSD_7_3_BASE OPENBSD_7_4_BASE OPENBSD_7_5_BASE
# 1.226 08-Mar-2023 guenther

Delete obsolete /* ARGSUSED */ lint comments.

ok miod@ millert@


# 1.225 03-Nov-2022 guenther

Style: always use *retval and never retval[0] in syscalls,
to reflect that retval is just a single return value.

ok miod@


# 1.224 13-Oct-2022 tb

Make comment match the code.

Since rnd.c r1.127, there is only one stirring polynomial.


Revision tags: OPENBSD_7_1_BASE OPENBSD_7_2_BASE
# 1.223 06-Feb-2022 rob

s/poll/pool


Revision tags: OPENBSD_6_9_BASE OPENBSD_7_0_BASE
# 1.222 06-Mar-2021 jsg

ansi


Revision tags: OPENBSD_6_8_BASE
# 1.221 15-Jun-2020 deraadt

slight copyright update regarding recent work


# 1.220 31-May-2020 dlg

introduce "cpu_rnd_messybits" for use instead of nanotime in dev/rnd.c.

rnd.c uses nanotime to get access to some bits that change quickly
between events that it can mix into the entropy pool. it doesn't
use nanotime to get a monotonically increasing set or ordered and
accurate timestamps, it just wants something with bits that change.

there's been discussions for years about letting rnd use a clock
that's super fast to read, but not necessarily accurate, but it
wasn't until recently that i figured out it wasn't interested in
time at all, so things like keeping a fast clock coherent between
cpu cores or correct according to ntp is unecessary. this means we
can just let rnd read the cycle counters on cpus and things will
be fine. cpus with cycle counters that vary in their speed and
arent kept consistent between cores may even be desirable in this
context.

so this is the first step in converting rnd.c to reading cycle
counter. it copies the nanotime backend to each arch, and they can
replace it with something MD as a second step later on.

djm@ suggested rnd_messybytes, but we landed on cpu_rnd_messybits.
thanks to visa for his eyes.
ok deraadt@ visa@
deraadt@ says he will help handle any MD fallout that occurs.


# 1.219 29-May-2020 deraadt

dev/rndvar.h no longer has statistical interfaces (removed during various
conversion steps). it only contains kernel prototypes for 4 interfaces,
all of which legitimately belong in sys/systm.h, which are already included
by all enqueue_randomness() users.


# 1.218 29-May-2020 deraadt

3 includes not needed


# 1.217 27-May-2020 deraadt

Update comment block at the top to describe (a) the ring damage logic,
and (b) the boot-time acceleration.


# 1.216 26-May-2020 deraadt

Rewrite the entropy enqueue ring to collect damage asyncronously, and adapt the
dequeue to mix a selection of "best" ring entries. Change the dequeue timeout
to exponentially backoff because excessive pool buffer generation is pointless
-- rekey's generally happen at 1.6MB and a long timeout, a lot of cpu cycles
were being wasted.

During boot-up (before timeouts work) aggressively consume enqueue damage
and rekey every time, to accelerate entropy injection into the chacha ring.

The goal is to compensate rapidly for weak seeding in unidentifiable
conditions, and ensure quality to arc4random() calls early in boot.
ok kettenis visa


# 1.215 25-May-2020 naddy

For large reads from /dev/random, use the arc4random_ctx_*() functions
instead of hand-rolling the same code to set up a temporary ChaCha
instance.
tweak/ok semarie@, ok deraadt@


# 1.214 25-May-2020 deraadt

Pass bootblock indicator RB_GOODRANDOM to random_start(). Future work
will frantically compensate.
ok kettenis


# 1.213 18-May-2020 deraadt

During the rekey operation, we feedback 1 word to the lowest level.
But it was a constant, that is really silly. Pass back the first
word from the middle layer.
ok visa


# 1.212 16-May-2020 deraadt

entropy_add_ptr and entropy_input_rotate are only used inside
enqueue_randomness(), so make them local static instead of global.


# 1.211 16-May-2020 deraadt

be more consistant about with using sizeof(object) rather than the constant
defining the [size]


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.227 04-Jun-2024 claudio

In dequeue_randomness() use an atomic instruction to increase the
rnd_event_cons. This way even concurrent calls to dequeue_randomness()
will use some different events.
OK deraadt@ djm@


Revision tags: OPENBSD_7_3_BASE OPENBSD_7_4_BASE OPENBSD_7_5_BASE
# 1.226 08-Mar-2023 guenther

Delete obsolete /* ARGSUSED */ lint comments.

ok miod@ millert@


# 1.225 03-Nov-2022 guenther

Style: always use *retval and never retval[0] in syscalls,
to reflect that retval is just a single return value.

ok miod@


# 1.224 13-Oct-2022 tb

Make comment match the code.

Since rnd.c r1.127, there is only one stirring polynomial.


Revision tags: OPENBSD_7_1_BASE OPENBSD_7_2_BASE
# 1.223 06-Feb-2022 rob

s/poll/pool


Revision tags: OPENBSD_6_9_BASE OPENBSD_7_0_BASE
# 1.222 06-Mar-2021 jsg

ansi


Revision tags: OPENBSD_6_8_BASE
# 1.221 15-Jun-2020 deraadt

slight copyright update regarding recent work


# 1.220 31-May-2020 dlg

introduce "cpu_rnd_messybits" for use instead of nanotime in dev/rnd.c.

rnd.c uses nanotime to get access to some bits that change quickly
between events that it can mix into the entropy pool. it doesn't
use nanotime to get a monotonically increasing set or ordered and
accurate timestamps, it just wants something with bits that change.

there's been discussions for years about letting rnd use a clock
that's super fast to read, but not necessarily accurate, but it
wasn't until recently that i figured out it wasn't interested in
time at all, so things like keeping a fast clock coherent between
cpu cores or correct according to ntp is unecessary. this means we
can just let rnd read the cycle counters on cpus and things will
be fine. cpus with cycle counters that vary in their speed and
arent kept consistent between cores may even be desirable in this
context.

so this is the first step in converting rnd.c to reading cycle
counter. it copies the nanotime backend to each arch, and they can
replace it with something MD as a second step later on.

djm@ suggested rnd_messybytes, but we landed on cpu_rnd_messybits.
thanks to visa for his eyes.
ok deraadt@ visa@
deraadt@ says he will help handle any MD fallout that occurs.


# 1.219 29-May-2020 deraadt

dev/rndvar.h no longer has statistical interfaces (removed during various
conversion steps). it only contains kernel prototypes for 4 interfaces,
all of which legitimately belong in sys/systm.h, which are already included
by all enqueue_randomness() users.


# 1.218 29-May-2020 deraadt

3 includes not needed


# 1.217 27-May-2020 deraadt

Update comment block at the top to describe (a) the ring damage logic,
and (b) the boot-time acceleration.


# 1.216 26-May-2020 deraadt

Rewrite the entropy enqueue ring to collect damage asyncronously, and adapt the
dequeue to mix a selection of "best" ring entries. Change the dequeue timeout
to exponentially backoff because excessive pool buffer generation is pointless
-- rekey's generally happen at 1.6MB and a long timeout, a lot of cpu cycles
were being wasted.

During boot-up (before timeouts work) aggressively consume enqueue damage
and rekey every time, to accelerate entropy injection into the chacha ring.

The goal is to compensate rapidly for weak seeding in unidentifiable
conditions, and ensure quality to arc4random() calls early in boot.
ok kettenis visa


# 1.215 25-May-2020 naddy

For large reads from /dev/random, use the arc4random_ctx_*() functions
instead of hand-rolling the same code to set up a temporary ChaCha
instance.
tweak/ok semarie@, ok deraadt@


# 1.214 25-May-2020 deraadt

Pass bootblock indicator RB_GOODRANDOM to random_start(). Future work
will frantically compensate.
ok kettenis


# 1.213 18-May-2020 deraadt

During the rekey operation, we feedback 1 word to the lowest level.
But it was a constant, that is really silly. Pass back the first
word from the middle layer.
ok visa


# 1.212 16-May-2020 deraadt

entropy_add_ptr and entropy_input_rotate are only used inside
enqueue_randomness(), so make them local static instead of global.


# 1.211 16-May-2020 deraadt

be more consistant about with using sizeof(object) rather than the constant
defining the [size]


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.226 08-Mar-2023 guenther

Delete obsolete /* ARGSUSED */ lint comments.

ok miod@ millert@


# 1.225 03-Nov-2022 guenther

Style: always use *retval and never retval[0] in syscalls,
to reflect that retval is just a single return value.

ok miod@


# 1.224 13-Oct-2022 tb

Make comment match the code.

Since rnd.c r1.127, there is only one stirring polynomial.


Revision tags: OPENBSD_7_1_BASE OPENBSD_7_2_BASE
# 1.223 06-Feb-2022 rob

s/poll/pool


Revision tags: OPENBSD_6_9_BASE OPENBSD_7_0_BASE
# 1.222 06-Mar-2021 jsg

ansi


Revision tags: OPENBSD_6_8_BASE
# 1.221 15-Jun-2020 deraadt

slight copyright update regarding recent work


# 1.220 31-May-2020 dlg

introduce "cpu_rnd_messybits" for use instead of nanotime in dev/rnd.c.

rnd.c uses nanotime to get access to some bits that change quickly
between events that it can mix into the entropy pool. it doesn't
use nanotime to get a monotonically increasing set or ordered and
accurate timestamps, it just wants something with bits that change.

there's been discussions for years about letting rnd use a clock
that's super fast to read, but not necessarily accurate, but it
wasn't until recently that i figured out it wasn't interested in
time at all, so things like keeping a fast clock coherent between
cpu cores or correct according to ntp is unecessary. this means we
can just let rnd read the cycle counters on cpus and things will
be fine. cpus with cycle counters that vary in their speed and
arent kept consistent between cores may even be desirable in this
context.

so this is the first step in converting rnd.c to reading cycle
counter. it copies the nanotime backend to each arch, and they can
replace it with something MD as a second step later on.

djm@ suggested rnd_messybytes, but we landed on cpu_rnd_messybits.
thanks to visa for his eyes.
ok deraadt@ visa@
deraadt@ says he will help handle any MD fallout that occurs.


# 1.219 29-May-2020 deraadt

dev/rndvar.h no longer has statistical interfaces (removed during various
conversion steps). it only contains kernel prototypes for 4 interfaces,
all of which legitimately belong in sys/systm.h, which are already included
by all enqueue_randomness() users.


# 1.218 29-May-2020 deraadt

3 includes not needed


# 1.217 27-May-2020 deraadt

Update comment block at the top to describe (a) the ring damage logic,
and (b) the boot-time acceleration.


# 1.216 26-May-2020 deraadt

Rewrite the entropy enqueue ring to collect damage asyncronously, and adapt the
dequeue to mix a selection of "best" ring entries. Change the dequeue timeout
to exponentially backoff because excessive pool buffer generation is pointless
-- rekey's generally happen at 1.6MB and a long timeout, a lot of cpu cycles
were being wasted.

During boot-up (before timeouts work) aggressively consume enqueue damage
and rekey every time, to accelerate entropy injection into the chacha ring.

The goal is to compensate rapidly for weak seeding in unidentifiable
conditions, and ensure quality to arc4random() calls early in boot.
ok kettenis visa


# 1.215 25-May-2020 naddy

For large reads from /dev/random, use the arc4random_ctx_*() functions
instead of hand-rolling the same code to set up a temporary ChaCha
instance.
tweak/ok semarie@, ok deraadt@


# 1.214 25-May-2020 deraadt

Pass bootblock indicator RB_GOODRANDOM to random_start(). Future work
will frantically compensate.
ok kettenis


# 1.213 18-May-2020 deraadt

During the rekey operation, we feedback 1 word to the lowest level.
But it was a constant, that is really silly. Pass back the first
word from the middle layer.
ok visa


# 1.212 16-May-2020 deraadt

entropy_add_ptr and entropy_input_rotate are only used inside
enqueue_randomness(), so make them local static instead of global.


# 1.211 16-May-2020 deraadt

be more consistant about with using sizeof(object) rather than the constant
defining the [size]


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.225 03-Nov-2022 guenther

Style: always use *retval and never retval[0] in syscalls,
to reflect that retval is just a single return value.

ok miod@


# 1.224 13-Oct-2022 tb

Make comment match the code.

Since rnd.c r1.127, there is only one stirring polynomial.


Revision tags: OPENBSD_7_1_BASE OPENBSD_7_2_BASE
# 1.223 06-Feb-2022 rob

s/poll/pool


Revision tags: OPENBSD_6_9_BASE OPENBSD_7_0_BASE
# 1.222 06-Mar-2021 jsg

ansi


Revision tags: OPENBSD_6_8_BASE
# 1.221 15-Jun-2020 deraadt

slight copyright update regarding recent work


# 1.220 31-May-2020 dlg

introduce "cpu_rnd_messybits" for use instead of nanotime in dev/rnd.c.

rnd.c uses nanotime to get access to some bits that change quickly
between events that it can mix into the entropy pool. it doesn't
use nanotime to get a monotonically increasing set or ordered and
accurate timestamps, it just wants something with bits that change.

there's been discussions for years about letting rnd use a clock
that's super fast to read, but not necessarily accurate, but it
wasn't until recently that i figured out it wasn't interested in
time at all, so things like keeping a fast clock coherent between
cpu cores or correct according to ntp is unecessary. this means we
can just let rnd read the cycle counters on cpus and things will
be fine. cpus with cycle counters that vary in their speed and
arent kept consistent between cores may even be desirable in this
context.

so this is the first step in converting rnd.c to reading cycle
counter. it copies the nanotime backend to each arch, and they can
replace it with something MD as a second step later on.

djm@ suggested rnd_messybytes, but we landed on cpu_rnd_messybits.
thanks to visa for his eyes.
ok deraadt@ visa@
deraadt@ says he will help handle any MD fallout that occurs.


# 1.219 29-May-2020 deraadt

dev/rndvar.h no longer has statistical interfaces (removed during various
conversion steps). it only contains kernel prototypes for 4 interfaces,
all of which legitimately belong in sys/systm.h, which are already included
by all enqueue_randomness() users.


# 1.218 29-May-2020 deraadt

3 includes not needed


# 1.217 27-May-2020 deraadt

Update comment block at the top to describe (a) the ring damage logic,
and (b) the boot-time acceleration.


# 1.216 26-May-2020 deraadt

Rewrite the entropy enqueue ring to collect damage asyncronously, and adapt the
dequeue to mix a selection of "best" ring entries. Change the dequeue timeout
to exponentially backoff because excessive pool buffer generation is pointless
-- rekey's generally happen at 1.6MB and a long timeout, a lot of cpu cycles
were being wasted.

During boot-up (before timeouts work) aggressively consume enqueue damage
and rekey every time, to accelerate entropy injection into the chacha ring.

The goal is to compensate rapidly for weak seeding in unidentifiable
conditions, and ensure quality to arc4random() calls early in boot.
ok kettenis visa


# 1.215 25-May-2020 naddy

For large reads from /dev/random, use the arc4random_ctx_*() functions
instead of hand-rolling the same code to set up a temporary ChaCha
instance.
tweak/ok semarie@, ok deraadt@


# 1.214 25-May-2020 deraadt

Pass bootblock indicator RB_GOODRANDOM to random_start(). Future work
will frantically compensate.
ok kettenis


# 1.213 18-May-2020 deraadt

During the rekey operation, we feedback 1 word to the lowest level.
But it was a constant, that is really silly. Pass back the first
word from the middle layer.
ok visa


# 1.212 16-May-2020 deraadt

entropy_add_ptr and entropy_input_rotate are only used inside
enqueue_randomness(), so make them local static instead of global.


# 1.211 16-May-2020 deraadt

be more consistant about with using sizeof(object) rather than the constant
defining the [size]


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.224 13-Oct-2022 tb

Make comment match the code.

Since rnd.c r1.127, there is only one stirring polynomial.


Revision tags: OPENBSD_7_1_BASE OPENBSD_7_2_BASE
# 1.223 06-Feb-2022 rob

s/poll/pool


Revision tags: OPENBSD_6_9_BASE OPENBSD_7_0_BASE
# 1.222 06-Mar-2021 jsg

ansi


Revision tags: OPENBSD_6_8_BASE
# 1.221 15-Jun-2020 deraadt

slight copyright update regarding recent work


# 1.220 31-May-2020 dlg

introduce "cpu_rnd_messybits" for use instead of nanotime in dev/rnd.c.

rnd.c uses nanotime to get access to some bits that change quickly
between events that it can mix into the entropy pool. it doesn't
use nanotime to get a monotonically increasing set or ordered and
accurate timestamps, it just wants something with bits that change.

there's been discussions for years about letting rnd use a clock
that's super fast to read, but not necessarily accurate, but it
wasn't until recently that i figured out it wasn't interested in
time at all, so things like keeping a fast clock coherent between
cpu cores or correct according to ntp is unecessary. this means we
can just let rnd read the cycle counters on cpus and things will
be fine. cpus with cycle counters that vary in their speed and
arent kept consistent between cores may even be desirable in this
context.

so this is the first step in converting rnd.c to reading cycle
counter. it copies the nanotime backend to each arch, and they can
replace it with something MD as a second step later on.

djm@ suggested rnd_messybytes, but we landed on cpu_rnd_messybits.
thanks to visa for his eyes.
ok deraadt@ visa@
deraadt@ says he will help handle any MD fallout that occurs.


# 1.219 29-May-2020 deraadt

dev/rndvar.h no longer has statistical interfaces (removed during various
conversion steps). it only contains kernel prototypes for 4 interfaces,
all of which legitimately belong in sys/systm.h, which are already included
by all enqueue_randomness() users.


# 1.218 29-May-2020 deraadt

3 includes not needed


# 1.217 27-May-2020 deraadt

Update comment block at the top to describe (a) the ring damage logic,
and (b) the boot-time acceleration.


# 1.216 26-May-2020 deraadt

Rewrite the entropy enqueue ring to collect damage asyncronously, and adapt the
dequeue to mix a selection of "best" ring entries. Change the dequeue timeout
to exponentially backoff because excessive pool buffer generation is pointless
-- rekey's generally happen at 1.6MB and a long timeout, a lot of cpu cycles
were being wasted.

During boot-up (before timeouts work) aggressively consume enqueue damage
and rekey every time, to accelerate entropy injection into the chacha ring.

The goal is to compensate rapidly for weak seeding in unidentifiable
conditions, and ensure quality to arc4random() calls early in boot.
ok kettenis visa


# 1.215 25-May-2020 naddy

For large reads from /dev/random, use the arc4random_ctx_*() functions
instead of hand-rolling the same code to set up a temporary ChaCha
instance.
tweak/ok semarie@, ok deraadt@


# 1.214 25-May-2020 deraadt

Pass bootblock indicator RB_GOODRANDOM to random_start(). Future work
will frantically compensate.
ok kettenis


# 1.213 18-May-2020 deraadt

During the rekey operation, we feedback 1 word to the lowest level.
But it was a constant, that is really silly. Pass back the first
word from the middle layer.
ok visa


# 1.212 16-May-2020 deraadt

entropy_add_ptr and entropy_input_rotate are only used inside
enqueue_randomness(), so make them local static instead of global.


# 1.211 16-May-2020 deraadt

be more consistant about with using sizeof(object) rather than the constant
defining the [size]


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.223 06-Feb-2022 rob

s/poll/pool


Revision tags: OPENBSD_6_9_BASE OPENBSD_7_0_BASE
# 1.222 06-Mar-2021 jsg

ansi


Revision tags: OPENBSD_6_8_BASE
# 1.221 15-Jun-2020 deraadt

slight copyright update regarding recent work


# 1.220 31-May-2020 dlg

introduce "cpu_rnd_messybits" for use instead of nanotime in dev/rnd.c.

rnd.c uses nanotime to get access to some bits that change quickly
between events that it can mix into the entropy pool. it doesn't
use nanotime to get a monotonically increasing set or ordered and
accurate timestamps, it just wants something with bits that change.

there's been discussions for years about letting rnd use a clock
that's super fast to read, but not necessarily accurate, but it
wasn't until recently that i figured out it wasn't interested in
time at all, so things like keeping a fast clock coherent between
cpu cores or correct according to ntp is unecessary. this means we
can just let rnd read the cycle counters on cpus and things will
be fine. cpus with cycle counters that vary in their speed and
arent kept consistent between cores may even be desirable in this
context.

so this is the first step in converting rnd.c to reading cycle
counter. it copies the nanotime backend to each arch, and they can
replace it with something MD as a second step later on.

djm@ suggested rnd_messybytes, but we landed on cpu_rnd_messybits.
thanks to visa for his eyes.
ok deraadt@ visa@
deraadt@ says he will help handle any MD fallout that occurs.


# 1.219 29-May-2020 deraadt

dev/rndvar.h no longer has statistical interfaces (removed during various
conversion steps). it only contains kernel prototypes for 4 interfaces,
all of which legitimately belong in sys/systm.h, which are already included
by all enqueue_randomness() users.


# 1.218 29-May-2020 deraadt

3 includes not needed


# 1.217 27-May-2020 deraadt

Update comment block at the top to describe (a) the ring damage logic,
and (b) the boot-time acceleration.


# 1.216 26-May-2020 deraadt

Rewrite the entropy enqueue ring to collect damage asyncronously, and adapt the
dequeue to mix a selection of "best" ring entries. Change the dequeue timeout
to exponentially backoff because excessive pool buffer generation is pointless
-- rekey's generally happen at 1.6MB and a long timeout, a lot of cpu cycles
were being wasted.

During boot-up (before timeouts work) aggressively consume enqueue damage
and rekey every time, to accelerate entropy injection into the chacha ring.

The goal is to compensate rapidly for weak seeding in unidentifiable
conditions, and ensure quality to arc4random() calls early in boot.
ok kettenis visa


# 1.215 25-May-2020 naddy

For large reads from /dev/random, use the arc4random_ctx_*() functions
instead of hand-rolling the same code to set up a temporary ChaCha
instance.
tweak/ok semarie@, ok deraadt@


# 1.214 25-May-2020 deraadt

Pass bootblock indicator RB_GOODRANDOM to random_start(). Future work
will frantically compensate.
ok kettenis


# 1.213 18-May-2020 deraadt

During the rekey operation, we feedback 1 word to the lowest level.
But it was a constant, that is really silly. Pass back the first
word from the middle layer.
ok visa


# 1.212 16-May-2020 deraadt

entropy_add_ptr and entropy_input_rotate are only used inside
enqueue_randomness(), so make them local static instead of global.


# 1.211 16-May-2020 deraadt

be more consistant about with using sizeof(object) rather than the constant
defining the [size]


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.222 06-Mar-2021 jsg

ansi


Revision tags: OPENBSD_6_8_BASE
# 1.221 15-Jun-2020 deraadt

slight copyright update regarding recent work


# 1.220 31-May-2020 dlg

introduce "cpu_rnd_messybits" for use instead of nanotime in dev/rnd.c.

rnd.c uses nanotime to get access to some bits that change quickly
between events that it can mix into the entropy pool. it doesn't
use nanotime to get a monotonically increasing set or ordered and
accurate timestamps, it just wants something with bits that change.

there's been discussions for years about letting rnd use a clock
that's super fast to read, but not necessarily accurate, but it
wasn't until recently that i figured out it wasn't interested in
time at all, so things like keeping a fast clock coherent between
cpu cores or correct according to ntp is unecessary. this means we
can just let rnd read the cycle counters on cpus and things will
be fine. cpus with cycle counters that vary in their speed and
arent kept consistent between cores may even be desirable in this
context.

so this is the first step in converting rnd.c to reading cycle
counter. it copies the nanotime backend to each arch, and they can
replace it with something MD as a second step later on.

djm@ suggested rnd_messybytes, but we landed on cpu_rnd_messybits.
thanks to visa for his eyes.
ok deraadt@ visa@
deraadt@ says he will help handle any MD fallout that occurs.


# 1.219 29-May-2020 deraadt

dev/rndvar.h no longer has statistical interfaces (removed during various
conversion steps). it only contains kernel prototypes for 4 interfaces,
all of which legitimately belong in sys/systm.h, which are already included
by all enqueue_randomness() users.


# 1.218 29-May-2020 deraadt

3 includes not needed


# 1.217 27-May-2020 deraadt

Update comment block at the top to describe (a) the ring damage logic,
and (b) the boot-time acceleration.


# 1.216 26-May-2020 deraadt

Rewrite the entropy enqueue ring to collect damage asyncronously, and adapt the
dequeue to mix a selection of "best" ring entries. Change the dequeue timeout
to exponentially backoff because excessive pool buffer generation is pointless
-- rekey's generally happen at 1.6MB and a long timeout, a lot of cpu cycles
were being wasted.

During boot-up (before timeouts work) aggressively consume enqueue damage
and rekey every time, to accelerate entropy injection into the chacha ring.

The goal is to compensate rapidly for weak seeding in unidentifiable
conditions, and ensure quality to arc4random() calls early in boot.
ok kettenis visa


# 1.215 25-May-2020 naddy

For large reads from /dev/random, use the arc4random_ctx_*() functions
instead of hand-rolling the same code to set up a temporary ChaCha
instance.
tweak/ok semarie@, ok deraadt@


# 1.214 25-May-2020 deraadt

Pass bootblock indicator RB_GOODRANDOM to random_start(). Future work
will frantically compensate.
ok kettenis


# 1.213 18-May-2020 deraadt

During the rekey operation, we feedback 1 word to the lowest level.
But it was a constant, that is really silly. Pass back the first
word from the middle layer.
ok visa


# 1.212 16-May-2020 deraadt

entropy_add_ptr and entropy_input_rotate are only used inside
enqueue_randomness(), so make them local static instead of global.


# 1.211 16-May-2020 deraadt

be more consistant about with using sizeof(object) rather than the constant
defining the [size]


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.221 15-Jun-2020 deraadt

slight copyright update regarding recent work


# 1.220 31-May-2020 dlg

introduce "cpu_rnd_messybits" for use instead of nanotime in dev/rnd.c.

rnd.c uses nanotime to get access to some bits that change quickly
between events that it can mix into the entropy pool. it doesn't
use nanotime to get a monotonically increasing set or ordered and
accurate timestamps, it just wants something with bits that change.

there's been discussions for years about letting rnd use a clock
that's super fast to read, but not necessarily accurate, but it
wasn't until recently that i figured out it wasn't interested in
time at all, so things like keeping a fast clock coherent between
cpu cores or correct according to ntp is unecessary. this means we
can just let rnd read the cycle counters on cpus and things will
be fine. cpus with cycle counters that vary in their speed and
arent kept consistent between cores may even be desirable in this
context.

so this is the first step in converting rnd.c to reading cycle
counter. it copies the nanotime backend to each arch, and they can
replace it with something MD as a second step later on.

djm@ suggested rnd_messybytes, but we landed on cpu_rnd_messybits.
thanks to visa for his eyes.
ok deraadt@ visa@
deraadt@ says he will help handle any MD fallout that occurs.


# 1.219 29-May-2020 deraadt

dev/rndvar.h no longer has statistical interfaces (removed during various
conversion steps). it only contains kernel prototypes for 4 interfaces,
all of which legitimately belong in sys/systm.h, which are already included
by all enqueue_randomness() users.


# 1.218 29-May-2020 deraadt

3 includes not needed


# 1.217 27-May-2020 deraadt

Update comment block at the top to describe (a) the ring damage logic,
and (b) the boot-time acceleration.


# 1.216 26-May-2020 deraadt

Rewrite the entropy enqueue ring to collect damage asyncronously, and adapt the
dequeue to mix a selection of "best" ring entries. Change the dequeue timeout
to exponentially backoff because excessive pool buffer generation is pointless
-- rekey's generally happen at 1.6MB and a long timeout, a lot of cpu cycles
were being wasted.

During boot-up (before timeouts work) aggressively consume enqueue damage
and rekey every time, to accelerate entropy injection into the chacha ring.

The goal is to compensate rapidly for weak seeding in unidentifiable
conditions, and ensure quality to arc4random() calls early in boot.
ok kettenis visa


# 1.215 25-May-2020 naddy

For large reads from /dev/random, use the arc4random_ctx_*() functions
instead of hand-rolling the same code to set up a temporary ChaCha
instance.
tweak/ok semarie@, ok deraadt@


# 1.214 25-May-2020 deraadt

Pass bootblock indicator RB_GOODRANDOM to random_start(). Future work
will frantically compensate.
ok kettenis


# 1.213 18-May-2020 deraadt

During the rekey operation, we feedback 1 word to the lowest level.
But it was a constant, that is really silly. Pass back the first
word from the middle layer.
ok visa


# 1.212 16-May-2020 deraadt

entropy_add_ptr and entropy_input_rotate are only used inside
enqueue_randomness(), so make them local static instead of global.


# 1.211 16-May-2020 deraadt

be more consistant about with using sizeof(object) rather than the constant
defining the [size]


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.220 31-May-2020 dlg

introduce "cpu_rnd_messybits" for use instead of nanotime in dev/rnd.c.

rnd.c uses nanotime to get access to some bits that change quickly
between events that it can mix into the entropy pool. it doesn't
use nanotime to get a monotonically increasing set or ordered and
accurate timestamps, it just wants something with bits that change.

there's been discussions for years about letting rnd use a clock
that's super fast to read, but not necessarily accurate, but it
wasn't until recently that i figured out it wasn't interested in
time at all, so things like keeping a fast clock coherent between
cpu cores or correct according to ntp is unecessary. this means we
can just let rnd read the cycle counters on cpus and things will
be fine. cpus with cycle counters that vary in their speed and
arent kept consistent between cores may even be desirable in this
context.

so this is the first step in converting rnd.c to reading cycle
counter. it copies the nanotime backend to each arch, and they can
replace it with something MD as a second step later on.

djm@ suggested rnd_messybytes, but we landed on cpu_rnd_messybits.
thanks to visa for his eyes.
ok deraadt@ visa@
deraadt@ says he will help handle any MD fallout that occurs.


# 1.219 29-May-2020 deraadt

dev/rndvar.h no longer has statistical interfaces (removed during various
conversion steps). it only contains kernel prototypes for 4 interfaces,
all of which legitimately belong in sys/systm.h, which are already included
by all enqueue_randomness() users.


# 1.218 29-May-2020 deraadt

3 includes not needed


# 1.217 27-May-2020 deraadt

Update comment block at the top to describe (a) the ring damage logic,
and (b) the boot-time acceleration.


# 1.216 26-May-2020 deraadt

Rewrite the entropy enqueue ring to collect damage asyncronously, and adapt the
dequeue to mix a selection of "best" ring entries. Change the dequeue timeout
to exponentially backoff because excessive pool buffer generation is pointless
-- rekey's generally happen at 1.6MB and a long timeout, a lot of cpu cycles
were being wasted.

During boot-up (before timeouts work) aggressively consume enqueue damage
and rekey every time, to accelerate entropy injection into the chacha ring.

The goal is to compensate rapidly for weak seeding in unidentifiable
conditions, and ensure quality to arc4random() calls early in boot.
ok kettenis visa


# 1.215 25-May-2020 naddy

For large reads from /dev/random, use the arc4random_ctx_*() functions
instead of hand-rolling the same code to set up a temporary ChaCha
instance.
tweak/ok semarie@, ok deraadt@


# 1.214 25-May-2020 deraadt

Pass bootblock indicator RB_GOODRANDOM to random_start(). Future work
will frantically compensate.
ok kettenis


# 1.213 18-May-2020 deraadt

During the rekey operation, we feedback 1 word to the lowest level.
But it was a constant, that is really silly. Pass back the first
word from the middle layer.
ok visa


# 1.212 16-May-2020 deraadt

entropy_add_ptr and entropy_input_rotate are only used inside
enqueue_randomness(), so make them local static instead of global.


# 1.211 16-May-2020 deraadt

be more consistant about with using sizeof(object) rather than the constant
defining the [size]


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.219 29-May-2020 deraadt

dev/rndvar.h no longer has statistical interfaces (removed during various
conversion steps). it only contains kernel prototypes for 4 interfaces,
all of which legitimately belong in sys/systm.h, which are already included
by all enqueue_randomness() users.


# 1.218 29-May-2020 deraadt

3 includes not needed


# 1.217 27-May-2020 deraadt

Update comment block at the top to describe (a) the ring damage logic,
and (b) the boot-time acceleration.


# 1.216 26-May-2020 deraadt

Rewrite the entropy enqueue ring to collect damage asyncronously, and adapt the
dequeue to mix a selection of "best" ring entries. Change the dequeue timeout
to exponentially backoff because excessive pool buffer generation is pointless
-- rekey's generally happen at 1.6MB and a long timeout, a lot of cpu cycles
were being wasted.

During boot-up (before timeouts work) aggressively consume enqueue damage
and rekey every time, to accelerate entropy injection into the chacha ring.

The goal is to compensate rapidly for weak seeding in unidentifiable
conditions, and ensure quality to arc4random() calls early in boot.
ok kettenis visa


# 1.215 25-May-2020 naddy

For large reads from /dev/random, use the arc4random_ctx_*() functions
instead of hand-rolling the same code to set up a temporary ChaCha
instance.
tweak/ok semarie@, ok deraadt@


# 1.214 25-May-2020 deraadt

Pass bootblock indicator RB_GOODRANDOM to random_start(). Future work
will frantically compensate.
ok kettenis


# 1.213 18-May-2020 deraadt

During the rekey operation, we feedback 1 word to the lowest level.
But it was a constant, that is really silly. Pass back the first
word from the middle layer.
ok visa


# 1.212 16-May-2020 deraadt

entropy_add_ptr and entropy_input_rotate are only used inside
enqueue_randomness(), so make them local static instead of global.


# 1.211 16-May-2020 deraadt

be more consistant about with using sizeof(object) rather than the constant
defining the [size]


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.217 27-May-2020 deraadt

Update comment block at the top to describe (a) the ring damage logic,
and (b) the boot-time acceleration.


# 1.216 26-May-2020 deraadt

Rewrite the entropy enqueue ring to collect damage asyncronously, and adapt the
dequeue to mix a selection of "best" ring entries. Change the dequeue timeout
to exponentially backoff because excessive pool buffer generation is pointless
-- rekey's generally happen at 1.6MB and a long timeout, a lot of cpu cycles
were being wasted.

During boot-up (before timeouts work) aggressively consume enqueue damage
and rekey every time, to accelerate entropy injection into the chacha ring.

The goal is to compensate rapidly for weak seeding in unidentifiable
conditions, and ensure quality to arc4random() calls early in boot.
ok kettenis visa


# 1.215 25-May-2020 naddy

For large reads from /dev/random, use the arc4random_ctx_*() functions
instead of hand-rolling the same code to set up a temporary ChaCha
instance.
tweak/ok semarie@, ok deraadt@


# 1.214 25-May-2020 deraadt

Pass bootblock indicator RB_GOODRANDOM to random_start(). Future work
will frantically compensate.
ok kettenis


# 1.213 18-May-2020 deraadt

During the rekey operation, we feedback 1 word to the lowest level.
But it was a constant, that is really silly. Pass back the first
word from the middle layer.
ok visa


# 1.212 16-May-2020 deraadt

entropy_add_ptr and entropy_input_rotate are only used inside
enqueue_randomness(), so make them local static instead of global.


# 1.211 16-May-2020 deraadt

be more consistant about with using sizeof(object) rather than the constant
defining the [size]


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.215 25-May-2020 naddy

For large reads from /dev/random, use the arc4random_ctx_*() functions
instead of hand-rolling the same code to set up a temporary ChaCha
instance.
tweak/ok semarie@, ok deraadt@


# 1.214 25-May-2020 deraadt

Pass bootblock indicator RB_GOODRANDOM to random_start(). Future work
will frantically compensate.
ok kettenis


# 1.213 18-May-2020 deraadt

During the rekey operation, we feedback 1 word to the lowest level.
But it was a constant, that is really silly. Pass back the first
word from the middle layer.
ok visa


# 1.212 16-May-2020 deraadt

entropy_add_ptr and entropy_input_rotate are only used inside
enqueue_randomness(), so make them local static instead of global.


# 1.211 16-May-2020 deraadt

be more consistant about with using sizeof(object) rather than the constant
defining the [size]


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.213 18-May-2020 deraadt

During the rekey operation, we feedback 1 word to the lowest level.
But it was a constant, that is really silly. Pass back the first
word from the middle layer.
ok visa


# 1.212 16-May-2020 deraadt

entropy_add_ptr and entropy_input_rotate are only used inside
enqueue_randomness(), so make them local static instead of global.


# 1.211 16-May-2020 deraadt

be more consistant about with using sizeof(object) rather than the constant
defining the [size]


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.212 16-May-2020 deraadt

entropy_add_ptr and entropy_input_rotate are only used inside
enqueue_randomness(), so make them local static instead of global.


# 1.211 16-May-2020 deraadt

be more consistant about with using sizeof(object) rather than the constant
defining the [size]


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.210 15-May-2020 deraadt

Describe the purpose of add_entropy_words() in simpler terms.


# 1.209 15-May-2020 deraadt

The description of the enqueue_randomness() input parameter was crazy untrue.


# 1.208 15-May-2020 deraadt

Explain enqueue_randomness() better. It is the supply-entropy function,
and change wording from 'entropy queue', what we have is a ring which
collects 'damage' from successive calls until drawn down


# 1.207 15-May-2020 deraadt

The long explanation for CRC stirring isn't helping. If anything
it suggests we should reconsider this mechanism and do something
simpler... delete the explanation for now.


# 1.206 15-May-2020 deraadt

The main comment block from 1996 has become highly inaccurate and
misleading, so rewrite it.

The interesting parts are bootblock-seeding from file + hwrng,
arc4random() being available incredibly early, and seperate timeouts
to pull entropy data forward into a stir of the chacha state (one for
entropy ring crc whitening into a buffer, the 2nd for buffer folding
into the chacha)

Now that it is better documented, I can try to improve each component.


# 1.205 15-May-2020 deraadt

remove unneccessary include files


Revision tags: OPENBSD_6_7_BASE
# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.204 06-Mar-2020 tobhe

Make sure 'ts' is initialized.

ok deraadt@


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.203 02-Mar-2020 deraadt

previous commit accidentally aliased two unique timeouts
hit by millert


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.202 01-Mar-2020 deraadt

rename functions and types unrelated to the higher-level arc4 API
ok djm markus


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.201 20-Feb-2020 visa

Replace field f_isfd with field f_flags in struct filterops to allow
adding more filter properties without cluttering the struct.

OK mpi@, anton@


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.200 31-Dec-2019 visa

Use C99 designated initializers with struct filterops. In addition,
make the structs const so that the data are put in .rodata.

OK mpi@, deraadt@, anton@, bluhm@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.199 28-Apr-2018 jasper

replace add_*_randomness with enqueue_randomness()

this gets rid of the source annotation which doesn't really add
anything other than adding complexitiy. randomess is generally
good enough that the few extra bits that the source type would
add are not worth it.

ok mikeb@ deraadt@


Revision tags: OPENBSD_6_3_BASE
# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.198 09-Feb-2018 deraadt

Situation occur where bootloader cannot supply kernel with early
random data. But a new source of entropy arrived a few months ago
-- KARL generates highly disturbed images for some kernels (well,
not for bsd.rd)
This assumes the tail of text (just before etext[]) is readable.
We are trying to use a portable symbol name, and also avoid reading
a locore0 which has been unmapped...
ok mortimer


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.197 08-Feb-2018 mortimer

Do not hardcode key length. Pointed out by jsing@

ok deraadt@


# 1.196 08-Feb-2018 mortimer

Use a temporary chacha instance to fill large randomdata sections. Avoids
grabbing the rnglock repeatedly.

ok deraadt@ djm@


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.


# 1.195 26-Nov-2017 mikeb

Don't mention XOR as a mix-in function since addition is done since 1.180


# 1.194 19-Nov-2017 mikeb

Remove interlocks between producers and consumers of randomness data

A lot of randomness event producers are executed in the interrupt
context increasing the time spent in the interrupt handler resulting
in extra costs when adding randomness data to the pool. However, in
practice randomness event producers require interlocking between each
other, but not with with consumers due to the opportunistic nature of
event consumers.

To be able to take advantage of this idea, the ring buffer indexing
is now done with two free running producer and consumer counters modulo
power of 2 size of the ring buffer.

With input from and OK visa, tb, jasper


Revision tags: OPENBSD_6_2_BASE
# 1.193 30-Jul-2017 deraadt

clang (and newer gcc at high -O) are unaware that objects placed in strange
sections, such as __attribute__((section(".openbsd.randomdata"))), may be
non-zero. In combination with "const" or "static" the compiler becomes even
more sure nothing can influence the object and assumes the value will be 0.
A few optimizations later, a security requirement has been removed.

Until a better annotation arrives in compilers, be warned: Do not mix
const or static with these random objects, you won't get what you want.
Spotted in a regression test by bluhm, long discussion with kettenis.


Revision tags: OPENBSD_6_1_BASE
# 1.192 15-Mar-2017 deraadt

spelling and whitespace


# 1.191 08-Dec-2016 deraadt

fix spelling errors and typos, from Michael W. Bombardieri


# 1.190 18-Oct-2016 deraadt

when openbsd.randomdata was made readonly, the proto seed copy got done
too late, leading to poor rng in the kernel early on. a behavioural
artifact in vmm spotted the issue.
ok tedu guenther mlarkin


# 1.189 07-Oct-2016 tedu

another unused variable bites the dust. spotted by deraadt


# 1.188 07-Oct-2016 tedu

the old time delta code is no longer used. nothing reads these values.
remove it another relic of the superstitious past.
ok deraadt millert mikeb


# 1.187 23-Sep-2016 deraadt

kern.arandom no longer exists
from rob pierce


# 1.186 22-Sep-2016 deraadt

Stop pushing version & cfdata into as entropy, since the contents are
known and we rely on the bootpath to prime us anyways.
This also solves the issue raised by kettenis, of version potentially
being non-word aligned
ok kettenis djm


# 1.185 04-Sep-2016 kettenis

Rototil the _rs_clearseed() function once more such that we don't map pages
beyond the end of .text/.rodata.

ok deraadt@


# 1.184 03-Sep-2016 kettenis

Since the initial entropy pool is 8192 bytes, we need three pages to create
the alias mapping when clearing it, since there is no guarantee the pool is
page aligned.

ok deraadt@


# 1.183 01-Sep-2016 deraadt

openbsd.randomdata became RO in userland due to the RELRO work. We should
also do so in the kernel, which gains us RO ssp cookie, which will prevent
spraying attacks.

The random layer was openbsd.randomdata annotating working entropy/chacha
buffers which in turn required them to be RW. To make that work again,
so we need to copy RO seeds to RW working buffers, and later clear the
RO seed buffers afterwards using a temporary RW mapping.

help & ok kettenis, ok guenther


Revision tags: OPENBSD_6_0_BASE
# 1.182 15-Jul-2016 tom

Remove unused re_nbits from dev/rnd.c

"another leftover of the bean counter"

od tedu@ deraadt@


# 1.181 23-May-2016 deraadt

remove the sysctl kern.random counters, since none of the remaining
ones are capable of giving valuable works vs does-not-work evidence.
ok tedu


# 1.180 17-May-2016 tedu

Change the random event buffer from a queue to an endless ring. This way
we don't drop any events when the queue is full. They are instead mixed
into previous events.
The mixing function selected is addition instead of xor to reduce the
possibility that new values effectively erase existing ones.
Convert some types to u_int to ensure defined overflow.
ok deraadt djm


Revision tags: OPENBSD_5_9_BASE
# 1.179 19-Feb-2016 stefan

Right shift by an amount larger than width of type is undefined behavior.
Pointed out by Martin Natano, slightly tweaked by me.

ok deraadt@


# 1.178 08-Jan-2016 stefan

Use uiomove() instead of uiomovei().
Diff from Martin Natano, thanks!

ok kettenis@, deraadt@


# 1.177 28-Dec-2015 tedu

use ulmin when looking at uio_resid to prevent wrapping around.
from Martin Natano (and also reported by Stefan Kempf)


# 1.176 27-Oct-2015 mikeb

Sync chacha_ivsetup to the version in ssh so that we could
specify custom counter value when setting up Chacha context.

ok reyk djm


Revision tags: OPENBSD_5_8_BASE
# 1.175 25-May-2015 deraadt

missing word in comment; Kyle Milz


# 1.174 04-May-2015 jsg

use the size of the buffer not the pointer in resume_randomness()
ok djm@ miod@ deraadt@


# 1.173 14-Mar-2015 jsg

Remove some includes include-what-you-use claims don't
have any direct symbols used. Tested for indirect use by compiling
amd64/i386/sparc64 kernels.

ok tedu@ deraadt@


Revision tags: OPENBSD_5_7_BASE
# 1.172 17-Feb-2015 tedu

the rnd event ringbuf calculations aren't correct, which may result in
failure to fire the collection timeout. discovered by markus.
the order of events here doesn't actually matter, so switch to a simple
stack, which is easier to understand. ok markus


# 1.171 10-Feb-2015 miod

First step towards making uiomove() take a size_t size argument:
- rename uiomove() to uiomovei() and update all its users.
- introduce uiomove(), which is similar to uiomovei() but with a size_t.
- rewrite uiomovei() as an uiomove() wrapper.
ok kettenis@


# 1.170 07-Feb-2015 deraadt

New framework that allows hibernate to pass in entropy from it's fresh
boot.
ok mlarkin


# 1.169 27-Jan-2015 dlg

remove the second void * argument on tasks.

when workqs were introduced, we provided a second argument so you
could pass a thing and some context to work on it in. there were
very few things that took advantage of the second argument, so when
i introduced pools i suggested removing it. since tasks were meant
to replace workqs, it was requested that we keep the second argument
to make porting from workqs to tasks easier.

now that workqs are gone, i had a look at the use of the second
argument again and found only one good use of it (vdsp(4) on sparc64
if you're interested) and a tiny handful of questionable uses. the
vast majority of tasks only used a single argument. i have since
modified all tasks that used two args to only use one, so now we
can remove the second argument.

so this is a mechanical change. all tasks only passed NULL as their
second argument, so we can just remove it.

ok krw@


# 1.168 23-Dec-2014 tedu

not necessary to zero hash context; the hash final functions all do that.


# 1.167 23-Dec-2014 tedu

tmp is a bad name for a shactx


# 1.166 19-Dec-2014 tedu

rename buffer to digest, more clear. ok deraadt


# 1.165 19-Dec-2014 tedu

sha512 produces enough output, we can simplify extraction by not looping.
ok deraadt djm


# 1.164 18-Dec-2014 deraadt

Create a suspend/resume infrastructure for the RNG. At suspend time,
process all queued entropy and create a brand new pool to prevent
backtracking upon resume. At resume time, process the entropy queue
(since other resume code paths which run earlier can enqueue entropy)
and force all higher to reseed.
ok reyk djm


# 1.163 24-Oct-2014 tedu

obvious sizes for free


# 1.162 20-Oct-2014 tedu

typo; deraadt


# 1.161 20-Oct-2014 tedu

use SHA512 to hash entropy instead of MD5


# 1.160 15-Sep-2014 tedu

update comments to reflect chacha20. from Max Fillinger


Revision tags: OPENBSD_5_6_BASE
# 1.159 17-Jul-2014 tedu

zero entropy buf


# 1.158 12-Jul-2014 tedu

add a size argument to free. will be used soon, but for now default to 0.
after discussions with beck deraadt kettenis.


# 1.157 14-Jun-2014 deraadt

Change return value of getentropy() to int 0 for success. Maximum
buffersize is enforced strictly, this supplies sufficient entropy
payload to act as seed material. Discourage general use of this
API, but lock down this function name as the go-to for userland
PRNG seeding. Improve documentation.
ok miod matthew


# 1.156 13-Jun-2014 deraadt

Add new getentropy() system call. Code and pressure from matthew.
I accepted that he's right (again) to seperate this out from heavy
sysctl API and this will simply a variety of things. Functionname
is not used by anyone in the ports tree, so we guess we can use it.
Shocking that no application has a function called this.
ok matthew & others who pushed him to start this early on


Revision tags: OPENBSD_5_5_BASE
# 1.155 05-Feb-2014 tedu

tiny style adjustments


# 1.154 22-Jan-2014 jsing

Emit a warning if no entropy was supplied by the boot loader.

ok deraadt@


# 1.153 19-Jan-2014 deraadt

Refactor rnd startup so arc4random/arc4random_buf can create a chacha state
on first call, very early on, from boot-supplied entropy, then feed from
that. Later when we have more subsystems ready, the main() can properly
initialize the entropy-driven model. Lots of discussion with mikeb.
ok kettenis markus mikeb


# 1.152 19-Jan-2014 deraadt

With the earlier initialization of the random subsystem, random_hostseed()
is no longer providing significant value. The random subsystem is in
pretty good state, and moments later userland will feed the dmesg.
ok jsing


# 1.151 19-Jan-2014 deraadt

In random_start() we can assume the msg buffer is mapped, all systems do
it at startup, or in cpu_startup(). Improve comments to explain what is
happening here.
ok kettenis jsing


# 1.150 28-Dec-2013 deraadt

Put the entropy_pool[] into the ELF .openbsd.randomdata segment.
Also allow random_init() to be called later, by moving a few
entropy control initializions into the lower-level _rs_seed() layer.
tested by jsing, phessler and a few others


# 1.149 22-Dec-2013 deraadt

spacing; Loganaden Velvindron


# 1.148 11-Dec-2013 guenther

Revert change to sha256: ramdisks don't build with this and the obvious
conf/files change isn't enough due to size limits


# 1.147 11-Dec-2013 tedu

update a few RC4 references to ChaCha. thanks sthen


# 1.146 11-Dec-2013 tedu

md5 smells bad. switch to sha256. ok deraadt matthew mikeb


# 1.145 02-Nov-2013 markus

replace rc4 with ChaCha20 here, too; ok djm, tedu, deraadt


# 1.144 30-Oct-2013 dlg

replace workq_add_task with the task api.

this guarantees the reliability of the arc4_reinit task being run by not
relying on a pool to give us memory in an interrupt context.

ok mpi@


Revision tags: OPENBSD_5_4_BASE
# 1.143 09-Jul-2013 blambert

Fix a pair of aesthetic nits in dev/rnd.c:

fix language (feed -> fed) in a comment
16 -> MD5_DIGEST_LENGTH for legibility

No change to resulting object file.

ok djm@


# 1.142 25-Mar-2013 markus

reseed the random pool with 'dmesg' when more devices are attached
from hshoexer@; ok tedu@, "looks good" deraadt@


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.141 24-Jun-2012 matthew

Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the
same on both ILP32 and LP64 architectures, and also slightly faster on
LP64 architectures by using a 32-bit remainder instead of a 64-bit
remainder.

Pointed out by Jorden Verwer on tech@
ok deraadt; no objections from djm or otto


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.140 06-Jul-2011 nicm

Add a new kqfilter for random which returns ARC4_MAIN_MAX_BYTES for read
and POOLBYTES for write.

looks right to deraadt


Revision tags: OPENBSD_4_9_BASE
# 1.139 11-Jan-2011 djm

bring back carrying over state from the previous RC4 instance when
rekeying; ok deraadt@


# 1.138 11-Jan-2011 tedu

all the bzeros in rnd are important, use explicit_bzero


# 1.137 10-Jan-2011 deraadt

update the documentation regarding the *4 vs *6 decision for early RC4
stream discard. this continues to be under discussion... at least this
moves the large-buffer transactions to using a *6 discard
discussed at length with djm and kjell


# 1.136 10-Jan-2011 deraadt

move comment block regarding ARC4_MAIN_MAX_BYTES


# 1.135 10-Jan-2011 tedu

randomread does its own rekeying now, so we don't need the large buf function.
ok deraadt


# 1.134 10-Jan-2011 deraadt

OK, this is getting silly, but we might as well zero the entropy buffer
supplied by root (it can be large enough to overwhelm the entropy buffer,
and we are doing a re-key almost immediately)


# 1.133 10-Jan-2011 deraadt

zero another intermediate key storage area


# 1.132 09-Jan-2011 deraadt

be more careful with nanotime() calls in early entropy storage, since
at least sparc may not have the clock mapped (found by miod).
while here, protect some more timeout_*() calls with timeout_initialized()


# 1.131 08-Jan-2011 deraadt

split randomattach into random_init() and random_start(), so that we
can make attempts to load 'entropy' into the RC4.
ok miod ariane


# 1.130 08-Jan-2011 deraadt

spaces


# 1.129 08-Jan-2011 deraadt

switch back from PAGE_SIZE for the sake of sparc


# 1.128 08-Jan-2011 tedu

destatic. ok deraadt


# 1.127 07-Jan-2011 tedu

some minor improvements to rnd.
1. only support pool words == 2048.
2. define the amount of key we use.
3. define the amount of rc4 we skip.
4. use arc4random_buf instead of reimplementing inline.
5. bzero some more "secrets".
ok deraadt djm


# 1.126 07-Jan-2011 deraadt

substantial rewrite. put a very thin mutex at the entropy-collection
side so that entropy events can come in from any kernel context. place
a 2nd very thin mutex at the call-down path as well, so that any context can
request random data. in the middle, meet with a bcopy that has no mutex,
but copying unlocked data is actually a benefit.
move the pool->MD5->RC4init sequence into a workq driven from a timeout,
so that we can do all the heavy work without any mutex held or IPL; only
grab the 2nd mutex to swap to a new RC4 state. (this workq design from tedu)
ok dlg tedu


# 1.125 07-Jan-2011 deraadt

since randomwrite() also has no blocking operations at all, we need to
do a yield, otherwise an accidental cat by root into /dev/random kind
of makes your machine hurt a lot.


# 1.124 06-Jan-2011 deraadt

For very large operations in randomread(), use a local rc4 instance
much like arc4random_buf_large does, but without re-initializing it
every 8K.
ok tedu


# 1.123 06-Jan-2011 deraadt

make all /dev/*random nodes respond; in fact, don't even worry about
the minor number at all. The chances of an application ignoring the
error on /dev/random are *greater* than the risk of an application
getting bad data from it.
ok dlg tedu kjell


# 1.122 04-Jan-2011 deraadt

in arc4_stir() only grab 64 bytes from the MD5 output. Grabbing more
does not substantially increase the quality of the RC4 state. These
days we may have lots more userland libc's initializing themselves,
or lots of largebuf kernel calls which re-initialize their own RC4,
and thus deplete the MD5 more than originally intended.
discussed at length with tedu, djm, kjell and kettenis
ok kettenis


# 1.121 01-Jan-2011 deraadt

Do not fold the MD5 in half. This might have made sense to someone when
we were feeding the MD5 output direct to consumers, but now we only feed
the RC4, so the effect is to throw away half of the stretched data.
ok tedu djm, initial discussion started by kjell


# 1.120 01-Jan-2011 deraadt

comment cleanup


# 1.119 31-Dec-2010 deraadt

make randomattach do the parts of it's job in the right order, then move
it to where it belongs


# 1.118 31-Dec-2010 deraadt

cleanup the ioctl function


# 1.117 31-Dec-2010 deraadt

delete includes we do not need


# 1.116 31-Dec-2010 deraadt

further improvements describing what we are doing


# 1.115 31-Dec-2010 deraadt

all random nodes have been arc4-based for a while, so none of them ever
block. the kq and poll code should have been replaced with "selltrue"
type code a while ago.
with and ok nicm


# 1.114 30-Dec-2010 deraadt

be more cynical about boot-time entropy, and fold time and entropy data in.
ok djm


# 1.113 29-Dec-2010 deraadt

knf


# 1.112 29-Dec-2010 deraadt

Since there is only one random_state, we can access it directly without
the rs-> song and dance. Exactly the same diff was written by djm.


# 1.111 29-Dec-2010 deraadt

arc4random_count is not used; other things inside rndstats do the accounting


# 1.110 29-Dec-2010 deraadt

the rnd_debug stuff was not useful


# 1.109 29-Dec-2010 deraadt

kill RND_ARND_OLD, and decrease RND_NODEV to account for it; ok djm


# 1.108 29-Dec-2010 deraadt

Remove the get_random_bytes() API.
ok kjell djm


# 1.107 29-Dec-2010 deraadt

the random ioctl stuff is not very useful. I want to see all the
non-essential parts of rnd.c removed so that we can keep our eye on
what the code should be doing.
ok tedu who had a similar diff in the past


# 1.106 24-Dec-2010 deraadt

try to update the monster comment at the top of this file to explain
what it is we are doing
ok djm


# 1.105 22-Dec-2010 deraadt

rewrite randomwrite() for clarity after discussion with mikeb
ok djm


# 1.104 21-Nov-2010 tedu

adding timer randomness in ioctl doesn't really help and looks suspicious.
ok deraadt


# 1.103 02-Oct-2010 tedu

remove support for srandom and urandom. direct everyone to arandom instead.
we do this to prevent people from opening a device that sounds good, but
doesn't have the properties they really need.
ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.102 20-Apr-2010 tedu

remove proc.h include from uvm_map.h. This has far reaching effects, as
sysctl.h was reliant on this particular include, and many drivers included
sysctl.h unnecessarily. remove sysctl.h or add proc.h as needed.
ok deraadt


Revision tags: OPENBSD_4_7_BASE
# 1.101 09-Nov-2009 nicm

Every selwakeup() should have a matching KNOTE() (even if kqueue isn't
supported it doesn't do any harm), so put the KNOTE() in selwakeup() itself and
remove it from any occurences where both are used, except one for kqueue itself
and one in sys_pipe.c (where the selwakeup is under a PIPE_SEL flag).

Based on a diff from tedu.

ok deraadt


Revision tags: OPENBSD_4_6_BASE
# 1.100 05-Jun-2009 guenther

Sanity check: we overrun the rnd_ed[] array if nbits is 32, but that
should be impossible given the multi-order delta logic

ok deraadt@


Revision tags: OPENBSD_4_5_BASE
# 1.99 15-Dec-2008 djm

remove i386-only inline assembler roll() function; gcc optimises the
equivalent C code into a rol instruction anyway (confirmed with
objdump -d); "nuke it" weingart@


# 1.98 24-Nov-2008 deraadt

extra decl not needed; spotted by djm


# 1.97 24-Nov-2008 deraadt

allow entropy to be queued before randomattach() is called
worked on with djm


# 1.96 24-Nov-2008 mpf

Seed the random pool with the dmesg buffer at randomattach().
This lets early arc4random() calls to return at least non-uniqe values
on different machines. The dmesg will have different MAC addresses,
etc. Also ignore the entropy count in arc4_stir, and just take what's
there. sizeof(struct timeval) should be sizof(struct timespec)
This was forgotten when we switched to nanotime.
With help from mickey.
OK djm@, deraadt@


# 1.95 15-Oct-2008 djm

kernel/5592: yield() between copying out large chunks of random data to
userspace - mitigates an effective DoS since generating these can hog
the CPU at splhigh()

feedback & ok tedu@ deraadt@


# 1.94 10-Oct-2008 deraadt

minor 3 was /dev/prandom, which used random(). make that use the
arandom code, just like minor 4. in fact, make them act exactly
the same.


# 1.93 10-Sep-2008 blambert

Convert timeout_add() calls using multiples of hz to timeout_add_sec()

Really just the low-hanging fruit of (hopefully) forthcoming timeout
conversions.

ok art@, krw@


Revision tags: OPENBSD_4_4_BASE
# 1.92 11-Jun-2008 djm

correct long since bitrotted comments

POOL_TAP5 is always 1 so unifdef it

no binary change


# 1.91 10-Jun-2008 djm

reorder functions and variables in rnd.c so they are more logically
arranged. They are now layed out in four sections:

1. Master entropy pool maintenance (add_entropy_words & extract entropy)
2. Entropy crediting (add_*_randomness backend)
3. Exported kernel API: arc4random() and friends
4. /dev/*random char devices


# 1.90 09-Jun-2008 djm

simplify math for arc4random_uniform() suggested by
Jinmei_Tatuya AT isc.org via jakob@

empirically verified for entire domain of upper_bound


# 1.89 09-Jun-2008 djm

rename arc4random_bytes => arc4random_buf to match libc's nicer name;
ok deraadt@


# 1.88 04-Jun-2008 djm

fix math screwup that reintroduced a bias for upper_bounds in range
(2^30,2^31). Nothing in the tree yet requests random numbers bounded
by this range.

report jakob!deraadt; ok deraadt@


Revision tags: OPENBSD_4_3_BASE
# 1.87 02-Mar-2008 djm

Add a arc4random_uniform() that returns a uniformly distributed number
in the range 0 <= x < upper_bound

Please use this new API instead of "arc4random() % upper_bound", as it
avoids the "modulo bias" that favours small results when upper_bound is
not a power of two.

feedback deraadt@ mcbride@; ok deraadt@


# 1.86 29-Dec-2007 dlg

switch from spls to mutexes for protecting the random state.

ok tedu@ djm@


# 1.85 15-Oct-2007 djm

zero the right object, not some hunk of stack; ok henric@


# 1.84 15-Oct-2007 djm

Switch arc4random to using routines from crypto/arc4.[ch], and rework
spl swizzling so we go to splhigh and back once per request instead of
once per byte.
Service large requests for arc4random_bytes using an independently keyed
generator rather than hogging the main one (at splhigh).
feedback from henric@; ok deraadt@


# 1.83 09-Oct-2007 gilles

MALLOC -> malloc

ok krw@


Revision tags: OPENBSD_4_2_BASE
# 1.82 17-Jun-2007 jasper

ansify/de-register

ok miod@


# 1.81 10-Apr-2007 miod

``it's'' -> ``its'' when the grammar gods require this change.


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.80 11-Apr-2006 djm

make this use nanotime, not microtime; ok mickey@


Revision tags: OPENBSD_3_8_BASE OPENBSD_3_9_BASE
# 1.79 31-Jul-2005 djm

use monotonic time for repeat event detections; feedback and ok deraadt@


# 1.78 07-Jul-2005 djm

fix accounting bug on extraction - we were incorrectly subtracting many times
the amount requested from the pool's entropy estimate; ok mickey@ deraadt@


# 1.77 27-May-2005 ho

De-inline a couple of long functions, which also makes them debugger-visible. 'makes sense' mickey@


Revision tags: OPENBSD_3_7_BASE
# 1.76 04-Mar-2005 robert

Fix a variable name in a comment; from Clint <cruoho@gmail.com>; ok tdeval@


# 1.75 27-Jan-2005 mickey

poll can ever deny reads for srandom only; millert@ ok


# 1.74 27-Jan-2005 millert

In randompoll() the write check was overriding the results of the read check.
OK mickey@


Revision tags: OPENBSD_3_6_BASE
# 1.73 21-Jul-2004 mickey

branches: 1.73.2;
remove a few inlines from funcs that are used more than once and make code bigger; asked by art@


# 1.72 06-Jul-2004 mickey

use MALLOC/FREE for fixed size buffer allocations


# 1.71 05-Jul-2004 millert

Allocate buffers in randomread and randomwrite via malloc instead
of from the stack. Keeps us from running out of kernel stack during
stack-heavy networking load. The bug manifests as a panic during
bootup with an fpu-related assertion failure on i386.
Fix from Christopher Pascoe; commit requested by deraadt@


Revision tags: SMP_SYNC_A SMP_SYNC_B
# 1.70 07-May-2004 millert

Replace RSA-derived md5 code with code derived from Colin Plumb's PD version.
This moves md5.c out of libkern and into sys/crypto where it belongs (as
requested by markus@). Note that md5.c is still mandatory (dev/rnd.c uses it).
Verified with IPsec + hmac-md5 and tcp md5sig. OK henning@ and hshoexer@


# 1.69 02-Apr-2004 mickey

repair linuxisms tested on hppa, sparc, vax and i386; from Sven Dehmlow <sven_dehmlow@gmx.de>


# 1.68 02-Apr-2004 mickey

kill _8 api completely


Revision tags: OPENBSD_3_5_BASE
# 1.67 15-Mar-2004 mickey

branches: 1.67.2;
per popular demand panic on premature arc4 initializations (would have paniced anyway elsewhere)


# 1.66 03-Nov-2003 tedu

add arc4random_bytes. input ok mickey@


# 1.65 21-Oct-2003 jmc

typos from Tom Cosgrove;


# 1.64 23-Sep-2003 millert

Replace select backends with poll backends. selscan() and pollscan()
now call the poll backend. With this change we implement greater
poll(2) functionality instead of emulating it via the select backend.
Adapted from NetBSD and including some changes from FreeBSD.
Tested by many, deraadt@ OK


Revision tags: OPENBSD_3_4_BASE
# 1.63 15-Aug-2003 tedu

branches: 1.63.2;
change arguments to suser. suser now takes the process, and a flags
argument. old cred only calls user suser_ucred. this will allow future
work to more flexibly implement the idea of a root process. looks like
something i saw in freebsd, but a little different.
use of suser_ucred vs suser in file system code should be looked at again,
for the moment semantics remain unchanged.
review and input from art@ testing and further review miod@


Revision tags: OPENBSD_3_3_BASE UBC_SYNC_A
# 1.62 25-Nov-2002 mickey

protect the arc4_getbyte() w/ an splhigh since
there by multiple pathways, where it worked
until read from userland in big buffers and some luck.
does not cause a memory trashing, but rather may
mess up the arc4 state such that it will not generate
one particular value until a stir. sigh.
was reported by multiple people over some time.


# 1.61 11-Nov-2002 mickey

grammar fixens from Andrey Smagin


Revision tags: OPENBSD_3_2_BASE UBC_SYNC_B
# 1.60 19-Jun-2002 mickey

add kqfilter for random, regress is coming


# 1.59 14-Jun-2002 mickey

from freebsd:
Throw away the first N words of output, as suggested in the
paper "Weaknesses in the Key Scheduling Algorithm of RC4"
by Fluher, Mantin, and Shamir. (N = 256 in our case.)


# 1.58 27-May-2002 deraadt

kill unused arc4random_8() API


Revision tags: OPENBSD_3_1_BASE
# 1.57 01-Apr-2002 mickey

a few typos from pechkin


# 1.56 21-Mar-2002 mickey

on extract: better spl granularity, make sure pool is updated between runs; later pt out by camield@


# 1.55 14-Mar-2002 millert

First round of __P removal in sys


# 1.54 31-Jan-2002 mickey

drop the low drop bits number to 10 drop


# 1.53 10-Jan-2002 mickey

return ENOTTY not EINVAL in default: in *ioctl()


# 1.52 03-Jan-2002 nordin

Restore entropy_count calculation. mickey@ ok


# 1.51 29-Dec-2001 mickey

finer spl granularity, allowing ints to happen; pointed out and tested on vax by hugh@


Revision tags: OPENBSD_3_0_BASE UBC_BASE
# 1.50 24-Sep-2001 mickey

branches: 1.50.4;
there was a possible overrun in prev folding length fix.
however i was lucky enough so it worked.
anyway, this fixes the problem and seems to run very
much alright on sparc at least.


# 1.49 23-Sep-2001 mickey

oops, fix the after folding sizes


# 1.48 24-Jun-2001 mickey

only run timeout if stirring happened, save cycles for mass energy conservation


# 1.47 08-May-2001 mickey

reapply 1.39 once again, it seems i've fixed two bugs in it and it
works ok on sparc and i386 now.


Revision tags: OPENBSD_2_9_BASE
# 1.46 17-Jan-2001 mickey

advance through buffer, leftovers from singular version; from Henric Jungheim <henric@aimnet.com>


Revision tags: OPENBSD_2_8_BASE
# 1.45 22-Oct-2000 mickey

branches: 1.45.2;
oops; deraadt@ ok


# 1.44 20-Oct-2000 mickey

fix ioctls; pointed out by Pawel Krawczyk <http://ceti.pl/~kravietz/>


# 1.43 21-Aug-2000 jason

fix indentation from 1.41 addition


# 1.42 18-Jul-2000 mickey

do not call arc4_stir() on pool overflow.
calling it would hit perfomance in two evil ways,
by delaying queue processing and hitting on arc4
quality. basic idea was expressed by dm@ some time ago
when we were investigating poor arc4 quality.
then, numbers showed how badly it hits on us.


# 1.41 18-Jun-2000 millert

Support FIONBIO and FIOASYNC. FIOASYNC is more or less a no-op>


# 1.40 16-Jun-2000 deraadt

undo latest problem. breaks the sparc. diff is too large, we are not debugging it for you


# 1.39 08-Jun-2000 mickey

replace linked lists for event queue with circular buffer,
which gives two advantages -- faster and smaller.
do not arc4_stir on pool overflow, it takes too much time, instead
just hash data in and keep entropy count trim.
some minor cleanups here and there.
fixes overdropping of entropy on non-idle system load.
provos@ ok


Revision tags: OPENBSD_2_7_BASE
# 1.38 18-Apr-2000 hugh

branches: 1.38.2;
Double usage of random() in the pseudo device to avoid setting
every 32nd bit to zero in the output. Checked by mickey.


# 1.37 14-Apr-2000 mickey

this should fix the alpha; closes PR kernel/1189


# 1.36 13-Apr-2000 mickey

better has when adding entropy to the pool.
bigger pool (4k).


# 1.35 10-Apr-2000 mickey

add support for more random sources.
make it easy to add more in the future.
make extract_entropy() faster.
more accurate stats.


# 1.34 19-Mar-2000 mickey

faster log2, more stats, lazy random stirring, more stats, less debug, help and ok from provos@


Revision tags: OPENBSD_2_6_BASE SMP_BASE kame_19991208
# 1.33 28-Sep-1999 deraadt

branches: 1.33.4;
Set j = i after arc4random key schedule to be more like arc4 stream cipher;
from conversations between various people


Revision tags: OPENBSD_2_2_BASE OPENBSD_2_3_BASE OPENBSD_2_4_BASE OPENBSD_2_5_BASE
# 1.32 22-Aug-1997 downsj

nbits should probably actually be initialized.


# 1.31 28-Jun-1997 deraadt

fix the types


# 1.30 24-Jun-1997 mickey

more accounting!


# 1.29 22-Jun-1997 flipk

now where did that patch go?


# 1.28 22-Jun-1997 flipk

wasn't a race after all. properly initialize event_q pointers so the
last one doesn't point off the end.


# 1.27 21-Jun-1997 flipk

revert, there's a nasty race condition here.


# 1.26 20-Jun-1997 mickey

count properly (;


# 1.25 18-Jun-1997 mickey

s/u_char/u_int8_t/g, where reasonable
s/\(static.*arc4_[^(]+(\)[^,)]+\([^)]*)\)/\1\2/g
less cpu load, just in case


# 1.24 17-Jun-1997 mickey

count slow queue low entropy drops
bigger queue
use queue overflows for arc4_stir()


# 1.23 14-Jun-1997 mickey

split the treatment of the random events
event_q by flipk@
spl fix by deraadt@
gother statistics about whole processing
use 'sysctl kern.random' to view what had happened
also fix wrong vm.psstrings description


# 1.22 12-Jun-1997 mickey

little faster, smaller, safer


# 1.21 12-Jun-1997 mickey

back out recent changes....


# 1.20 11-Jun-1997 mickey

oops, clean debug flags


# 1.19 10-Jun-1997 mickey

do the job out of the calling function's spl


Revision tags: OPENBSD_2_1_BASE
# 1.18 30-Mar-1997 mickey

no more 2(two) md5 libs in kernel!
tested for rnd(4).... should work for ip too, since it's
the copy of ip_md*.
use sys/md5k.h for protos.... std iface forever!
hurray!


# 1.17 04-Feb-1997 dm

Make sure arc4random gets initialized eventually.


# 1.16 15-Jan-1997 kstailey

moved init of ret in randomioctl() to better location


# 1.15 15-Jan-1997 kstailey

prevent this warning:
rnd.c:823: warning: `ret' might be used uninitialized in this function
when compiling with -Wall


# 1.14 05-Jan-1997 niklas

Remove lots of timer_state structs as they just ate memory and only a few was
ever used. Now a single state is kept for net, tty and disk events resp.
Also, call the randomness from disk_unbusy instead of biodone, as biodone
gets a lot of virtual events (from virtual filesystems etc), and as a bonus:
feed xfer time and size into the entropy pool too.


# 1.13 01-Jan-1997 mickey

don't count on MFS in add_blkdev_randomness


# 1.12 28-Dec-1996 niklas

Fix prerequisite test, still need to check why NODEV bufs comes here.


# 1.11 19-Oct-1996 mickey

random device is permanent now.


# 1.10 18-Oct-1996 mickey

-Wall happieness


Revision tags: OPENBSD_2_0_BASE
# 1.9 29-Sep-1996 dm

Short comment describing the origin of arc4.


# 1.8 06-Sep-1996 mickey

cleanup and sync w/ latest Linux source.
remove keyboard randomness entry point.
make Free ppl happy, remove suspicious piece.
missed: SHA neede in libkern, why not to put aRC4 there too?


# 1.7 29-Aug-1996 deraadt

rnd -> random


# 1.6 11-Aug-1996 dm

Increased entropy through decreased typos.


# 1.5 11-Aug-1996 dm

Added arc4random and /dev/arnd.


# 1.4 10-Aug-1996 deraadt

indent nicely


# 1.3 24-Apr-1996 mickey

Supply randomness source for the rnd device.


# 1.2 17-Apr-1996 mickey

Update w/ the fact of MD5 presence in the libkern.a


# 1.1 29-Mar-1996 mickey

The random data source driver itself.
Initial commit.