1 /* $OpenBSD: arc4random_linux.h,v 1.12 2019/07/11 10:37:28 inoguchi Exp $ */
2
3 /*
4 * Copyright (c) 1996, David Mazieres <dm@uun.org>
5 * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
6 * Copyright (c) 2013, Markus Friedl <markus@openbsd.org>
7 * Copyright (c) 2014, Theo de Raadt <deraadt@openbsd.org>
8 *
9 * Permission to use, copy, modify, and distribute this software for any
10 * purpose with or without fee is hereby granted, provided that the above
11 * copyright notice and this permission notice appear in all copies.
12 *
13 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 */
21
22 /*
23 * Stub functions for portability. From LibreSSL with some adaptations.
24 */
25
26 #ifdef HAVE_SYS_MMAN_H
27 #include <sys/mman.h>
28 #endif
29
30 #include <signal.h>
31
32 /* OpenSSH isn't multithreaded */
33 #define _ARC4_LOCK()
34 #define _ARC4_UNLOCK()
35 #define _ARC4_ATFORK(f)
36
37 static inline void
_getentropy_fail(void)38 _getentropy_fail(void)
39 {
40 fatal("getentropy failed");
41 }
42
43 static volatile sig_atomic_t _rs_forked;
44
45 static inline void
_rs_forkhandler(void)46 _rs_forkhandler(void)
47 {
48 _rs_forked = 1;
49 }
50
51 static inline void
_rs_forkdetect(void)52 _rs_forkdetect(void)
53 {
54 static pid_t _rs_pid = 0;
55 pid_t pid = getpid();
56
57 if (_rs_pid == 0 || _rs_pid == 1 || _rs_pid != pid || _rs_forked) {
58 _rs_pid = pid;
59 _rs_forked = 0;
60 if (rs)
61 memset(rs, 0, sizeof(*rs));
62 }
63 }
64
65 static inline int
_rs_allocate(struct _rs ** rsp,struct _rsx ** rsxp)66 _rs_allocate(struct _rs **rsp, struct _rsx **rsxp)
67 {
68 #if defined(MAP_ANON) && defined(MAP_PRIVATE)
69 if ((*rsp = mmap(NULL, sizeof(**rsp), PROT_READ|PROT_WRITE,
70 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED)
71 return (-1);
72
73 if ((*rsxp = mmap(NULL, sizeof(**rsxp), PROT_READ|PROT_WRITE,
74 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
75 munmap(*rsp, sizeof(**rsp));
76 *rsp = NULL;
77 return (-1);
78 }
79 #else
80 if ((*rsp = calloc(1, sizeof(**rsp))) == NULL)
81 return (-1);
82 if ((*rsxp = calloc(1, sizeof(**rsxp))) == NULL) {
83 free(*rsp);
84 *rsp = NULL;
85 return (-1);
86 }
87 #endif
88
89 _ARC4_ATFORK(_rs_forkhandler);
90 return (0);
91 }
92