Sync arc4random(3) implementation from OpenBSD

Closes: #12
This commit is contained in:
Guillem Jover 2022-08-03 02:03:05 +02:00
parent 873639ebb5
commit 1f6a48b209
3 changed files with 15 additions and 9 deletions

View File

@ -1,4 +1,4 @@
.\" $OpenBSD: arc4random.3,v 1.34 2014/07/19 16:11:16 naddy Exp $
.\" $OpenBSD: arc4random.3,v 1.37 2019/09/29 16:30:35 jmc Exp $
.\"
.\" Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de>
.\" All rights reserved.
@ -30,7 +30,7 @@
.\"
.\" Manual page, using -mandoc macros
.\"
.Dd $Mdocdate: July 19 2014 $
.Dd $Mdocdate: September 29 2019 $
.Dt ARC4RANDOM 3bsd
.Os
.Sh NAME
@ -39,7 +39,7 @@
.Nm arc4random_uniform ,
.Nm arc4random_stir ,
.Nm arc4random_addrandom
.Nd arc4 random number generator
.Nd random number generator
.Sh LIBRARY
.ds str-Lb-libbsd Utility functions from BSD systems (libbsd, \-lbsd)
.ds doc-str-Lb-libbsd \*[str-Lb-libbsd]

View File

@ -1,4 +1,4 @@
/* $OpenBSD: arc4random.c,v 1.53 2015/09/10 18:53:50 bcook Exp $ */
/* $OpenBSD: arc4random.c,v 1.58 2022/07/31 13:41:45 tb Exp $ */
/*
* Copyright (c) 1996, David Mazieres <dm@uun.org>
@ -50,6 +50,8 @@
#define BLOCKSZ 64
#define RSBUFSZ (16*BLOCKSZ)
#define REKEY_BASE (1024*1024) /* NB. should be a power of 2 */
/* Marked MAP_INHERIT_ZERO, so zero'd out in fork children. */
static struct _rs {
size_t rs_have; /* valid bytes at end of rs_buf */
@ -74,10 +76,10 @@ _rs_init(unsigned char *buf, size_t n)
if (rs == NULL) {
if (_rs_allocate(&rs, &rsx) == -1)
abort();
_exit(1);
}
chacha_keysetup(&rsx->rs_chacha, buf, KEYSZ * 8, 0);
chacha_keysetup(&rsx->rs_chacha, buf, KEYSZ * 8);
chacha_ivsetup(&rsx->rs_chacha, buf + KEYSZ);
}
@ -108,6 +110,7 @@ static void
_rs_stir(void)
{
unsigned char rnd[KEYSZ + IVSZ];
uint32_t rekey_fuzz = 0;
if (getentropy(rnd, sizeof rnd) == -1)
_getentropy_fail();
@ -122,7 +125,10 @@ _rs_stir(void)
rs->rs_have = 0;
memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
rs->rs_count = 1600000;
/* rekey interval should not be predictable */
chacha_encrypt_bytes(&rsx->rs_chacha, (uint8_t *)&rekey_fuzz,
(uint8_t *)&rekey_fuzz, sizeof(rekey_fuzz));
rs->rs_count = REKEY_BASE + (rekey_fuzz % REKEY_BASE);
}
static inline void

View File

@ -4,7 +4,7 @@ D. J. Bernstein
Public domain.
*/
/* $OpenBSD: chacha_private.h,v 1.2 2013/10/04 07:02:27 djm Exp $ */
/* $OpenBSD: chacha_private.h,v 1.3 2022/02/28 21:56:29 dtucker Exp $ */
typedef unsigned char u8;
typedef unsigned int u32;
@ -52,7 +52,7 @@ static const char sigma[16] = "expand 32-byte k";
static const char tau[16] = "expand 16-byte k";
static void
chacha_keysetup(chacha_ctx *x,const u8 *k,u32 kbits,u32 ivbits)
chacha_keysetup(chacha_ctx *x,const u8 *k,u32 kbits)
{
const char *constants;