1 /*	$OpenBSD: getentropy_aix.c,v 1.9 2022/12/26 07:18:50 jmc Exp $	*/
2 
3 /*
4  * Copyright (c) 2015 Michael Felt <aixtools@gmail.com>
5  * Copyright (c) 2014 Theo de Raadt <deraadt@openbsd.org>
6  * Copyright (c) 2014 Bob Beck <beck@obtuse.com>
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  * Emulation of getentropy(2) as documented at:
21  * http://man.openbsd.org/getentropy.2
22  */
23 /*
24  * -lperfstat is needed for the pseudo entropy data
25  */
26 
27 #include <sys/mman.h>
28 #include <sys/procfs.h>
29 #include <sys/protosw.h>
30 #include <sys/resource.h>
31 #include <sys/socket.h>
32 #include <sys/stat.h>
33 #include <sys/statvfs.h>
34 #include <sys/timers.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <signal.h>
38 #include <stdio.h>
39 #include <string.h>
40 #include <termios.h>
41 
42 #include <openssl/sha.h>
43 
44 #include <libperfstat.h>
45 
46 #define REPEAT 5
47 #define MINIMUM(a, b) (((a) < (b)) ? (a) : (b))
48 
49 #define HX(a, b) \
50 	do { \
51 		if ((a)) \
52 			HD(errno); \
53 		else \
54 			HD(b); \
55 	} while (0)
56 
57 #define HR(x, l) (SHA512_Update(&ctx, (char *)(x), (l)))
58 #define HD(x)	 (SHA512_Update(&ctx, (char *)&(x), sizeof (x)))
59 #define HF(x)    (SHA512_Update(&ctx, (char *)&(x), sizeof (void*)))
60 
61 int	getentropy(void *buf, size_t len);
62 
63 static int getentropy_urandom(void *buf, size_t len, const char *path,
64     int devfscheck);
65 static int getentropy_fallback(void *buf, size_t len);
66 
67 int
getentropy(void * buf,size_t len)68 getentropy(void *buf, size_t len)
69 {
70 	int ret = -1;
71 
72 	if (len > 256) {
73 		errno = EIO;
74 		return (-1);
75 	}
76 
77 	/*
78 	 * Try to get entropy with /dev/urandom
79 	 */
80 	ret = getentropy_urandom(buf, len, "/dev/urandom", 0);
81 	if (ret != -1)
82 		return (ret);
83 
84 	/*
85 	 * Entropy collection via /dev/urandom has failed.
86 	 *
87 	 * No other API exists for collecting entropy, and we have
88 	 * no failsafe way to get it on AIX that is not sensitive
89 	 * to resource exhaustion.
90 	 *
91 	 * We have very few options:
92 	 *     - Even syslog_r is unsafe to call at this low level, so
93 	 *	 there is no way to alert the user or program.
94 	 *     - Cannot call abort() because some systems have unsafe
95 	 *	 corefiles.
96 	 *     - Could raise(SIGKILL) resulting in silent program termination.
97 	 *     - Return EIO, to hint that arc4random's stir function
98 	 *       should raise(SIGKILL)
99 	 *     - Do the best under the circumstances....
100 	 *
101 	 * This code path exists to bring light to the issue that AIX
102 	 * does not provide a failsafe API for entropy collection.
103 	 *
104 	 * We hope this demonstrates that AIX should consider
105 	 * providing a new failsafe API which works in a chroot or
106 	 * when file descriptors are exhausted.
107 	 */
108 #undef FAIL_INSTEAD_OF_TRYING_FALLBACK
109 #ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
110 	raise(SIGKILL);
111 #endif
112 	ret = getentropy_fallback(buf, len);
113 	if (ret != -1)
114 		return (ret);
115 
116 	errno = EIO;
117 	return (ret);
118 }
119 
120 static int
getentropy_urandom(void * buf,size_t len,const char * path,int devfscheck)121 getentropy_urandom(void *buf, size_t len, const char *path, int devfscheck)
122 {
123 	struct stat st;
124 	size_t i;
125 	int fd, flags;
126 	int save_errno = errno;
127 
128 start:
129 
130 	flags = O_RDONLY;
131 #ifdef O_NOFOLLOW
132 	flags |= O_NOFOLLOW;
133 #endif
134 #ifdef O_CLOEXEC
135 	flags |= O_CLOEXEC;
136 #endif
137 	fd = open(path, flags);
138 	if (fd == -1) {
139 		if (errno == EINTR)
140 			goto start;
141 		goto nodevrandom;
142 	}
143 #ifndef O_CLOEXEC
144 	fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
145 #endif
146 
147 	/* Lightly verify that the device node looks sane */
148 	if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode)) {
149 		close(fd);
150 		goto nodevrandom;
151 	}
152 	for (i = 0; i < len; ) {
153 		size_t wanted = len - i;
154 		ssize_t ret = read(fd, (char *)buf + i, wanted);
155 
156 		if (ret == -1) {
157 			if (errno == EAGAIN || errno == EINTR)
158 				continue;
159 			close(fd);
160 			goto nodevrandom;
161 		}
162 		i += ret;
163 	}
164 	close(fd);
165 	errno = save_errno;
166 	return (0);		/* satisfied */
167 nodevrandom:
168 	errno = EIO;
169 	return (-1);
170 }
171 
172 static const int cl[] = {
173 	CLOCK_REALTIME,
174 #ifdef CLOCK_MONOTONIC
175 	CLOCK_MONOTONIC,
176 #endif
177 #ifdef CLOCK_MONOTONIC_RAW
178 	CLOCK_MONOTONIC_RAW,
179 #endif
180 #ifdef CLOCK_TAI
181 	CLOCK_TAI,
182 #endif
183 #ifdef CLOCK_VIRTUAL
184 	CLOCK_VIRTUAL,
185 #endif
186 #ifdef CLOCK_UPTIME
187 	CLOCK_UPTIME,
188 #endif
189 #ifdef CLOCK_PROCESS_CPUTIME_ID
190 	CLOCK_PROCESS_CPUTIME_ID,
191 #endif
192 #ifdef CLOCK_THREAD_CPUTIME_ID
193 	CLOCK_THREAD_CPUTIME_ID,
194 #endif
195 };
196 
197 static int
getentropy_fallback(void * buf,size_t len)198 getentropy_fallback(void *buf, size_t len)
199 {
200 	uint8_t results[SHA512_DIGEST_LENGTH];
201 	int save_errno = errno, e, pgs = sysconf(_SC_PAGESIZE), faster = 0, repeat;
202 	static int cnt;
203 	struct timespec ts;
204 	struct timeval tv;
205 	perfstat_cpu_total_t cpustats;
206 #ifdef _AIX61
207 	perfstat_cpu_total_wpar_t cpustats_wpar;
208 #endif
209 	perfstat_partition_total_t lparstats;
210 	perfstat_disk_total_t diskinfo;
211 	perfstat_netinterface_total_t netinfo;
212 	struct rusage ru;
213 	sigset_t sigset;
214 	struct stat st;
215 	SHA512_CTX ctx;
216 	static pid_t lastpid;
217 	pid_t pid;
218 	size_t i, ii, m;
219 	char *p;
220 
221 	pid = getpid();
222 	if (lastpid == pid) {
223 		faster = 1;
224 		repeat = 2;
225 	} else {
226 		faster = 0;
227 		lastpid = pid;
228 		repeat = REPEAT;
229 	}
230 	for (i = 0; i < len; ) {
231 		int j;
232 		SHA512_Init(&ctx);
233 		for (j = 0; j < repeat; j++) {
234 			HX((e = gettimeofday(&tv, NULL)) == -1, tv);
235 			if (e != -1) {
236 				cnt += (int)tv.tv_sec;
237 				cnt += (int)tv.tv_usec;
238 			}
239 
240 			HX(perfstat_cpu_total(NULL, &cpustats,
241 			    sizeof(cpustats), 1) == -1, cpustats);
242 
243 #ifdef _AIX61
244 			HX(perfstat_cpu_total_wpar(NULL, &cpustats_wpar,
245 			    sizeof(cpustats_wpar), 1) == -1, cpustats_wpar);
246 #endif
247 
248 			HX(perfstat_partition_total(NULL, &lparstats,
249 			    sizeof(lparstats), 1) == -1, lparstats);
250 
251 			HX(perfstat_disk_total(NULL, &diskinfo,
252 			    sizeof(diskinfo), 1) == -1, diskinfo);
253 
254 			HX(perfstat_netinterface_total(NULL, &netinfo,
255 			    sizeof(netinfo), 1) == -1, netinfo);
256 
257 			for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]); ii++)
258 				HX(clock_gettime(cl[ii], &ts) == -1, ts);
259 
260 			HX((pid = getpid()) == -1, pid);
261 			HX((pid = getsid(pid)) == -1, pid);
262 			HX((pid = getppid()) == -1, pid);
263 			HX((pid = getpgid(0)) == -1, pid);
264 			HX((e = getpriority(0, 0)) == -1, e);
265 
266 			if (!faster) {
267 				ts.tv_sec = 0;
268 				ts.tv_nsec = 1;
269 				(void) nanosleep(&ts, NULL);
270 			}
271 
272 			HX(sigpending(&sigset) == -1, sigset);
273 			HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
274 			    sigset);
275 
276 			HF(getentropy);	/* an addr in this library */
277 			HF(printf);		/* an addr in libc */
278 			p = (char *)&p;
279 			HD(p);		/* an addr on stack */
280 			p = (char *)&errno;
281 			HD(p);		/* the addr of errno */
282 
283 			if (i == 0) {
284 				struct sockaddr_storage ss;
285 				struct statvfs stvfs;
286 				struct termios tios;
287 				socklen_t ssl;
288 				off_t off;
289 
290 				/*
291 				 * Prime-sized mappings encourage fragmentation;
292 				 * thus exposing some address entropy.
293 				 */
294 				struct mm {
295 					size_t	npg;
296 					void	*p;
297 				} mm[] =	 {
298 					{ 17, MAP_FAILED }, { 3, MAP_FAILED },
299 					{ 11, MAP_FAILED }, { 2, MAP_FAILED },
300 					{ 5, MAP_FAILED }, { 3, MAP_FAILED },
301 					{ 7, MAP_FAILED }, { 1, MAP_FAILED },
302 					{ 57, MAP_FAILED }, { 3, MAP_FAILED },
303 					{ 131, MAP_FAILED }, { 1, MAP_FAILED },
304 				};
305 
306 				for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
307 					HX(mm[m].p = mmap(NULL,
308 					    mm[m].npg * pgs,
309 					    PROT_READ|PROT_WRITE,
310 					    MAP_PRIVATE|MAP_ANON, -1,
311 					    (off_t)0), mm[m].p);
312 					if (mm[m].p != MAP_FAILED) {
313 						size_t mo;
314 
315 						/* Touch some memory... */
316 						p = mm[m].p;
317 						mo = cnt %
318 						    (mm[m].npg * pgs - 1);
319 						p[mo] = 1;
320 						cnt += (int)((long)(mm[m].p)
321 						    / pgs);
322 					}
323 
324 					/* Check cnts and times... */
325 					for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]);
326 					    ii++) {
327 						HX((e = clock_gettime(cl[ii],
328 						    &ts)) == -1, ts);
329 						if (e != -1)
330 							cnt += (int)ts.tv_nsec;
331 					}
332 
333 					HX((e = getrusage(RUSAGE_SELF,
334 					    &ru)) == -1, ru);
335 					if (e != -1) {
336 						cnt += (int)ru.ru_utime.tv_sec;
337 						cnt += (int)ru.ru_utime.tv_usec;
338 					}
339 				}
340 
341 				for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
342 					if (mm[m].p != MAP_FAILED)
343 						munmap(mm[m].p, mm[m].npg * pgs);
344 					mm[m].p = MAP_FAILED;
345 				}
346 
347 				HX(stat(".", &st) == -1, st);
348 				HX(statvfs(".", &stvfs) == -1, stvfs);
349 
350 				HX(stat("/", &st) == -1, st);
351 				HX(statvfs("/", &stvfs) == -1, stvfs);
352 
353 				HX((e = fstat(0, &st)) == -1, st);
354 				if (e == -1) {
355 					if (S_ISREG(st.st_mode) ||
356 					    S_ISFIFO(st.st_mode) ||
357 					    S_ISSOCK(st.st_mode)) {
358 						HX(fstatvfs(0, &stvfs) == -1,
359 						    stvfs);
360 						HX((off = lseek(0, (off_t)0,
361 						    SEEK_CUR)) < 0, off);
362 					}
363 					if (S_ISCHR(st.st_mode)) {
364 						HX(tcgetattr(0, &tios) == -1,
365 						    tios);
366 					} else if (S_ISSOCK(st.st_mode)) {
367 						memset(&ss, 0, sizeof ss);
368 						ssl = sizeof(ss);
369 						HX(getpeername(0,
370 						    (void *)&ss, &ssl) == -1,
371 						    ss);
372 					}
373 				}
374 
375 				HX((e = getrusage(RUSAGE_CHILDREN,
376 				    &ru)) == -1, ru);
377 				if (e != -1) {
378 					cnt += (int)ru.ru_utime.tv_sec;
379 					cnt += (int)ru.ru_utime.tv_usec;
380 				}
381 			} else {
382 				/* Subsequent hashes absorb previous result */
383 				HD(results);
384 			}
385 
386 			HX((e = gettimeofday(&tv, NULL)) == -1, tv);
387 			if (e != -1) {
388 				cnt += (int)tv.tv_sec;
389 				cnt += (int)tv.tv_usec;
390 			}
391 
392 			HD(cnt);
393 		}
394 		SHA512_Final(results, &ctx);
395 		memcpy((char *)buf + i, results, MINIMUM(sizeof(results), len - i));
396 		i += MINIMUM(sizeof(results), len - i);
397 	}
398 	explicit_bzero(&ctx, sizeof ctx);
399 	explicit_bzero(results, sizeof results);
400 	errno = save_errno;
401 	return (0);		/* satisfied */
402 }
403