Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sudo-project
GitHub Repository: sudo-project/sudo
Path: blob/main/lib/util/arc4random_uniform.c
1532 views
1
/* $OpenBSD: arc4random_uniform.c,v 1.2 2015/09/13 08:31:47 guenther Exp $ */
2
3
/*
4
* SPDX-License-Identifier: ISC
5
*
6
* Copyright (c) 2008, Damien Miller <[email protected]>
7
*
8
* Permission to use, copy, modify, and distribute this software for any
9
* purpose with or without fee is hereby granted, provided that the above
10
* copyright notice and this permission notice appear in all copies.
11
*
12
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19
*/
20
21
#include <config.h>
22
23
#ifndef HAVE_ARC4RANDOM_UNIFORM
24
25
#include <stdlib.h>
26
#if defined(HAVE_STDINT_H)
27
# include <stdint.h>
28
#elif defined(HAVE_INTTYPES_H)
29
# include <inttypes.h>
30
#endif
31
32
#include <sudo_compat.h>
33
#include <sudo_rand.h>
34
35
/*
36
* Calculate a uniformly distributed random number less than upper_bound
37
* avoiding "modulo bias".
38
*
39
* Uniformity is achieved by generating new random numbers until the one
40
* returned is outside the range [0, 2**32 % upper_bound). This
41
* guarantees the selected random number will be inside
42
* [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
43
* after reduction modulo upper_bound.
44
*/
45
uint32_t
46
sudo_arc4random_uniform(uint32_t upper_bound)
47
{
48
uint32_t r, min;
49
50
if (upper_bound < 2)
51
return 0;
52
53
/* 2**32 % x == (2**32 - x) % x */
54
min = -upper_bound % upper_bound;
55
56
/*
57
* This could theoretically loop forever but each retry has
58
* p > 0.5 (worst case, usually far better) of selecting a
59
* number inside the range we need, so it should rarely need
60
* to re-roll.
61
*/
62
for (;;) {
63
r = arc4random();
64
if (r >= min)
65
break;
66
}
67
68
return r % upper_bound;
69
}
70
71
#endif /* HAVE_ARC4RANDOM_UNIFORM */
72
73