lua-symmetric

Symmetric crypto for Lua
Log | Files | Refs

getentropy_solaris.c (10911B)


      1 /*	$OpenBSD: getentropy_solaris.c,v 1.8 2014/07/19 16:12:00 deraadt Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2014 Theo de Raadt <deraadt@openbsd.org>
      5  * Copyright (c) 2014 Bob Beck <beck@obtuse.com>
      6  *
      7  * Permission to use, copy, modify, and distribute this software for any
      8  * purpose with or without fee is hereby granted, provided that the above
      9  * copyright notice and this permission notice appear in all copies.
     10  *
     11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     18  *
     19  * Emulation of getentropy(2) as documented at:
     20  * http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man2/getentropy.2
     21  */
     22 
     23 #include <sys/types.h>
     24 #include <sys/param.h>
     25 #include <sys/ioctl.h>
     26 #include <sys/resource.h>
     27 #include <sys/syscall.h>
     28 #include <sys/statvfs.h>
     29 #include <sys/socket.h>
     30 #include <sys/mount.h>
     31 #include <sys/mman.h>
     32 #include <sys/stat.h>
     33 #include <sys/time.h>
     34 #include <stdlib.h>
     35 #include <stdint.h>
     36 #include <stdio.h>
     37 #include <link.h>
     38 #include <termios.h>
     39 #include <fcntl.h>
     40 #include <signal.h>
     41 #include <string.h>
     42 #include <errno.h>
     43 #include <unistd.h>
     44 #include <time.h>
     45 #include <sys/sha2.h>
     46 #define SHA512_Init SHA512Init
     47 #define SHA512_Update SHA512Update
     48 #define SHA512_Final SHA512Final
     49 
     50 #include <sys/vfs.h>
     51 #include <sys/statfs.h>
     52 #include <sys/loadavg.h>
     53 
     54 #define REPEAT 5
     55 #define min(a, b) (((a) < (b)) ? (a) : (b))
     56 
     57 #define HX(a, b) \
     58 	do { \
     59 		if ((a)) \
     60 			HD(errno); \
     61 		else \
     62 			HD(b); \
     63 	} while (0)
     64 
     65 #define HR(x, l) (SHA512_Update(&ctx, (char *)(x), (l)))
     66 #define HD(x)	 (SHA512_Update(&ctx, (char *)&(x), sizeof (x)))
     67 #define HF(x)	 (SHA512_Update(&ctx, (char *)&(x), sizeof (void*)))
     68 
     69 int	getentropy(void *buf, size_t len);
     70 
     71 static int gotdata(char *buf, size_t len);
     72 static int getentropy_urandom(void *buf, size_t len, const char *path,
     73     int devfscheck);
     74 static int getentropy_fallback(void *buf, size_t len);
     75 static int getentropy_phdr(struct dl_phdr_info *info, size_t size, void *data);
     76 
     77 int
     78 getentropy(void *buf, size_t len)
     79 {
     80 	int ret = -1;
     81 
     82 	if (len > 256) {
     83 		errno = EIO;
     84 		return -1;
     85 	}
     86 
     87 	/*
     88 	 * Try to get entropy with /dev/urandom
     89 	 *
     90 	 * Solaris provides /dev/urandom as a symbolic link to
     91 	 * /devices/pseudo/random@0:urandom which is provided by
     92 	 * a devfs filesystem.  Best practice is to use O_NOFOLLOW,
     93 	 * so we must try the unpublished name directly.
     94 	 *
     95 	 * This can fail if the process is inside a chroot which lacks
     96 	 * the devfs mount, or if file descriptors are exhausted.
     97 	 */
     98 	ret = getentropy_urandom(buf, len,
     99 	    "/devices/pseudo/random@0:urandom", 1);
    100 	if (ret != -1)
    101 		return (ret);
    102 
    103 	/*
    104 	 * Unfortunately, chroot spaces on Solaris are sometimes setup
    105 	 * with direct device node of the well-known /dev/urandom name
    106 	 * (perhaps to avoid dragging all of devfs into the space).
    107 	 *
    108 	 * This can fail if the process is inside a chroot or if file
    109 	 * descriptors are exhausted.
    110 	 */
    111 	ret = getentropy_urandom(buf, len, "/dev/urandom", 0);
    112 	if (ret != -1)
    113 		return (ret);
    114 
    115 	/*
    116 	 * Entropy collection via /dev/urandom has failed.
    117 	 *
    118 	 * No other API exists for collecting entropy, and we have
    119 	 * no failsafe way to get it on Solaris that is not sensitive
    120 	 * to resource exhaustion.
    121 	 *
    122 	 * We have very few options:
    123 	 *     - Even syslog_r is unsafe to call at this low level, so
    124 	 *	 there is no way to alert the user or program.
    125 	 *     - Cannot call abort() because some systems have unsafe
    126 	 *	 corefiles.
    127 	 *     - Could raise(SIGKILL) resulting in silent program termination.
    128 	 *     - Return EIO, to hint that arc4random's stir function
    129 	 *       should raise(SIGKILL)
    130 	 *     - Do the best under the circumstances....
    131 	 *
    132 	 * This code path exists to bring light to the issue that Solaris
    133 	 * does not provide a failsafe API for entropy collection.
    134 	 *
    135 	 * We hope this demonstrates that Solaris should consider
    136 	 * providing a new failsafe API which works in a chroot or
    137 	 * when file descriptors are exhausted.
    138 	 */
    139 #undef FAIL_INSTEAD_OF_TRYING_FALLBACK
    140 #ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
    141 	raise(SIGKILL);
    142 #endif
    143 	ret = getentropy_fallback(buf, len);
    144 	if (ret != -1)
    145 		return (ret);
    146 
    147 	errno = EIO;
    148 	return (ret);
    149 }
    150 
    151 /*
    152  * Basic sanity checking; wish we could do better.
    153  */
    154 static int
    155 gotdata(char *buf, size_t len)
    156 {
    157 	char	any_set = 0;
    158 	size_t	i;
    159 
    160 	for (i = 0; i < len; ++i)
    161 		any_set |= buf[i];
    162 	if (any_set == 0)
    163 		return -1;
    164 	return 0;
    165 }
    166 
    167 static int
    168 getentropy_urandom(void *buf, size_t len, const char *path, int devfscheck)
    169 {
    170 	struct stat st;
    171 	size_t i;
    172 	int fd, flags;
    173 	int save_errno = errno;
    174 
    175 start:
    176 
    177 	flags = O_RDONLY;
    178 #ifdef O_NOFOLLOW
    179 	flags |= O_NOFOLLOW;
    180 #endif
    181 #ifdef O_CLOEXEC
    182 	flags |= O_CLOEXEC;
    183 #endif
    184 	fd = open(path, flags, 0);
    185 	if (fd == -1) {
    186 		if (errno == EINTR)
    187 			goto start;
    188 		goto nodevrandom;
    189 	}
    190 #ifndef O_CLOEXEC
    191 	fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
    192 #endif
    193 
    194 	/* Lightly verify that the device node looks sane */
    195 	if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode) ||
    196 	    (devfscheck && (strcmp(st.st_fstype, "devfs") != 0))) {
    197 		close(fd);
    198 		goto nodevrandom;
    199 	}
    200 	for (i = 0; i < len; ) {
    201 		size_t wanted = len - i;
    202 		ssize_t ret = read(fd, (char *)buf + i, wanted);
    203 
    204 		if (ret == -1) {
    205 			if (errno == EAGAIN || errno == EINTR)
    206 				continue;
    207 			close(fd);
    208 			goto nodevrandom;
    209 		}
    210 		i += ret;
    211 	}
    212 	close(fd);
    213 	if (gotdata(buf, len) == 0) {
    214 		errno = save_errno;
    215 		return 0;		/* satisfied */
    216 	}
    217 nodevrandom:
    218 	errno = EIO;
    219 	return -1;
    220 }
    221 
    222 static const int cl[] = {
    223 	CLOCK_REALTIME,
    224 #ifdef CLOCK_MONOTONIC
    225 	CLOCK_MONOTONIC,
    226 #endif
    227 #ifdef CLOCK_MONOTONIC_RAW
    228 	CLOCK_MONOTONIC_RAW,
    229 #endif
    230 #ifdef CLOCK_TAI
    231 	CLOCK_TAI,
    232 #endif
    233 #ifdef CLOCK_VIRTUAL
    234 	CLOCK_VIRTUAL,
    235 #endif
    236 #ifdef CLOCK_UPTIME
    237 	CLOCK_UPTIME,
    238 #endif
    239 #ifdef CLOCK_PROCESS_CPUTIME_ID
    240 	CLOCK_PROCESS_CPUTIME_ID,
    241 #endif
    242 #ifdef CLOCK_THREAD_CPUTIME_ID
    243 	CLOCK_THREAD_CPUTIME_ID,
    244 #endif
    245 };
    246 
    247 static int
    248 getentropy_phdr(struct dl_phdr_info *info, size_t size, void *data)
    249 {
    250 	SHA512_CTX *ctx = data;
    251 
    252 	SHA512_Update(ctx, &info->dlpi_addr, sizeof (info->dlpi_addr));
    253 	return 0;
    254 }
    255 
    256 static int
    257 getentropy_fallback(void *buf, size_t len)
    258 {
    259 	uint8_t results[SHA512_DIGEST_LENGTH];
    260 	int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat;
    261 	static int cnt;
    262 	struct timespec ts;
    263 	struct timeval tv;
    264 	double loadavg[3];
    265 	struct rusage ru;
    266 	sigset_t sigset;
    267 	struct stat st;
    268 	SHA512_CTX ctx;
    269 	static pid_t lastpid;
    270 	pid_t pid;
    271 	size_t i, ii, m;
    272 	char *p;
    273 
    274 	pid = getpid();
    275 	if (lastpid == pid) {
    276 		faster = 1;
    277 		repeat = 2;
    278 	} else {
    279 		faster = 0;
    280 		lastpid = pid;
    281 		repeat = REPEAT;
    282 	}
    283 	for (i = 0; i < len; ) {
    284 		int j;
    285 		SHA512_Init(&ctx);
    286 		for (j = 0; j < repeat; j++) {
    287 			HX((e = gettimeofday(&tv, NULL)) == -1, tv);
    288 			if (e != -1) {
    289 				cnt += (int)tv.tv_sec;
    290 				cnt += (int)tv.tv_usec;
    291 			}
    292 
    293 			dl_iterate_phdr(getentropy_phdr, &ctx);
    294 
    295 			for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]); ii++)
    296 				HX(clock_gettime(cl[ii], &ts) == -1, ts);
    297 
    298 			HX((pid = getpid()) == -1, pid);
    299 			HX((pid = getsid(pid)) == -1, pid);
    300 			HX((pid = getppid()) == -1, pid);
    301 			HX((pid = getpgid(0)) == -1, pid);
    302 			HX((e = getpriority(0, 0)) == -1, e);
    303 			HX((getloadavg(loadavg, 3) == -1), loadavg);
    304 
    305 			if (!faster) {
    306 				ts.tv_sec = 0;
    307 				ts.tv_nsec = 1;
    308 				(void) nanosleep(&ts, NULL);
    309 			}
    310 
    311 			HX(sigpending(&sigset) == -1, sigset);
    312 			HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
    313 			    sigset);
    314 
    315 			HF(getentropy);	/* an addr in this library */
    316 			HF(printf);		/* an addr in libc */
    317 			p = (char *)&p;
    318 			HD(p);		/* an addr on stack */
    319 			p = (char *)&errno;
    320 			HD(p);		/* the addr of errno */
    321 
    322 			if (i == 0) {
    323 				struct sockaddr_storage ss;
    324 				struct statvfs stvfs;
    325 				struct termios tios;
    326 				socklen_t ssl;
    327 				off_t off;
    328 
    329 				/*
    330 				 * Prime-sized mappings encourage fragmentation;
    331 				 * thus exposing some address entropy.
    332 				 */
    333 				struct mm {
    334 					size_t	npg;
    335 					void	*p;
    336 				} mm[] =	 {
    337 					{ 17, MAP_FAILED }, { 3, MAP_FAILED },
    338 					{ 11, MAP_FAILED }, { 2, MAP_FAILED },
    339 					{ 5, MAP_FAILED }, { 3, MAP_FAILED },
    340 					{ 7, MAP_FAILED }, { 1, MAP_FAILED },
    341 					{ 57, MAP_FAILED }, { 3, MAP_FAILED },
    342 					{ 131, MAP_FAILED }, { 1, MAP_FAILED },
    343 				};
    344 
    345 				for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
    346 					HX(mm[m].p = mmap(NULL,
    347 					    mm[m].npg * pgs,
    348 					    PROT_READ|PROT_WRITE,
    349 					    MAP_PRIVATE|MAP_ANON, -1,
    350 					    (off_t)0), mm[m].p);
    351 					if (mm[m].p != MAP_FAILED) {
    352 						size_t mo;
    353 
    354 						/* Touch some memory... */
    355 						p = mm[m].p;
    356 						mo = cnt %
    357 						    (mm[m].npg * pgs - 1);
    358 						p[mo] = 1;
    359 						cnt += (int)((long)(mm[m].p)
    360 						    / pgs);
    361 					}
    362 
    363 					/* Check cnts and times... */
    364 					for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]);
    365 					    ii++) {
    366 						HX((e = clock_gettime(cl[ii],
    367 						    &ts)) == -1, ts);
    368 						if (e != -1)
    369 							cnt += (int)ts.tv_nsec;
    370 					}
    371 
    372 					HX((e = getrusage(RUSAGE_SELF,
    373 					    &ru)) == -1, ru);
    374 					if (e != -1) {
    375 						cnt += (int)ru.ru_utime.tv_sec;
    376 						cnt += (int)ru.ru_utime.tv_usec;
    377 					}
    378 				}
    379 
    380 				for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
    381 					if (mm[m].p != MAP_FAILED)
    382 						munmap(mm[m].p, mm[m].npg * pgs);
    383 					mm[m].p = MAP_FAILED;
    384 				}
    385 
    386 				HX(stat(".", &st) == -1, st);
    387 				HX(statvfs(".", &stvfs) == -1, stvfs);
    388 
    389 				HX(stat("/", &st) == -1, st);
    390 				HX(statvfs("/", &stvfs) == -1, stvfs);
    391 
    392 				HX((e = fstat(0, &st)) == -1, st);
    393 				if (e == -1) {
    394 					if (S_ISREG(st.st_mode) ||
    395 					    S_ISFIFO(st.st_mode) ||
    396 					    S_ISSOCK(st.st_mode)) {
    397 						HX(fstatvfs(0, &stvfs) == -1,
    398 						    stvfs);
    399 						HX((off = lseek(0, (off_t)0,
    400 						    SEEK_CUR)) < 0, off);
    401 					}
    402 					if (S_ISCHR(st.st_mode)) {
    403 						HX(tcgetattr(0, &tios) == -1,
    404 						    tios);
    405 					} else if (S_ISSOCK(st.st_mode)) {
    406 						memset(&ss, 0, sizeof ss);
    407 						ssl = sizeof(ss);
    408 						HX(getpeername(0,
    409 						    (void *)&ss, &ssl) == -1,
    410 						    ss);
    411 					}
    412 				}
    413 
    414 				HX((e = getrusage(RUSAGE_CHILDREN,
    415 				    &ru)) == -1, ru);
    416 				if (e != -1) {
    417 					cnt += (int)ru.ru_utime.tv_sec;
    418 					cnt += (int)ru.ru_utime.tv_usec;
    419 				}
    420 			} else {
    421 				/* Subsequent hashes absorb previous result */
    422 				HD(results);
    423 			}
    424 
    425 			HX((e = gettimeofday(&tv, NULL)) == -1, tv);
    426 			if (e != -1) {
    427 				cnt += (int)tv.tv_sec;
    428 				cnt += (int)tv.tv_usec;
    429 			}
    430 
    431 			HD(cnt);
    432 		}
    433 		SHA512_Final(results, &ctx);
    434 		memcpy((char *)buf + i, results, min(sizeof(results), len - i));
    435 		i += min(sizeof(results), len - i);
    436 	}
    437 	explicit_bzero(&ctx, sizeof ctx);
    438 	explicit_bzero(results, sizeof results);
    439 	if (gotdata(buf, len) == 0) {
    440 		errno = save_errno;
    441 		return 0;		/* satisfied */
    442 	}
    443 	errno = EIO;
    444 	return -1;
    445 }