Home | History | Annotate | Line # | Download | only in gen
arc4random.c revision 1.40
      1  1.40  riastrad /*	$NetBSD: arc4random.c,v 1.40 2025/03/02 22:46:23 riastradh Exp $	*/
      2   1.1    itojun 
      3  1.26  riastrad /*-
      4  1.26  riastrad  * Copyright (c) 2014 The NetBSD Foundation, Inc.
      5  1.26  riastrad  * All rights reserved.
      6  1.26  riastrad  *
      7  1.26  riastrad  * This code is derived from software contributed to The NetBSD Foundation
      8  1.26  riastrad  * by Taylor R. Campbell.
      9  1.26  riastrad  *
     10  1.26  riastrad  * Redistribution and use in source and binary forms, with or without
     11  1.26  riastrad  * modification, are permitted provided that the following conditions
     12  1.26  riastrad  * are met:
     13  1.26  riastrad  * 1. Redistributions of source code must retain the above copyright
     14  1.26  riastrad  *    notice, this list of conditions and the following disclaimer.
     15  1.26  riastrad  * 2. Redistributions in binary form must reproduce the above copyright
     16  1.26  riastrad  *    notice, this list of conditions and the following disclaimer in the
     17  1.26  riastrad  *    documentation and/or other materials provided with the distribution.
     18   1.1    itojun  *
     19  1.26  riastrad  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  1.26  riastrad  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  1.26  riastrad  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  1.26  riastrad  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  1.26  riastrad  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  1.26  riastrad  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  1.26  riastrad  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  1.26  riastrad  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  1.26  riastrad  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  1.26  riastrad  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  1.26  riastrad  * POSSIBILITY OF SUCH DAMAGE.
     30   1.1    itojun  */
     31   1.1    itojun 
     32   1.1    itojun /*
     33  1.26  riastrad  * Legacy arc4random(3) API from OpenBSD reimplemented using the
     34  1.26  riastrad  * ChaCha20 PRF, with per-thread state.
     35  1.26  riastrad  *
     36  1.26  riastrad  * Security model:
     37  1.26  riastrad  * - An attacker who sees some outputs cannot predict past or future
     38  1.26  riastrad  *   outputs.
     39  1.26  riastrad  * - An attacker who sees the PRNG state cannot predict past outputs.
     40  1.26  riastrad  * - An attacker who sees a child's PRNG state cannot predict past or
     41  1.26  riastrad  *   future outputs in the parent, or in other children.
     42  1.26  riastrad  *
     43  1.26  riastrad  * The arc4random(3) API may abort the process if:
     44   1.1    itojun  *
     45  1.26  riastrad  * (a) the crypto self-test fails,
     46  1.26  riastrad  * (b) pthread_atfork or thr_keycreate fail, or
     47  1.26  riastrad  * (c) sysctl(KERN_ARND) fails when reseeding the PRNG.
     48   1.1    itojun  *
     49  1.26  riastrad  * The crypto self-test, pthread_atfork, and thr_keycreate occur only
     50  1.26  riastrad  * once, on the first use of any of the arc4random(3) API.  KERN_ARND
     51  1.26  riastrad  * is unlikely to fail later unless the kernel is seriously broken.
     52   1.1    itojun  */
     53   1.1    itojun 
     54   1.8     lukem #include <sys/cdefs.h>
     55  1.40  riastrad __RCSID("$NetBSD: arc4random.c,v 1.40 2025/03/02 22:46:23 riastradh Exp $");
     56   1.8     lukem 
     57   1.7    kleink #include "namespace.h"
     58  1.11       tls #include "reentrant.h"
     59  1.26  riastrad 
     60  1.26  riastrad #include <sys/bitops.h>
     61  1.26  riastrad #include <sys/endian.h>
     62  1.26  riastrad #include <sys/errno.h>
     63  1.26  riastrad #include <sys/mman.h>
     64  1.26  riastrad #include <sys/sysctl.h>
     65  1.26  riastrad 
     66  1.26  riastrad #include <assert.h>
     67  1.26  riastrad #include <sha2.h>
     68  1.35  riastrad #include <stdatomic.h>
     69  1.22       roy #include <stdbool.h>
     70  1.26  riastrad #include <stdint.h>
     71   1.1    itojun #include <stdlib.h>
     72  1.26  riastrad #include <string.h>
     73   1.1    itojun #include <unistd.h>
     74   1.1    itojun 
     75  1.37  riastrad #include "arc4random.h"
     76  1.40  riastrad #include "atfork.h"
     77  1.37  riastrad #include "reentrant.h"
     78  1.37  riastrad 
     79   1.7    kleink #ifdef __weak_alias
     80   1.7    kleink __weak_alias(arc4random,_arc4random)
     81  1.20       dsl __weak_alias(arc4random_addrandom,_arc4random_addrandom)
     82  1.20       dsl __weak_alias(arc4random_buf,_arc4random_buf)
     83  1.20       dsl __weak_alias(arc4random_stir,_arc4random_stir)
     84  1.20       dsl __weak_alias(arc4random_uniform,_arc4random_uniform)
     85   1.7    kleink #endif
     86   1.7    kleink 
     87  1.26  riastrad /*
     88  1.26  riastrad  * For standard ChaCha, use le32dec/le32enc.  We don't need that for
     89  1.26  riastrad  * the purposes of a nondeterministic random number generator -- we
     90  1.26  riastrad  * don't need to be bit-for-bit compatible over any wire.
     91  1.26  riastrad  */
     92  1.26  riastrad 
     93  1.26  riastrad static inline uint32_t
     94  1.26  riastrad crypto_le32dec(const void *p)
     95  1.26  riastrad {
     96  1.26  riastrad 	uint32_t v;
     97  1.26  riastrad 
     98  1.26  riastrad 	(void)memcpy(&v, p, sizeof v);
     99  1.23       apb 
    100  1.26  riastrad 	return v;
    101  1.26  riastrad }
    102  1.26  riastrad 
    103  1.26  riastrad static inline void
    104  1.26  riastrad crypto_le32enc(void *p, uint32_t v)
    105  1.26  riastrad {
    106  1.26  riastrad 
    107  1.26  riastrad 	(void)memcpy(p, &v, sizeof v);
    108  1.26  riastrad }
    109  1.26  riastrad 
    110  1.26  riastrad /* ChaCha core */
    111  1.26  riastrad 
    112  1.26  riastrad #define	crypto_core_OUTPUTBYTES	64
    113  1.26  riastrad #define	crypto_core_INPUTBYTES	16
    114  1.26  riastrad #define	crypto_core_KEYBYTES	32
    115  1.26  riastrad #define	crypto_core_CONSTBYTES	16
    116  1.26  riastrad 
    117  1.28  riastrad #define	crypto_core_ROUNDS	20
    118  1.26  riastrad 
    119  1.26  riastrad static uint32_t
    120  1.26  riastrad rotate(uint32_t u, unsigned c)
    121  1.26  riastrad {
    122  1.26  riastrad 
    123  1.26  riastrad 	return (u << c) | (u >> (32 - c));
    124  1.26  riastrad }
    125  1.26  riastrad 
    126  1.26  riastrad #define	QUARTERROUND(a, b, c, d) do {					      \
    127  1.26  riastrad 	(a) += (b); (d) ^= (a); (d) = rotate((d), 16);			      \
    128  1.26  riastrad 	(c) += (d); (b) ^= (c); (b) = rotate((b), 12);			      \
    129  1.26  riastrad 	(a) += (b); (d) ^= (a); (d) = rotate((d),  8);			      \
    130  1.26  riastrad 	(c) += (d); (b) ^= (c); (b) = rotate((b),  7);			      \
    131  1.33    rillig } while (0)
    132  1.26  riastrad 
    133  1.34  christos static const uint8_t crypto_core_constant32[16] = "expand 32-byte k";
    134  1.26  riastrad 
    135  1.26  riastrad static void
    136  1.26  riastrad crypto_core(uint8_t *out, const uint8_t *in, const uint8_t *k,
    137  1.26  riastrad     const uint8_t *c)
    138  1.26  riastrad {
    139  1.26  riastrad 	uint32_t x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15;
    140  1.26  riastrad 	uint32_t j0,j1,j2,j3,j4,j5,j6,j7,j8,j9,j10,j11,j12,j13,j14,j15;
    141  1.26  riastrad 	int i;
    142  1.26  riastrad 
    143  1.26  riastrad 	j0 = x0 = crypto_le32dec(c + 0);
    144  1.26  riastrad 	j1 = x1 = crypto_le32dec(c + 4);
    145  1.26  riastrad 	j2 = x2 = crypto_le32dec(c + 8);
    146  1.26  riastrad 	j3 = x3 = crypto_le32dec(c + 12);
    147  1.26  riastrad 	j4 = x4 = crypto_le32dec(k + 0);
    148  1.26  riastrad 	j5 = x5 = crypto_le32dec(k + 4);
    149  1.26  riastrad 	j6 = x6 = crypto_le32dec(k + 8);
    150  1.26  riastrad 	j7 = x7 = crypto_le32dec(k + 12);
    151  1.26  riastrad 	j8 = x8 = crypto_le32dec(k + 16);
    152  1.26  riastrad 	j9 = x9 = crypto_le32dec(k + 20);
    153  1.26  riastrad 	j10 = x10 = crypto_le32dec(k + 24);
    154  1.26  riastrad 	j11 = x11 = crypto_le32dec(k + 28);
    155  1.26  riastrad 	j12 = x12 = crypto_le32dec(in + 0);
    156  1.26  riastrad 	j13 = x13 = crypto_le32dec(in + 4);
    157  1.26  riastrad 	j14 = x14 = crypto_le32dec(in + 8);
    158  1.26  riastrad 	j15 = x15 = crypto_le32dec(in + 12);
    159  1.26  riastrad 
    160  1.26  riastrad 	for (i = crypto_core_ROUNDS; i > 0; i -= 2) {
    161  1.26  riastrad 		QUARTERROUND( x0, x4, x8,x12);
    162  1.26  riastrad 		QUARTERROUND( x1, x5, x9,x13);
    163  1.26  riastrad 		QUARTERROUND( x2, x6,x10,x14);
    164  1.26  riastrad 		QUARTERROUND( x3, x7,x11,x15);
    165  1.26  riastrad 		QUARTERROUND( x0, x5,x10,x15);
    166  1.26  riastrad 		QUARTERROUND( x1, x6,x11,x12);
    167  1.26  riastrad 		QUARTERROUND( x2, x7, x8,x13);
    168  1.26  riastrad 		QUARTERROUND( x3, x4, x9,x14);
    169  1.26  riastrad 	}
    170  1.26  riastrad 
    171  1.26  riastrad 	crypto_le32enc(out + 0, x0 + j0);
    172  1.26  riastrad 	crypto_le32enc(out + 4, x1 + j1);
    173  1.26  riastrad 	crypto_le32enc(out + 8, x2 + j2);
    174  1.26  riastrad 	crypto_le32enc(out + 12, x3 + j3);
    175  1.26  riastrad 	crypto_le32enc(out + 16, x4 + j4);
    176  1.26  riastrad 	crypto_le32enc(out + 20, x5 + j5);
    177  1.26  riastrad 	crypto_le32enc(out + 24, x6 + j6);
    178  1.26  riastrad 	crypto_le32enc(out + 28, x7 + j7);
    179  1.26  riastrad 	crypto_le32enc(out + 32, x8 + j8);
    180  1.26  riastrad 	crypto_le32enc(out + 36, x9 + j9);
    181  1.26  riastrad 	crypto_le32enc(out + 40, x10 + j10);
    182  1.26  riastrad 	crypto_le32enc(out + 44, x11 + j11);
    183  1.26  riastrad 	crypto_le32enc(out + 48, x12 + j12);
    184  1.26  riastrad 	crypto_le32enc(out + 52, x13 + j13);
    185  1.26  riastrad 	crypto_le32enc(out + 56, x14 + j14);
    186  1.26  riastrad 	crypto_le32enc(out + 60, x15 + j15);
    187  1.26  riastrad }
    188  1.26  riastrad 
    189  1.26  riastrad /* ChaCha self-test */
    190  1.26  riastrad 
    191  1.26  riastrad #ifdef _DIAGNOSTIC
    192  1.26  riastrad 
    193  1.26  riastrad /*
    194  1.26  riastrad  * Test vector for ChaCha20 from
    195  1.26  riastrad  * <http://tools.ietf.org/html/draft-strombergson-chacha-test-vectors-00>,
    196  1.26  riastrad  * test vectors for ChaCha12 and ChaCha8 and for big-endian machines
    197  1.26  riastrad  * generated by the same crypto_core code with crypto_core_ROUNDS and
    198  1.26  riastrad  * crypto_le32enc/dec varied.
    199  1.26  riastrad  */
    200   1.1    itojun 
    201  1.26  riastrad static const uint8_t crypto_core_selftest_vector[64] = {
    202  1.26  riastrad #if _BYTE_ORDER == _LITTLE_ENDIAN
    203  1.26  riastrad #  if crypto_core_ROUNDS == 8
    204  1.26  riastrad 	0x3e,0x00,0xef,0x2f,0x89,0x5f,0x40,0xd6,
    205  1.26  riastrad 	0x7f,0x5b,0xb8,0xe8,0x1f,0x09,0xa5,0xa1,
    206  1.26  riastrad 	0x2c,0x84,0x0e,0xc3,0xce,0x9a,0x7f,0x3b,
    207  1.26  riastrad 	0x18,0x1b,0xe1,0x88,0xef,0x71,0x1a,0x1e,
    208  1.26  riastrad 	0x98,0x4c,0xe1,0x72,0xb9,0x21,0x6f,0x41,
    209  1.26  riastrad 	0x9f,0x44,0x53,0x67,0x45,0x6d,0x56,0x19,
    210  1.26  riastrad 	0x31,0x4a,0x42,0xa3,0xda,0x86,0xb0,0x01,
    211  1.26  riastrad 	0x38,0x7b,0xfd,0xb8,0x0e,0x0c,0xfe,0x42,
    212  1.26  riastrad #  elif crypto_core_ROUNDS == 12
    213  1.26  riastrad 	0x9b,0xf4,0x9a,0x6a,0x07,0x55,0xf9,0x53,
    214  1.26  riastrad 	0x81,0x1f,0xce,0x12,0x5f,0x26,0x83,0xd5,
    215  1.26  riastrad 	0x04,0x29,0xc3,0xbb,0x49,0xe0,0x74,0x14,
    216  1.26  riastrad 	0x7e,0x00,0x89,0xa5,0x2e,0xae,0x15,0x5f,
    217  1.26  riastrad 	0x05,0x64,0xf8,0x79,0xd2,0x7a,0xe3,0xc0,
    218  1.26  riastrad 	0x2c,0xe8,0x28,0x34,0xac,0xfa,0x8c,0x79,
    219  1.26  riastrad 	0x3a,0x62,0x9f,0x2c,0xa0,0xde,0x69,0x19,
    220  1.26  riastrad 	0x61,0x0b,0xe8,0x2f,0x41,0x13,0x26,0xbe,
    221  1.26  riastrad #  elif crypto_core_ROUNDS == 20
    222  1.26  riastrad 	0x76,0xb8,0xe0,0xad,0xa0,0xf1,0x3d,0x90,
    223  1.26  riastrad 	0x40,0x5d,0x6a,0xe5,0x53,0x86,0xbd,0x28,
    224  1.26  riastrad 	0xbd,0xd2,0x19,0xb8,0xa0,0x8d,0xed,0x1a,
    225  1.26  riastrad 	0xa8,0x36,0xef,0xcc,0x8b,0x77,0x0d,0xc7,
    226  1.26  riastrad 	0xda,0x41,0x59,0x7c,0x51,0x57,0x48,0x8d,
    227  1.26  riastrad 	0x77,0x24,0xe0,0x3f,0xb8,0xd8,0x4a,0x37,
    228  1.26  riastrad 	0x6a,0x43,0xb8,0xf4,0x15,0x18,0xa1,0x1c,
    229  1.26  riastrad 	0xc3,0x87,0xb6,0x69,0xb2,0xee,0x65,0x86,
    230  1.26  riastrad #  else
    231  1.26  riastrad #    error crypto_core_ROUNDS must be 8, 12, or 20.
    232  1.26  riastrad #  endif
    233  1.26  riastrad #elif _BYTE_ORDER == _BIG_ENDIAN
    234  1.26  riastrad #  if crypto_core_ROUNDS == 8
    235  1.26  riastrad 	0x9a,0x13,0x07,0xe3,0x38,0x18,0x9e,0x99,
    236  1.26  riastrad 	0x15,0x37,0x16,0x4d,0x04,0xe6,0x48,0x9a,
    237  1.26  riastrad 	0x07,0xd6,0xe8,0x7a,0x02,0xf9,0xf5,0xc7,
    238  1.26  riastrad 	0x3f,0xa9,0xc2,0x0a,0xe1,0xc6,0x62,0xea,
    239  1.26  riastrad 	0x80,0xaf,0xb6,0x51,0xca,0x52,0x43,0x87,
    240  1.26  riastrad 	0xe3,0xa6,0xa6,0x61,0x11,0xf5,0xe6,0xcf,
    241  1.26  riastrad 	0x09,0x0f,0xdc,0x9d,0xc3,0xc3,0xbb,0x43,
    242  1.26  riastrad 	0xd7,0xfa,0x70,0x42,0xbf,0xa5,0xee,0xa2,
    243  1.26  riastrad #  elif crypto_core_ROUNDS == 12
    244  1.26  riastrad 	0xcf,0x6c,0x16,0x48,0xbf,0xf4,0xba,0x85,
    245  1.26  riastrad 	0x32,0x69,0xd3,0x98,0xc8,0x7d,0xcd,0x3f,
    246  1.26  riastrad 	0xdc,0x76,0x6b,0xa2,0x7b,0xcb,0x17,0x4d,
    247  1.26  riastrad 	0x05,0xda,0xdd,0xd8,0x62,0x54,0xbf,0xe0,
    248  1.26  riastrad 	0x65,0xed,0x0e,0xf4,0x01,0x7e,0x3c,0x05,
    249  1.26  riastrad 	0x35,0xb2,0x7a,0x60,0xf3,0x8f,0x12,0x33,
    250  1.26  riastrad 	0x24,0x60,0xcd,0x85,0xfe,0x4c,0xf3,0x39,
    251  1.26  riastrad 	0xb1,0x0e,0x3e,0xe0,0xba,0xa6,0x2f,0xa9,
    252  1.26  riastrad #  elif crypto_core_ROUNDS == 20
    253  1.26  riastrad 	0x83,0x8b,0xf8,0x75,0xf7,0xde,0x9d,0x8c,
    254  1.26  riastrad 	0x33,0x14,0x72,0x28,0xd1,0xbe,0x88,0xe5,
    255  1.26  riastrad 	0x94,0xb5,0xed,0xb8,0x56,0xb5,0x9e,0x0c,
    256  1.26  riastrad 	0x64,0x6a,0xaf,0xd9,0xa7,0x49,0x10,0x59,
    257  1.26  riastrad 	0xba,0x3a,0x82,0xf8,0x4a,0x70,0x9c,0x00,
    258  1.26  riastrad 	0x82,0x2c,0xae,0xc6,0xd7,0x1c,0x2e,0xda,
    259  1.26  riastrad 	0x2a,0xfb,0x61,0x70,0x2b,0xd1,0xbf,0x8b,
    260  1.26  riastrad 	0x95,0xbc,0x23,0xb6,0x4b,0x60,0x02,0xec,
    261  1.26  riastrad #  else
    262  1.26  riastrad #    error crypto_core_ROUNDS must be 8, 12, or 20.
    263  1.26  riastrad #  endif
    264  1.16       dsl #else
    265  1.26  riastrad #  error Byte order must be little-endian or big-endian.
    266  1.16       dsl #endif
    267  1.26  riastrad };
    268  1.16       dsl 
    269  1.26  riastrad static int
    270  1.26  riastrad crypto_core_selftest(void)
    271  1.26  riastrad {
    272  1.26  riastrad 	const uint8_t nonce[crypto_core_INPUTBYTES] = {0};
    273  1.26  riastrad 	const uint8_t key[crypto_core_KEYBYTES] = {0};
    274  1.26  riastrad 	uint8_t block[64];
    275  1.26  riastrad 	unsigned i;
    276  1.26  riastrad 
    277  1.26  riastrad 	crypto_core(block, nonce, key, crypto_core_constant32);
    278  1.26  riastrad 	for (i = 0; i < 64; i++) {
    279  1.26  riastrad 		if (block[i] != crypto_core_selftest_vector[i])
    280  1.26  riastrad 			return EIO;
    281  1.26  riastrad 	}
    282   1.1    itojun 
    283  1.26  riastrad 	return 0;
    284  1.26  riastrad }
    285  1.26  riastrad 
    286  1.26  riastrad #else  /* !_DIAGNOSTIC */
    287  1.26  riastrad 
    288  1.26  riastrad static int
    289  1.26  riastrad crypto_core_selftest(void)
    290  1.22       roy {
    291  1.22       roy 
    292  1.26  riastrad 	return 0;
    293  1.22       roy }
    294  1.22       roy 
    295  1.26  riastrad #endif
    296  1.26  riastrad 
    297  1.26  riastrad /* PRNG */
    298  1.26  riastrad 
    299  1.26  riastrad /*
    300  1.26  riastrad  * For a state s, rather than use ChaCha20 as a stream cipher to
    301  1.26  riastrad  * generate the concatenation ChaCha20_s(0) || ChaCha20_s(1) || ..., we
    302  1.26  riastrad  * split ChaCha20_s(0) into s' || x and yield x for the first request,
    303  1.26  riastrad  * split ChaCha20_s'(0) into s'' || y and yield y for the second
    304  1.26  riastrad  * request, &c.  This provides backtracking resistance: an attacker who
    305  1.26  riastrad  * finds s'' can't recover s' or x.
    306  1.26  riastrad  */
    307  1.26  riastrad 
    308  1.26  riastrad #define	crypto_prng_SEEDBYTES		crypto_core_KEYBYTES
    309  1.26  riastrad #define	crypto_prng_MAXOUTPUTBYTES	\
    310  1.26  riastrad 	(crypto_core_OUTPUTBYTES - crypto_prng_SEEDBYTES)
    311  1.26  riastrad 
    312  1.37  riastrad __CTASSERT(sizeof(struct crypto_prng) == crypto_prng_SEEDBYTES);
    313  1.26  riastrad 
    314  1.22       roy static void
    315  1.26  riastrad crypto_prng_seed(struct crypto_prng *prng, const void *seed)
    316  1.22       roy {
    317  1.22       roy 
    318  1.26  riastrad 	(void)memcpy(prng->state, seed, crypto_prng_SEEDBYTES);
    319  1.22       roy }
    320  1.22       roy 
    321  1.22       roy static void
    322  1.26  riastrad crypto_prng_buf(struct crypto_prng *prng, void *buf, size_t n)
    323  1.22       roy {
    324  1.26  riastrad 	const uint8_t nonce[crypto_core_INPUTBYTES] = {0};
    325  1.26  riastrad 	uint8_t output[crypto_core_OUTPUTBYTES];
    326  1.26  riastrad 
    327  1.26  riastrad 	_DIAGASSERT(n <= crypto_prng_MAXOUTPUTBYTES);
    328  1.26  riastrad 	__CTASSERT(sizeof prng->state + crypto_prng_MAXOUTPUTBYTES
    329  1.26  riastrad 	    <= sizeof output);
    330  1.22       roy 
    331  1.26  riastrad 	crypto_core(output, nonce, prng->state, crypto_core_constant32);
    332  1.26  riastrad 	(void)memcpy(prng->state, output, sizeof prng->state);
    333  1.26  riastrad 	(void)memcpy(buf, output + sizeof prng->state, n);
    334  1.26  riastrad 	(void)explicit_memset(output, 0, sizeof output);
    335  1.22       roy }
    336  1.22       roy 
    337  1.26  riastrad /* One-time stream: expand short single-use secret into long secret */
    338  1.26  riastrad 
    339  1.26  riastrad #define	crypto_onetimestream_SEEDBYTES	crypto_core_KEYBYTES
    340  1.26  riastrad 
    341  1.26  riastrad static void
    342  1.26  riastrad crypto_onetimestream(const void *seed, void *buf, size_t n)
    343  1.15       dsl {
    344  1.26  riastrad 	uint32_t nonce[crypto_core_INPUTBYTES / sizeof(uint32_t)] = {0};
    345  1.26  riastrad 	uint8_t block[crypto_core_OUTPUTBYTES];
    346  1.26  riastrad 	uint8_t *p8, *p32;
    347  1.27  christos 	const uint8_t *nonce8 = (const uint8_t *)(void *)nonce;
    348  1.26  riastrad 	size_t ni, nb, nf;
    349  1.26  riastrad 
    350  1.25       roy 	/*
    351  1.26  riastrad 	 * Guarantee we can generate up to n bytes.  We have
    352  1.26  riastrad 	 * 2^(8*INPUTBYTES) possible inputs yielding output of
    353  1.26  riastrad 	 * OUTPUTBYTES*2^(8*INPUTBYTES) bytes.  It suffices to require
    354  1.26  riastrad 	 * that sizeof n > (1/CHAR_BIT) log_2 n be less than
    355  1.26  riastrad 	 * (1/CHAR_BIT) log_2 of the total output stream length.  We
    356  1.26  riastrad 	 * have
    357  1.26  riastrad 	 *
    358  1.26  riastrad 	 *	log_2 (o 2^(8 i)) = log_2 o + log_2 2^(8 i)
    359  1.26  riastrad 	 *	  = log_2 o + 8 i.
    360  1.25       roy 	 */
    361  1.32  christos #ifndef __lint__
    362  1.32  christos 	__CTASSERT(CHAR_BIT * sizeof n <= (ilog2(crypto_core_OUTPUTBYTES) +
    363  1.32  christos 		8 * crypto_core_INPUTBYTES));
    364  1.32  christos #endif
    365  1.15       dsl 
    366  1.26  riastrad 	p8 = buf;
    367  1.26  riastrad 	p32 = (uint8_t *)roundup2((uintptr_t)p8, 4);
    368  1.26  riastrad 	ni = p32 - p8;
    369  1.26  riastrad 	if (n < ni)
    370  1.26  riastrad 		ni = n;
    371  1.26  riastrad 	nb = (n - ni) / sizeof block;
    372  1.26  riastrad 	nf = (n - ni) % sizeof block;
    373  1.26  riastrad 
    374  1.26  riastrad 	_DIAGASSERT(((uintptr_t)p32 & 3) == 0);
    375  1.26  riastrad 	_DIAGASSERT(ni <= n);
    376  1.26  riastrad 	_DIAGASSERT(nb <= (n / sizeof block));
    377  1.26  riastrad 	_DIAGASSERT(nf <= n);
    378  1.26  riastrad 	_DIAGASSERT(n == (ni + (nb * sizeof block) + nf));
    379  1.26  riastrad 	_DIAGASSERT(ni < 4);
    380  1.26  riastrad 	_DIAGASSERT(nf < sizeof block);
    381  1.26  riastrad 
    382  1.26  riastrad 	if (ni) {
    383  1.26  riastrad 		crypto_core(block, nonce8, seed, crypto_core_constant32);
    384  1.26  riastrad 		nonce[0]++;
    385  1.26  riastrad 		(void)memcpy(p8, block, ni);
    386  1.26  riastrad 	}
    387  1.26  riastrad 	while (nb--) {
    388  1.26  riastrad 		crypto_core(p32, nonce8, seed, crypto_core_constant32);
    389  1.26  riastrad 		if (++nonce[0] == 0)
    390  1.26  riastrad 			nonce[1]++;
    391  1.26  riastrad 		p32 += crypto_core_OUTPUTBYTES;
    392  1.26  riastrad 	}
    393  1.26  riastrad 	if (nf) {
    394  1.26  riastrad 		crypto_core(block, nonce8, seed, crypto_core_constant32);
    395  1.26  riastrad 		if (++nonce[0] == 0)
    396  1.26  riastrad 			nonce[1]++;
    397  1.26  riastrad 		(void)memcpy(p32, block, nf);
    398  1.22       roy 	}
    399  1.26  riastrad 
    400  1.26  riastrad 	if (ni | nf)
    401  1.26  riastrad 		(void)explicit_memset(block, 0, sizeof block);
    402  1.15       dsl }
    403  1.15       dsl 
    404  1.35  riastrad /*
    405  1.35  riastrad  * entropy_epoch()
    406  1.35  riastrad  *
    407  1.35  riastrad  *	Return the current entropy epoch, from the sysctl node
    408  1.35  riastrad  *	kern.entropy.epoch.
    409  1.35  riastrad  *
    410  1.35  riastrad  *	The entropy epoch is never zero.  Initially, or on error, it is
    411  1.35  riastrad  *	(unsigned)-1.  It may wrap around but it skips (unsigned)-1 and
    412  1.35  riastrad  *	0 when it does.  Changes happen less than once per second, so
    413  1.35  riastrad  *	wraparound will only affect systems after 136 years of uptime.
    414  1.35  riastrad  *
    415  1.35  riastrad  *	XXX This should get it from a page shared read-only by kernel
    416  1.35  riastrad  *	with userland, but until we implement such a mechanism, this
    417  1.35  riastrad  *	sysctl -- incurring the cost of a syscall -- will have to
    418  1.35  riastrad  *	serve.
    419  1.35  riastrad  */
    420  1.35  riastrad static unsigned
    421  1.35  riastrad entropy_epoch(void)
    422  1.35  riastrad {
    423  1.35  riastrad 	static atomic_int mib0[3];
    424  1.35  riastrad 	static atomic_bool initialized = false;
    425  1.35  riastrad 	int mib[3];
    426  1.38  riastrad 	unsigned epoch = (unsigned)-1;
    427  1.35  riastrad 	size_t epochlen = sizeof(epoch);
    428  1.35  riastrad 
    429  1.35  riastrad 	/*
    430  1.35  riastrad 	 * Resolve kern.entropy.epoch if we haven't already.  Cache it
    431  1.35  riastrad 	 * for the next caller.  Initialization is idempotent, so it's
    432  1.35  riastrad 	 * OK if two threads do it at once.
    433  1.35  riastrad 	 */
    434  1.35  riastrad 	if (atomic_load_explicit(&initialized, memory_order_acquire)) {
    435  1.35  riastrad 		mib[0] = atomic_load_explicit(&mib0[0], memory_order_relaxed);
    436  1.35  riastrad 		mib[1] = atomic_load_explicit(&mib0[1], memory_order_relaxed);
    437  1.35  riastrad 		mib[2] = atomic_load_explicit(&mib0[2], memory_order_relaxed);
    438  1.35  riastrad 	} else {
    439  1.35  riastrad 		size_t nmib = __arraycount(mib);
    440  1.35  riastrad 
    441  1.35  riastrad 		if (sysctlnametomib("kern.entropy.epoch", mib, &nmib) == -1)
    442  1.38  riastrad 			return (unsigned)-1;
    443  1.35  riastrad 		if (nmib != __arraycount(mib))
    444  1.38  riastrad 			return (unsigned)-1;
    445  1.35  riastrad 		atomic_store_explicit(&mib0[0], mib[0], memory_order_relaxed);
    446  1.35  riastrad 		atomic_store_explicit(&mib0[1], mib[1], memory_order_relaxed);
    447  1.35  riastrad 		atomic_store_explicit(&mib0[2], mib[2], memory_order_relaxed);
    448  1.35  riastrad 		atomic_store_explicit(&initialized, true,
    449  1.35  riastrad 		    memory_order_release);
    450  1.35  riastrad 	}
    451  1.35  riastrad 
    452  1.35  riastrad 	if (sysctl(mib, __arraycount(mib), &epoch, &epochlen, NULL, 0) == -1)
    453  1.38  riastrad 		return (unsigned)-1;
    454  1.35  riastrad 	if (epochlen != sizeof(epoch))
    455  1.38  riastrad 		return (unsigned)-1;
    456  1.35  riastrad 
    457  1.35  riastrad 	return epoch;
    458  1.35  riastrad }
    459  1.35  riastrad 
    460  1.26  riastrad /* arc4random state: per-thread, per-process (zeroed in child on fork) */
    461  1.26  riastrad 
    462  1.26  riastrad static void
    463  1.26  riastrad arc4random_prng_addrandom(struct arc4random_prng *prng, const void *data,
    464  1.26  riastrad     size_t datalen)
    465  1.26  riastrad {
    466  1.26  riastrad 	const int mib[] = { CTL_KERN, KERN_ARND };
    467  1.26  riastrad 	SHA256_CTX ctx;
    468  1.26  riastrad 	uint8_t buf[crypto_prng_SEEDBYTES];
    469  1.26  riastrad 	size_t buflen = sizeof buf;
    470  1.35  riastrad 	unsigned epoch = entropy_epoch();
    471  1.26  riastrad 
    472  1.26  riastrad 	__CTASSERT(sizeof buf == SHA256_DIGEST_LENGTH);
    473  1.26  riastrad 
    474  1.26  riastrad 	SHA256_Init(&ctx);
    475  1.26  riastrad 
    476  1.26  riastrad 	crypto_prng_buf(&prng->arc4_prng, buf, sizeof buf);
    477  1.26  riastrad 	SHA256_Update(&ctx, buf, sizeof buf);
    478  1.26  riastrad 
    479  1.27  christos 	if (sysctl(mib, (u_int)__arraycount(mib), buf, &buflen, NULL, 0) == -1)
    480  1.26  riastrad 		abort();
    481  1.26  riastrad 	if (buflen != sizeof buf)
    482  1.26  riastrad 		abort();
    483  1.26  riastrad 	SHA256_Update(&ctx, buf, sizeof buf);
    484  1.26  riastrad 
    485  1.26  riastrad 	if (data != NULL)
    486  1.26  riastrad 		SHA256_Update(&ctx, data, datalen);
    487  1.26  riastrad 
    488  1.26  riastrad 	SHA256_Final(buf, &ctx);
    489  1.26  riastrad 	(void)explicit_memset(&ctx, 0, sizeof ctx);
    490  1.26  riastrad 
    491  1.26  riastrad 	/* reseed(SHA256(prng() || sysctl(KERN_ARND) || data)) */
    492  1.26  riastrad 	crypto_prng_seed(&prng->arc4_prng, buf);
    493  1.26  riastrad 	(void)explicit_memset(buf, 0, sizeof buf);
    494  1.35  riastrad 	prng->arc4_epoch = epoch;
    495  1.26  riastrad }
    496  1.26  riastrad 
    497  1.26  riastrad #ifdef _REENTRANT
    498  1.26  riastrad static struct arc4random_prng *
    499  1.26  riastrad arc4random_prng_create(void)
    500   1.1    itojun {
    501  1.26  riastrad 	struct arc4random_prng *prng;
    502  1.26  riastrad 	const size_t size = roundup(sizeof(*prng), sysconf(_SC_PAGESIZE));
    503   1.1    itojun 
    504  1.31  riastrad 	prng = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1,
    505  1.31  riastrad 	    0);
    506  1.26  riastrad 	if (prng == MAP_FAILED)
    507  1.26  riastrad 		goto fail0;
    508  1.26  riastrad 	if (minherit(prng, size, MAP_INHERIT_ZERO) == -1)
    509  1.26  riastrad 		goto fail1;
    510  1.26  riastrad 
    511  1.26  riastrad 	return prng;
    512  1.26  riastrad 
    513  1.26  riastrad fail1:	(void)munmap(prng, size);
    514  1.26  riastrad fail0:	return NULL;
    515   1.1    itojun }
    516  1.26  riastrad #endif
    517   1.1    itojun 
    518  1.26  riastrad #ifdef _REENTRANT
    519  1.26  riastrad static void
    520  1.26  riastrad arc4random_prng_destroy(struct arc4random_prng *prng)
    521   1.1    itojun {
    522  1.26  riastrad 	const size_t size = roundup(sizeof(*prng), sysconf(_SC_PAGESIZE));
    523   1.1    itojun 
    524  1.26  riastrad 	(void)explicit_memset(prng, 0, sizeof(*prng));
    525  1.26  riastrad 	(void)munmap(prng, size);
    526  1.26  riastrad }
    527  1.26  riastrad #endif
    528  1.22       roy 
    529  1.26  riastrad /* Library state */
    530  1.11       tls 
    531  1.37  riastrad struct arc4random_global_state arc4random_global = {
    532  1.26  riastrad #ifdef _REENTRANT
    533  1.26  riastrad 	.lock		= MUTEX_INITIALIZER,
    534  1.26  riastrad #endif
    535  1.26  riastrad 	.initialized	= false,
    536  1.26  riastrad };
    537   1.3    itojun 
    538  1.40  riastrad static struct atfork_callback arc4random_atfork_prepare_cb;
    539  1.26  riastrad static void
    540  1.26  riastrad arc4random_atfork_prepare(void)
    541  1.26  riastrad {
    542  1.18       dsl 
    543  1.26  riastrad 	mutex_lock(&arc4random_global.lock);
    544  1.26  riastrad 	(void)explicit_memset(&arc4random_global.prng, 0,
    545  1.26  riastrad 	    sizeof arc4random_global.prng);
    546  1.22       roy }
    547  1.22       roy 
    548  1.40  riastrad static struct atfork_callback arc4random_atfork_parent_cb;
    549  1.26  riastrad static void
    550  1.26  riastrad arc4random_atfork_parent(void)
    551  1.22       roy {
    552  1.22       roy 
    553  1.26  riastrad 	mutex_unlock(&arc4random_global.lock);
    554   1.1    itojun }
    555   1.1    itojun 
    556  1.40  riastrad static struct atfork_callback arc4random_atfork_child_cb;
    557  1.26  riastrad static void
    558  1.26  riastrad arc4random_atfork_child(void)
    559   1.1    itojun {
    560   1.1    itojun 
    561  1.26  riastrad 	mutex_unlock(&arc4random_global.lock);
    562   1.1    itojun }
    563   1.1    itojun 
    564  1.26  riastrad #ifdef _REENTRANT
    565  1.26  riastrad static void
    566  1.26  riastrad arc4random_tsd_destructor(void *p)
    567  1.17       dsl {
    568  1.26  riastrad 	struct arc4random_prng *const prng = p;
    569  1.22       roy 
    570  1.26  riastrad 	arc4random_prng_destroy(prng);
    571  1.17       dsl }
    572  1.26  riastrad #endif
    573  1.17       dsl 
    574  1.26  riastrad static void
    575  1.26  riastrad arc4random_initialize(void)
    576   1.1    itojun {
    577  1.22       roy 
    578  1.26  riastrad 	mutex_lock(&arc4random_global.lock);
    579  1.26  riastrad 	if (!arc4random_global.initialized) {
    580  1.26  riastrad 		if (crypto_core_selftest() != 0)
    581  1.26  riastrad 			abort();
    582  1.40  riastrad 		__libc_atfork(
    583  1.40  riastrad 		    &arc4random_atfork_prepare_cb, &arc4random_atfork_prepare,
    584  1.40  riastrad 		    &arc4random_atfork_parent_cb, &arc4random_atfork_parent,
    585  1.40  riastrad 		    &arc4random_atfork_child_cb, &arc4random_atfork_child);
    586  1.26  riastrad #ifdef _REENTRANT
    587  1.26  riastrad 		if (thr_keycreate(&arc4random_global.thread_key,
    588  1.39  riastrad 			&arc4random_tsd_destructor) == 0)
    589  1.39  riastrad 			arc4random_global.per_thread = true;
    590  1.26  riastrad #endif
    591  1.26  riastrad 		arc4random_global.initialized = true;
    592  1.26  riastrad 	}
    593  1.26  riastrad 	mutex_unlock(&arc4random_global.lock);
    594   1.1    itojun }
    595   1.1    itojun 
    596  1.26  riastrad static struct arc4random_prng *
    597  1.26  riastrad arc4random_prng_get(void)
    598   1.1    itojun {
    599  1.26  riastrad 	struct arc4random_prng *prng = NULL;
    600  1.26  riastrad 
    601  1.26  riastrad 	/* Make sure the library is initialized.  */
    602  1.26  riastrad 	if (__predict_false(!arc4random_global.initialized))
    603  1.26  riastrad 		arc4random_initialize();
    604  1.26  riastrad 
    605  1.26  riastrad #ifdef _REENTRANT
    606  1.26  riastrad 	/* Get or create the per-thread PRNG state.  */
    607  1.39  riastrad 	prng = __predict_true(arc4random_global.per_thread)
    608  1.39  riastrad 	    ? thr_getspecific(arc4random_global.thread_key)
    609  1.39  riastrad 	    : NULL;
    610  1.39  riastrad 	if (__predict_false(prng == NULL) && arc4random_global.per_thread) {
    611  1.26  riastrad 		prng = arc4random_prng_create();
    612  1.26  riastrad 		thr_setspecific(arc4random_global.thread_key, prng);
    613  1.26  riastrad 	}
    614  1.26  riastrad #endif
    615  1.26  riastrad 
    616  1.26  riastrad 	/* If we can't create it, fall back to the global PRNG.  */
    617  1.26  riastrad 	if (__predict_false(prng == NULL)) {
    618  1.26  riastrad 		mutex_lock(&arc4random_global.lock);
    619  1.26  riastrad 		prng = &arc4random_global.prng;
    620  1.26  riastrad 	}
    621  1.22       roy 
    622  1.26  riastrad 	/* Guarantee the PRNG is seeded.  */
    623  1.35  riastrad 	if (__predict_false(prng->arc4_epoch != entropy_epoch()))
    624  1.26  riastrad 		arc4random_prng_addrandom(prng, NULL, 0);
    625  1.26  riastrad 
    626  1.26  riastrad 	return prng;
    627   1.1    itojun }
    628   1.1    itojun 
    629  1.26  riastrad static void
    630  1.26  riastrad arc4random_prng_put(struct arc4random_prng *prng)
    631  1.11       tls {
    632  1.22       roy 
    633  1.26  riastrad 	/* If we had fallen back to the global PRNG, unlock it.  */
    634  1.26  riastrad 	if (__predict_false(prng == &arc4random_global.prng))
    635  1.26  riastrad 		mutex_unlock(&arc4random_global.lock);
    636   1.1    itojun }
    637   1.1    itojun 
    638  1.26  riastrad /* Public API */
    639  1.26  riastrad 
    640  1.10  christos uint32_t
    641  1.10  christos arc4random(void)
    642   1.1    itojun {
    643  1.26  riastrad 	struct arc4random_prng *prng;
    644  1.11       tls 	uint32_t v;
    645  1.16       dsl 
    646  1.26  riastrad 	prng = arc4random_prng_get();
    647  1.26  riastrad 	crypto_prng_buf(&prng->arc4_prng, &v, sizeof v);
    648  1.26  riastrad 	arc4random_prng_put(prng);
    649  1.26  riastrad 
    650  1.11       tls 	return v;
    651   1.1    itojun }
    652   1.1    itojun 
    653  1.16       dsl void
    654  1.16       dsl arc4random_buf(void *buf, size_t len)
    655  1.10  christos {
    656  1.26  riastrad 	struct arc4random_prng *prng;
    657  1.26  riastrad 
    658  1.26  riastrad 	if (len <= crypto_prng_MAXOUTPUTBYTES) {
    659  1.26  riastrad 		prng = arc4random_prng_get();
    660  1.26  riastrad 		crypto_prng_buf(&prng->arc4_prng, buf, len);
    661  1.26  riastrad 		arc4random_prng_put(prng);
    662  1.26  riastrad 	} else {
    663  1.26  riastrad 		uint8_t seed[crypto_onetimestream_SEEDBYTES];
    664  1.26  riastrad 
    665  1.26  riastrad 		prng = arc4random_prng_get();
    666  1.26  riastrad 		crypto_prng_buf(&prng->arc4_prng, seed, sizeof seed);
    667  1.26  riastrad 		arc4random_prng_put(prng);
    668  1.26  riastrad 
    669  1.26  riastrad 		crypto_onetimestream(seed, buf, len);
    670  1.26  riastrad 		(void)explicit_memset(seed, 0, sizeof seed);
    671  1.26  riastrad 	}
    672  1.26  riastrad }
    673  1.26  riastrad 
    674  1.26  riastrad uint32_t
    675  1.26  riastrad arc4random_uniform(uint32_t bound)
    676  1.26  riastrad {
    677  1.26  riastrad 	struct arc4random_prng *prng;
    678  1.26  riastrad 	uint32_t minimum, r;
    679  1.26  riastrad 
    680  1.26  riastrad 	/*
    681  1.26  riastrad 	 * We want a uniform random choice in [0, n), and arc4random()
    682  1.26  riastrad 	 * makes a uniform random choice in [0, 2^32).  If we reduce
    683  1.26  riastrad 	 * that modulo n, values in [0, 2^32 mod n) will be represented
    684  1.26  riastrad 	 * slightly more than values in [2^32 mod n, n).  Instead we
    685  1.26  riastrad 	 * choose only from [2^32 mod n, 2^32) by rejecting samples in
    686  1.26  riastrad 	 * [0, 2^32 mod n), to avoid counting the extra representative
    687  1.26  riastrad 	 * of [0, 2^32 mod n).  To compute 2^32 mod n, note that
    688  1.26  riastrad 	 *
    689  1.26  riastrad 	 *	2^32 mod n = 2^32 mod n - 0
    690  1.26  riastrad 	 *	  = 2^32 mod n - n mod n
    691  1.26  riastrad 	 *	  = (2^32 - n) mod n,
    692  1.26  riastrad 	 *
    693  1.26  riastrad 	 * the last of which is what we compute in 32-bit arithmetic.
    694  1.26  riastrad 	 */
    695  1.26  riastrad 	minimum = (-bound % bound);
    696  1.26  riastrad 
    697  1.26  riastrad 	prng = arc4random_prng_get();
    698  1.26  riastrad 	do crypto_prng_buf(&prng->arc4_prng, &r, sizeof r);
    699  1.26  riastrad 	while (__predict_false(r < minimum));
    700  1.26  riastrad 	arc4random_prng_put(prng);
    701  1.17       dsl 
    702  1.26  riastrad 	return (r % bound);
    703  1.11       tls }
    704  1.11       tls 
    705  1.26  riastrad void
    706  1.26  riastrad arc4random_stir(void)
    707  1.26  riastrad {
    708  1.26  riastrad 	struct arc4random_prng *prng;
    709  1.26  riastrad 
    710  1.26  riastrad 	prng = arc4random_prng_get();
    711  1.26  riastrad 	arc4random_prng_addrandom(prng, NULL, 0);
    712  1.26  riastrad 	arc4random_prng_put(prng);
    713  1.26  riastrad }
    714  1.10  christos 
    715  1.10  christos /*
    716  1.26  riastrad  * Silly signature here is for hysterical raisins.  Should instead be
    717  1.26  riastrad  * const void *data and size_t datalen.
    718  1.10  christos  */
    719  1.26  riastrad void
    720  1.26  riastrad arc4random_addrandom(u_char *data, int datalen)
    721  1.10  christos {
    722  1.26  riastrad 	struct arc4random_prng *prng;
    723  1.10  christos 
    724  1.26  riastrad 	_DIAGASSERT(0 <= datalen);
    725  1.10  christos 
    726  1.26  riastrad 	prng = arc4random_prng_get();
    727  1.26  riastrad 	arc4random_prng_addrandom(prng, data, datalen);
    728  1.26  riastrad 	arc4random_prng_put(prng);
    729  1.26  riastrad }
    730  1.26  riastrad 
    731  1.26  riastrad #ifdef _ARC4RANDOM_TEST
    732  1.26  riastrad 
    733  1.26  riastrad #include <sys/wait.h>
    734  1.26  riastrad 
    735  1.26  riastrad #include <err.h>
    736  1.26  riastrad #include <stdio.h>
    737  1.26  riastrad 
    738  1.26  riastrad int
    739  1.26  riastrad main(int argc __unused, char **argv __unused)
    740  1.26  riastrad {
    741  1.26  riastrad 	unsigned char gubbish[] = "random gubbish";
    742  1.26  riastrad 	const uint8_t zero64[64] = {0};
    743  1.26  riastrad 	uint8_t buf[2048];
    744  1.26  riastrad 	unsigned i, a, n;
    745  1.26  riastrad 
    746  1.26  riastrad 	/* Test arc4random: should not be deterministic.  */
    747  1.26  riastrad 	if (printf("arc4random: %08"PRIx32"\n", arc4random()) < 0)
    748  1.26  riastrad 		err(1, "printf");
    749  1.26  riastrad 
    750  1.26  riastrad 	/* Test stirring: should definitely not be deterministic.  */
    751  1.26  riastrad 	arc4random_stir();
    752  1.26  riastrad 
    753  1.26  riastrad 	/* Test small buffer.  */
    754  1.26  riastrad 	arc4random_buf(buf, 8);
    755  1.26  riastrad 	if (printf("arc4randombuf small:") < 0)
    756  1.26  riastrad 		err(1, "printf");
    757  1.26  riastrad 	for (i = 0; i < 8; i++)
    758  1.26  riastrad 		if (printf(" %02x", buf[i]) < 0)
    759  1.26  riastrad 			err(1, "printf");
    760  1.26  riastrad 	if (printf("\n") < 0)
    761  1.26  riastrad 		err(1, "printf");
    762  1.26  riastrad 
    763  1.26  riastrad 	/* Test addrandom: should not make the rest deterministic.  */
    764  1.26  riastrad 	arc4random_addrandom(gubbish, sizeof gubbish);
    765  1.26  riastrad 
    766  1.26  riastrad 	/* Test large buffer.  */
    767  1.26  riastrad 	arc4random_buf(buf, sizeof buf);
    768  1.26  riastrad 	if (printf("arc4randombuf_large:") < 0)
    769  1.26  riastrad 		err(1, "printf");
    770  1.26  riastrad 	for (i = 0; i < sizeof buf; i++)
    771  1.26  riastrad 		if (printf(" %02x", buf[i]) < 0)
    772  1.26  riastrad 			err(1, "printf");
    773  1.26  riastrad 	if (printf("\n") < 0)
    774  1.26  riastrad 		err(1, "printf");
    775  1.26  riastrad 
    776  1.26  riastrad 	/* Test misaligned small and large.  */
    777  1.26  riastrad 	for (a = 0; a < 64; a++) {
    778  1.26  riastrad 		for (n = a; n < sizeof buf; n++) {
    779  1.26  riastrad 			(void)memset(buf, 0, sizeof buf);
    780  1.26  riastrad 			arc4random_buf(buf, n - a);
    781  1.26  riastrad 			if (memcmp(buf + n - a, zero64, a) != 0)
    782  1.26  riastrad 				errx(1, "arc4random buffer overflow 0");
    783  1.26  riastrad 
    784  1.26  riastrad 			(void)memset(buf, 0, sizeof buf);
    785  1.26  riastrad 			arc4random_buf(buf + a, n - a);
    786  1.26  riastrad 			if (memcmp(buf, zero64, a) != 0)
    787  1.26  riastrad 				errx(1, "arc4random buffer overflow 1");
    788  1.26  riastrad 
    789  1.26  riastrad 			if ((2*a) <= n) {
    790  1.26  riastrad 				(void)memset(buf, 0, sizeof buf);
    791  1.26  riastrad 				arc4random_buf(buf + a, n - a - a);
    792  1.26  riastrad 				if (memcmp(buf + n - a, zero64, a) != 0)
    793  1.26  riastrad 					errx(1,
    794  1.26  riastrad 					    "arc4random buffer overflow 2");
    795  1.26  riastrad 			}
    796  1.26  riastrad 		}
    797  1.26  riastrad 	}
    798  1.16       dsl 
    799  1.26  riastrad 	/* Test fork-safety.  */
    800  1.26  riastrad     {
    801  1.26  riastrad 	pid_t pid, rpid;
    802  1.26  riastrad 	int status;
    803  1.26  riastrad 
    804  1.26  riastrad 	pid = fork();
    805  1.26  riastrad 	switch (pid) {
    806  1.26  riastrad 	case -1:
    807  1.26  riastrad 		err(1, "fork");
    808  1.36  riastrad 	case 0: {
    809  1.36  riastrad 		/*
    810  1.36  riastrad 		 * Verify the epoch has been set to zero by fork.
    811  1.36  riastrad 		 */
    812  1.36  riastrad 		struct arc4random_prng *prng = NULL;
    813  1.36  riastrad #ifdef _REENTRANT
    814  1.36  riastrad 		prng = thr_getspecific(arc4random_global.thread_key);
    815  1.36  riastrad #endif
    816  1.36  riastrad 		if (prng == NULL)
    817  1.36  riastrad 			prng = &arc4random_global.prng;
    818  1.36  riastrad 		_exit(prng->arc4_epoch != 0);
    819  1.36  riastrad 	}
    820  1.26  riastrad 	default:
    821  1.26  riastrad 		rpid = waitpid(pid, &status, 0);
    822  1.26  riastrad 		if (rpid == -1)
    823  1.26  riastrad 			err(1, "waitpid");
    824  1.26  riastrad 		if (rpid != pid)
    825  1.26  riastrad 			errx(1, "waitpid returned wrong pid"
    826  1.26  riastrad 			    ": %"PRIdMAX" != %"PRIdMAX,
    827  1.26  riastrad 			    (intmax_t)rpid,
    828  1.26  riastrad 			    (intmax_t)pid);
    829  1.26  riastrad 		if (WIFEXITED(status)) {
    830  1.26  riastrad 			if (WEXITSTATUS(status) != 0)
    831  1.26  riastrad 				errx(1, "child exited with %d",
    832  1.26  riastrad 				    WEXITSTATUS(status));
    833  1.26  riastrad 		} else if (WIFSIGNALED(status)) {
    834  1.26  riastrad 			errx(1, "child terminated on signal %d",
    835  1.26  riastrad 			    WTERMSIG(status));
    836  1.26  riastrad 		} else {
    837  1.26  riastrad 			errx(1, "child died mysteriously: %d", status);
    838  1.26  riastrad 		}
    839  1.26  riastrad 	}
    840  1.26  riastrad     }
    841  1.16       dsl 
    842  1.26  riastrad 	/* XXX Test multithreaded fork safety...?  */
    843  1.10  christos 
    844  1.26  riastrad 	return 0;
    845  1.10  christos }
    846  1.26  riastrad #endif
    847