xref: /titanic_50/usr/src/uts/common/crypto/api/kcf_random.c (revision adecd3c68045d04dc367d30faf2eb5cac1f45d5a)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * This file implements the interfaces that the /dev/random
30  * driver uses for read(2), write(2) and poll(2) on /dev/random or
31  * /dev/urandom. It also implements the kernel API - random_add_entropy(),
32  * random_get_pseudo_bytes() and random_get_bytes().
33  *
34  * We periodically collect random bits from providers which are registered
35  * with the Kernel Cryptographic Framework (kCF) as capable of random
36  * number generation. The random bits are maintained in a cache and
37  * it is used for high quality random numbers (/dev/random) requests.
38  * We pick a provider and call its SPI routine, if the cache does not have
39  * enough bytes to satisfy a request.
40  *
41  * /dev/urandom requests use a software-based generator algorithm that uses the
42  * random bits in the cache as a seed. We create one pseudo-random generator
43  * (for /dev/urandom) per possible CPU on the system, and use it,
44  * kmem-magazine-style, to avoid cache line contention.
45  *
46  * LOCKING HIERARCHY:
47  *	1) rmp->rm_lock protects the per-cpu pseudo-random generators.
48  * 	2) rndpool_lock protects the high-quality randomness pool.
49  *		It may be locked while a rmp->rm_lock is held.
50  *
51  * A history note: The kernel API and the software-based algorithms in this
52  * file used to be part of the /dev/random driver.
53  */
54 
55 #include <sys/types.h>
56 #include <sys/conf.h>
57 #include <sys/sunddi.h>
58 #include <sys/disp.h>
59 #include <sys/modctl.h>
60 #include <sys/ddi.h>
61 #include <sys/crypto/common.h>
62 #include <sys/crypto/api.h>
63 #include <sys/crypto/impl.h>
64 #include <sys/crypto/sched_impl.h>
65 #include <sys/random.h>
66 #include <sys/sha1.h>
67 #include <sys/time.h>
68 #include <sys/sysmacros.h>
69 #include <sys/cpuvar.h>
70 #include <sys/taskq.h>
71 
72 #define	RNDPOOLSIZE		1024	/* Pool size in bytes */
73 #define	MINEXTRACTBYTES		20
74 #define	MAXEXTRACTBYTES		1024
75 #define	PRNG_MAXOBLOCKS		1310720	/* Max output block per prng key */
76 #define	TIMEOUT_INTERVAL	5	/* Periodic mixing interval in secs */
77 
78 typedef enum    extract_type {
79 	NONBLOCK_EXTRACT,
80 	BLOCKING_EXTRACT,
81 	ALWAYS_EXTRACT
82 } extract_type_t;
83 
84 /*
85  * Hash-algo generic definitions. For now, they are SHA1's. We use SHA1
86  * routines directly instead of using k-API because we can't return any
87  * error code in /dev/urandom case and we can get an error using k-API
88  * if a mechanism is disabled.
89  */
90 #define	HASHSIZE		20
91 #define	HASH_CTX		SHA1_CTX
92 #define	HashInit(ctx)		SHA1Init((ctx))
93 #define	HashUpdate(ctx, p, s)	SHA1Update((ctx), (p), (s))
94 #define	HashFinal(d, ctx)	SHA1Final((d), (ctx))
95 
96 /* HMAC-SHA1 */
97 #define	HMAC_KEYSIZE			20
98 #define	HMAC_BLOCK_SIZE			64
99 #define	HMAC_KEYSCHED			sha1keysched_t
100 #define	SET_ENCRYPT_KEY(k, s, ks)	hmac_key((k), (s), (ks))
101 #define	HMAC_ENCRYPT(ks, p, s, d)	hmac_encr((ks), (uint8_t *)(p), s, d)
102 
103 /* HMAC-SHA1 "keyschedule" */
104 typedef struct sha1keysched_s {
105 	SHA1_CTX ictx;
106 	SHA1_CTX octx;
107 } sha1keysched_t;
108 
109 /*
110  * Cache of random bytes implemented as a circular buffer. findex and rindex
111  * track the front and back of the circular buffer.
112  */
113 uint8_t rndpool[RNDPOOLSIZE];
114 static int findex, rindex;
115 static int rnbyte_cnt;		/* Number of bytes in the cache */
116 
117 static kmutex_t rndpool_lock;	/* protects r/w accesses to the cache, */
118 				/* and the global variables */
119 static kcondvar_t rndpool_read_cv; /* serializes poll/read syscalls */
120 static int num_waiters;		/* #threads waiting to read from /dev/random */
121 
122 static struct pollhead rnd_pollhead;
123 static timeout_id_t kcf_rndtimeout_id;
124 static crypto_mech_type_t rngmech_type = CRYPTO_MECH_INVALID;
125 rnd_stats_t rnd_stats;
126 static boolean_t rng_prov_found = B_TRUE;
127 static boolean_t rng_ok_to_log = B_TRUE;
128 
129 static void rndc_addbytes(uint8_t *, size_t);
130 static void rndc_getbytes(uint8_t *ptr, size_t len);
131 static void rnd_handler(void *);
132 static void rnd_alloc_magazines();
133 static void hmac_key(uint8_t *, size_t, void *);
134 static void hmac_encr(void *, uint8_t *, size_t, uint8_t *);
135 
136 
137 void
138 kcf_rnd_init()
139 {
140 	hrtime_t ts;
141 	time_t now;
142 
143 	mutex_init(&rndpool_lock, NULL, MUTEX_DEFAULT, NULL);
144 	cv_init(&rndpool_read_cv, NULL, CV_DEFAULT, NULL);
145 
146 	/*
147 	 * Add bytes to the cache using
148 	 * . 2 unpredictable times: high resolution time since the boot-time,
149 	 *   and the current time-of-the day.
150 	 * This is used only to make the timeout value in the timer
151 	 * unpredictable.
152 	 */
153 	ts = gethrtime();
154 	rndc_addbytes((uint8_t *)&ts, sizeof (ts));
155 
156 	(void) drv_getparm(TIME, &now);
157 	rndc_addbytes((uint8_t *)&now, sizeof (now));
158 
159 	rnbyte_cnt = 0;
160 	findex = rindex = 0;
161 	num_waiters = 0;
162 	rngmech_type = KCF_MECHID(KCF_MISC_CLASS, 0);
163 
164 	rnd_alloc_magazines();
165 }
166 
167 /*
168  * Return TRUE if at least one provider exists that can
169  * supply random numbers.
170  */
171 boolean_t
172 kcf_rngprov_check(void)
173 {
174 	int rv;
175 	kcf_provider_desc_t *pd;
176 
177 	if ((pd = kcf_get_mech_provider(rngmech_type, NULL, &rv,
178 	    NULL, CRYPTO_FG_RANDOM, B_FALSE, 0)) != NULL) {
179 		KCF_PROV_REFRELE(pd);
180 		/*
181 		 * We logged a warning once about no provider being available
182 		 * and now a provider became available. So, set the flag so
183 		 * that we can log again if the problem recurs.
184 		 */
185 		rng_ok_to_log = B_TRUE;
186 		rng_prov_found = B_TRUE;
187 		return (B_TRUE);
188 	} else {
189 		rng_prov_found = B_FALSE;
190 		return (B_FALSE);
191 	}
192 }
193 
194 /*
195  * Pick a software-based provider and submit a request to seed
196  * its random number generator.
197  */
198 static void
199 rngprov_seed(uint8_t *buf, int len, uint_t entropy_est, uint32_t flags)
200 {
201 	kcf_provider_desc_t *pd = NULL;
202 
203 	if (kcf_get_sw_prov(rngmech_type, &pd, B_FALSE) == CRYPTO_SUCCESS) {
204 		(void) KCF_PROV_SEED_RANDOM(pd, pd->pd_sid, buf, len,
205 		    entropy_est, flags, NULL);
206 		KCF_PROV_REFRELE(pd);
207 	}
208 }
209 
210 /* Boot-time tunable for experimentation. */
211 int kcf_limit_hwrng = 1;
212 
213 
214 /*
215  * This routine is called for blocking reads.
216  *
217  * The argument from_user_api indicates whether the caller is
218  * from userland coming via the /dev/random driver.
219  *
220  * The argument is_taskq_thr indicates whether the caller is
221  * the taskq thread dispatched by the timeout handler routine.
222  * In this case, we cycle through all the providers
223  * submitting a request to each provider to generate random numbers.
224  *
225  * For other cases, we pick a provider and submit a request to generate
226  * random numbers. We retry using another provider if we get an error.
227  *
228  * Returns the number of bytes that are written to 'ptr'. Returns -1
229  * if no provider is found. ptr and need are unchanged.
230  */
231 static int
232 rngprov_getbytes(uint8_t *ptr, size_t need, boolean_t from_user_api,
233     boolean_t is_taskq_thr)
234 {
235 	int rv;
236 	int prov_cnt = 0;
237 	int total_bytes = 0;
238 	kcf_provider_desc_t *pd;
239 	kcf_req_params_t params;
240 	kcf_prov_tried_t *list = NULL;
241 
242 	while ((pd = kcf_get_mech_provider(rngmech_type, NULL, &rv,
243 	    list, CRYPTO_FG_RANDOM, B_FALSE, 0)) != NULL) {
244 
245 		prov_cnt++;
246 		/*
247 		 * Typically a hardware RNG is a multi-purpose
248 		 * crypto card and hence we do not want to overload the card
249 		 * just for random numbers. The following check is to prevent
250 		 * a user process from hogging the hardware RNG. Note that we
251 		 * still use the hardware RNG from the periodically run
252 		 * taskq thread.
253 		 */
254 		if (pd->pd_prov_type == CRYPTO_HW_PROVIDER && from_user_api &&
255 		    kcf_limit_hwrng == 1) {
256 			ASSERT(is_taskq_thr == B_FALSE);
257 			goto try_next;
258 		}
259 
260 		KCF_WRAP_RANDOM_OPS_PARAMS(&params, KCF_OP_RANDOM_GENERATE,
261 		    pd->pd_sid, ptr, need, 0, 0);
262 		rv = kcf_submit_request(pd, NULL, NULL, &params, B_FALSE);
263 		ASSERT(rv != CRYPTO_QUEUED);
264 
265 		if (rv == CRYPTO_SUCCESS) {
266 			total_bytes += need;
267 			if (is_taskq_thr)
268 				rndc_addbytes(ptr, need);
269 			else {
270 				KCF_PROV_REFRELE(pd);
271 				break;
272 			}
273 		}
274 
275 		if (is_taskq_thr || rv != CRYPTO_SUCCESS) {
276 try_next:
277 			/* Add pd to the linked list of providers tried. */
278 			if (kcf_insert_triedlist(&list, pd, KM_SLEEP) == NULL) {
279 				KCF_PROV_REFRELE(pd);
280 				break;
281 			}
282 		}
283 
284 	}
285 
286 	if (list != NULL)
287 		kcf_free_triedlist(list);
288 
289 	if (prov_cnt == 0) { /* no provider could be found. */
290 		rng_prov_found = B_FALSE;
291 		return (-1);
292 	} else {
293 		rng_prov_found = B_TRUE;
294 		/* See comments in kcf_rngprov_check() */
295 		rng_ok_to_log = B_TRUE;
296 	}
297 
298 	return (total_bytes);
299 }
300 
301 static void
302 notify_done(void *arg, int rv)
303 {
304 	uchar_t *rndbuf = arg;
305 
306 	if (rv == CRYPTO_SUCCESS)
307 		rndc_addbytes(rndbuf, MINEXTRACTBYTES);
308 
309 	bzero(rndbuf, MINEXTRACTBYTES);
310 	kmem_free(rndbuf, MINEXTRACTBYTES);
311 }
312 
313 /*
314  * Cycle through all the providers submitting a request to each provider
315  * to generate random numbers. This is called for the modes - NONBLOCK_EXTRACT
316  * and ALWAYS_EXTRACT.
317  *
318  * Returns the number of bytes that are written to 'ptr'. Returns -1
319  * if no provider is found. ptr and len are unchanged.
320  */
321 static int
322 rngprov_getbytes_nblk(uint8_t *ptr, size_t len, boolean_t from_user_api)
323 {
324 	int rv, blen, total_bytes;
325 	uchar_t *rndbuf;
326 	kcf_provider_desc_t *pd;
327 	kcf_req_params_t params;
328 	crypto_call_req_t req;
329 	kcf_prov_tried_t *list = NULL;
330 	int prov_cnt = 0;
331 
332 	blen = 0;
333 	total_bytes = 0;
334 	req.cr_flag = CRYPTO_SKIP_REQID;
335 	req.cr_callback_func = notify_done;
336 
337 	while ((pd = kcf_get_mech_provider(rngmech_type, NULL, &rv,
338 	    list, CRYPTO_FG_RANDOM, CHECK_RESTRICT(&req), 0)) != NULL) {
339 
340 		prov_cnt ++;
341 		switch (pd->pd_prov_type) {
342 		case CRYPTO_HW_PROVIDER:
343 			/* See comments in rngprov_getbytes() */
344 			if (from_user_api && kcf_limit_hwrng == 1)
345 				goto try_next;
346 
347 			/*
348 			 * We have to allocate a buffer here as we can not
349 			 * assume that the input buffer will remain valid
350 			 * when the callback comes. We use a fixed size buffer
351 			 * to simplify the book keeping.
352 			 */
353 			rndbuf = kmem_alloc(MINEXTRACTBYTES, KM_NOSLEEP);
354 			if (rndbuf == NULL) {
355 				KCF_PROV_REFRELE(pd);
356 				if (list != NULL)
357 					kcf_free_triedlist(list);
358 				return (total_bytes);
359 			}
360 			req.cr_callback_arg = rndbuf;
361 			KCF_WRAP_RANDOM_OPS_PARAMS(&params,
362 			    KCF_OP_RANDOM_GENERATE,
363 			    pd->pd_sid, rndbuf, MINEXTRACTBYTES, 0, 0);
364 			break;
365 
366 		case CRYPTO_SW_PROVIDER:
367 			/*
368 			 * We do not need to allocate a buffer in the software
369 			 * provider case as there is no callback involved. We
370 			 * avoid any extra data copy by directly passing 'ptr'.
371 			 */
372 			KCF_WRAP_RANDOM_OPS_PARAMS(&params,
373 			    KCF_OP_RANDOM_GENERATE,
374 			    pd->pd_sid, ptr, len, 0, 0);
375 			break;
376 		}
377 
378 		rv = kcf_submit_request(pd, NULL, &req, &params, B_FALSE);
379 		if (rv == CRYPTO_SUCCESS) {
380 			switch (pd->pd_prov_type) {
381 			case CRYPTO_HW_PROVIDER:
382 				/*
383 				 * Since we have the input buffer handy,
384 				 * we directly copy to it rather than
385 				 * adding to the pool.
386 				 */
387 				blen = min(MINEXTRACTBYTES, len);
388 				bcopy(rndbuf, ptr, blen);
389 				if (len < MINEXTRACTBYTES)
390 					rndc_addbytes(rndbuf + len,
391 					    MINEXTRACTBYTES - len);
392 				ptr += blen;
393 				len -= blen;
394 				total_bytes += blen;
395 				break;
396 
397 			case CRYPTO_SW_PROVIDER:
398 				total_bytes += len;
399 				len = 0;
400 				break;
401 			}
402 		}
403 
404 		/*
405 		 * We free the buffer in the callback routine
406 		 * for the CRYPTO_QUEUED case.
407 		 */
408 		if (pd->pd_prov_type == CRYPTO_HW_PROVIDER &&
409 		    rv != CRYPTO_QUEUED) {
410 			bzero(rndbuf, MINEXTRACTBYTES);
411 			kmem_free(rndbuf, MINEXTRACTBYTES);
412 		}
413 
414 		if (len == 0) {
415 			KCF_PROV_REFRELE(pd);
416 			break;
417 		}
418 
419 		if (rv != CRYPTO_SUCCESS) {
420 try_next:
421 			/* Add pd to the linked list of providers tried. */
422 			if (kcf_insert_triedlist(&list, pd, KM_NOSLEEP) ==
423 			    NULL) {
424 				KCF_PROV_REFRELE(pd);
425 				break;
426 			}
427 		}
428 	}
429 
430 	if (list != NULL) {
431 		kcf_free_triedlist(list);
432 	}
433 
434 	if (prov_cnt == 0) { /* no provider could be found. */
435 		rng_prov_found = B_FALSE;
436 		return (-1);
437 	} else {
438 		rng_prov_found = B_TRUE;
439 		/* See comments in kcf_rngprov_check() */
440 		rng_ok_to_log = B_TRUE;
441 	}
442 
443 	return (total_bytes);
444 }
445 
446 static void
447 rngprov_task(void *arg)
448 {
449 	int len = (int)(uintptr_t)arg;
450 	uchar_t tbuf[MAXEXTRACTBYTES];
451 
452 	ASSERT(len <= MAXEXTRACTBYTES);
453 	(void) rngprov_getbytes(tbuf, len, B_FALSE, B_TRUE);
454 }
455 
456 /*
457  * Returns "len" random or pseudo-random bytes in *ptr.
458  * Will block if not enough random bytes are available and the
459  * call is blocking.
460  *
461  * Called with rndpool_lock held (allowing caller to do optimistic locking;
462  * releases the lock before return).
463  */
464 static int
465 rnd_get_bytes(uint8_t *ptr, size_t len, extract_type_t how,
466     boolean_t from_user_api)
467 {
468 	int bytes;
469 	size_t got;
470 
471 	ASSERT(mutex_owned(&rndpool_lock));
472 	/*
473 	 * Check if the request can be satisfied from the cache
474 	 * of random bytes.
475 	 */
476 	if (len <= rnbyte_cnt) {
477 		rndc_getbytes(ptr, len);
478 		mutex_exit(&rndpool_lock);
479 		return (0);
480 	}
481 	mutex_exit(&rndpool_lock);
482 
483 	switch (how) {
484 	case BLOCKING_EXTRACT:
485 		if ((got = rngprov_getbytes(ptr, len, from_user_api,
486 		    B_FALSE)) == -1)
487 			break;	/* No provider found */
488 
489 		if (got == len)
490 			return (0);
491 		len -= got;
492 		ptr += got;
493 		break;
494 
495 	case NONBLOCK_EXTRACT:
496 	case ALWAYS_EXTRACT:
497 		if ((got = rngprov_getbytes_nblk(ptr, len,
498 		    from_user_api)) == -1) {
499 			/* No provider found */
500 			if (how == NONBLOCK_EXTRACT) {
501 				return (EAGAIN);
502 			}
503 		} else {
504 			if (got == len)
505 				return (0);
506 			len -= got;
507 			ptr += got;
508 		}
509 		if (how == NONBLOCK_EXTRACT && (rnbyte_cnt < len))
510 			return (EAGAIN);
511 		break;
512 	}
513 
514 	mutex_enter(&rndpool_lock);
515 	while (len > 0) {
516 		if (how == BLOCKING_EXTRACT) {
517 			/* Check if there is enough */
518 			while (rnbyte_cnt < MINEXTRACTBYTES) {
519 				num_waiters++;
520 				if (cv_wait_sig(&rndpool_read_cv,
521 				    &rndpool_lock) == 0) {
522 					num_waiters--;
523 					mutex_exit(&rndpool_lock);
524 					return (EINTR);
525 				}
526 				num_waiters--;
527 			}
528 		}
529 
530 		/* Figure out how many bytes to extract */
531 		bytes = min(len, rnbyte_cnt);
532 		rndc_getbytes(ptr, bytes);
533 
534 		len -= bytes;
535 		ptr += bytes;
536 
537 		if (len > 0 && how == ALWAYS_EXTRACT) {
538 			/*
539 			 * There are not enough bytes, but we can not block.
540 			 * This only happens in the case of /dev/urandom which
541 			 * runs an additional generation algorithm. So, there
542 			 * is no problem.
543 			 */
544 			while (len > 0) {
545 				*ptr = rndpool[findex];
546 				ptr++; len--;
547 				rindex = findex = (findex + 1) &
548 				    (RNDPOOLSIZE - 1);
549 			}
550 			break;
551 		}
552 	}
553 
554 	mutex_exit(&rndpool_lock);
555 	return (0);
556 }
557 
558 int
559 kcf_rnd_get_bytes(uint8_t *ptr, size_t len, boolean_t noblock,
560     boolean_t from_user_api)
561 {
562 	extract_type_t how;
563 	int error;
564 
565 	how = noblock ? NONBLOCK_EXTRACT : BLOCKING_EXTRACT;
566 	mutex_enter(&rndpool_lock);
567 	if ((error = rnd_get_bytes(ptr, len, how, from_user_api)) != 0)
568 		return (error);
569 
570 	BUMP_RND_STATS(rs_rndOut, len);
571 	return (0);
572 }
573 
574 /*
575  * Revisit this if the structs grow or we come up with a better way
576  * of cache-line-padding structures.
577  */
578 #define	RND_CPU_CACHE_SIZE	64
579 #define	RND_CPU_PAD_SIZE	RND_CPU_CACHE_SIZE*5
580 #define	RND_CPU_PAD (RND_CPU_PAD_SIZE - \
581 	(sizeof (kmutex_t) + 3*sizeof (uint8_t *) + sizeof (HMAC_KEYSCHED) + \
582 	sizeof (uint64_t) + 3*sizeof (uint32_t) + sizeof (rnd_stats_t)))
583 
584 /*
585  * Per-CPU random state.  Somewhat like like kmem's magazines, this provides
586  * a per-CPU instance of the pseudo-random generator.  We have it much easier
587  * than kmem, as we can afford to "leak" random bits if a CPU is DR'ed out.
588  *
589  * Note that this usage is preemption-safe; a thread
590  * entering a critical section remembers which generator it locked
591  * and unlocks the same one; should it be preempted and wind up running on
592  * a different CPU, there will be a brief period of increased contention
593  * before it exits the critical section but nothing will melt.
594  */
595 typedef struct rndmag_s
596 {
597 	kmutex_t	rm_lock;
598 	uint8_t 	*rm_buffer;	/* Start of buffer */
599 	uint8_t		*rm_eptr;	/* End of buffer */
600 	uint8_t		*rm_rptr;	/* Current read pointer */
601 	HMAC_KEYSCHED 	rm_ks;		/* seed */
602 	uint64_t 	rm_counter;	/* rotating counter for extracting */
603 	uint32_t	rm_oblocks;	/* time to rekey? */
604 	uint32_t	rm_ofuzz;	/* Rekey backoff state */
605 	uint32_t	rm_olimit;	/* Hard rekey limit */
606 	rnd_stats_t	rm_stats;	/* Per-CPU Statistics */
607 	uint8_t		rm_pad[RND_CPU_PAD];
608 } rndmag_t;
609 
610 /*
611  * Generate random bytes for /dev/urandom by encrypting a
612  * rotating counter with a key created from bytes extracted
613  * from the pool.  A maximum of PRNG_MAXOBLOCKS output blocks
614  * is generated before a new key is obtained.
615  *
616  * Note that callers to this routine are likely to assume it can't fail.
617  *
618  * Called with rmp locked; releases lock.
619  */
620 static int
621 rnd_generate_pseudo_bytes(rndmag_t *rmp, uint8_t *ptr, size_t len)
622 {
623 	size_t bytes = len;
624 	int nblock, size;
625 	uint32_t oblocks;
626 	uint8_t digest[HASHSIZE];
627 
628 	ASSERT(mutex_owned(&rmp->rm_lock));
629 
630 	/* Nothing is being asked */
631 	if (len == 0) {
632 		mutex_exit(&rmp->rm_lock);
633 		return (0);
634 	}
635 
636 	nblock = howmany(len, HASHSIZE);
637 
638 	rmp->rm_oblocks += nblock;
639 	oblocks = rmp->rm_oblocks;
640 
641 	do {
642 		if (oblocks >= rmp->rm_olimit) {
643 			hrtime_t timestamp;
644 			uint8_t key[HMAC_KEYSIZE];
645 
646 			/*
647 			 * Contention-avoiding rekey: see if
648 			 * the pool is locked, and if so, wait a bit.
649 			 * Do an 'exponential back-in' to ensure we don't
650 			 * run too long without rekey.
651 			 */
652 			if (rmp->rm_ofuzz) {
653 				/*
654 				 * Decaying exponential back-in for rekey.
655 				 */
656 				if ((rnbyte_cnt < MINEXTRACTBYTES) ||
657 				    (!mutex_tryenter(&rndpool_lock))) {
658 					rmp->rm_olimit += rmp->rm_ofuzz;
659 					rmp->rm_ofuzz >>= 1;
660 					goto punt;
661 				}
662 			} else {
663 				mutex_enter(&rndpool_lock);
664 			}
665 
666 			/* Get a new chunk of entropy */
667 			(void) rnd_get_bytes(key, HMAC_KEYSIZE,
668 			    ALWAYS_EXTRACT, B_FALSE);
669 
670 			/* Set up key */
671 			SET_ENCRYPT_KEY(key, HMAC_KEYSIZE, &rmp->rm_ks);
672 
673 			/* Get new counter value by encrypting timestamp */
674 			timestamp = gethrtime();
675 			HMAC_ENCRYPT(&rmp->rm_ks, &timestamp,
676 			    sizeof (timestamp), digest);
677 			rmp->rm_olimit = PRNG_MAXOBLOCKS/2;
678 			rmp->rm_ofuzz = PRNG_MAXOBLOCKS/4;
679 			bcopy(digest, &rmp->rm_counter, sizeof (uint64_t));
680 			oblocks = 0;
681 			rmp->rm_oblocks = nblock;
682 		}
683 punt:
684 		/* Hash counter to produce prn stream */
685 		if (bytes >= HASHSIZE) {
686 			size = HASHSIZE;
687 			HMAC_ENCRYPT(&rmp->rm_ks, &rmp->rm_counter,
688 			    sizeof (rmp->rm_counter), ptr);
689 		} else {
690 			size = min(bytes, HASHSIZE);
691 			HMAC_ENCRYPT(&rmp->rm_ks, &rmp->rm_counter,
692 			    sizeof (rmp->rm_counter), digest);
693 			bcopy(digest, ptr, size);
694 		}
695 		ptr += size;
696 		bytes -= size;
697 		rmp->rm_counter++;
698 		oblocks++;
699 		nblock--;
700 	} while (bytes > 0);
701 
702 	mutex_exit(&rmp->rm_lock);
703 	return (0);
704 }
705 
706 /*
707  * Per-CPU Random magazines.
708  */
709 static rndmag_t *rndmag;
710 static uint8_t	*rndbuf;
711 static size_t 	rndmag_total;
712 /*
713  * common/os/cpu.c says that platform support code can shrinkwrap
714  * max_ncpus.  On the off chance that we get loaded very early, we
715  * read it exactly once, to copy it here.
716  */
717 static uint32_t	random_max_ncpus = 0;
718 
719 /*
720  * Boot-time tunables, for experimentation.
721  */
722 size_t	rndmag_threshold = 2560;
723 size_t	rndbuf_len = 5120;
724 size_t	rndmag_size = 1280;
725 
726 
727 int
728 kcf_rnd_get_pseudo_bytes(uint8_t *ptr, size_t len)
729 {
730 	rndmag_t *rmp;
731 	uint8_t *cptr, *eptr;
732 
733 	/*
734 	 * Anyone who asks for zero bytes of randomness should get slapped.
735 	 */
736 	ASSERT(len > 0);
737 
738 	/*
739 	 * Fast path.
740 	 */
741 	for (;;) {
742 		rmp = &rndmag[CPU->cpu_seqid];
743 		mutex_enter(&rmp->rm_lock);
744 
745 		/*
746 		 * Big requests bypass buffer and tail-call the
747 		 * generate routine directly.
748 		 */
749 		if (len > rndmag_threshold) {
750 			BUMP_CPU_RND_STATS(rmp, rs_urndOut, len);
751 			return (rnd_generate_pseudo_bytes(rmp, ptr, len));
752 		}
753 
754 		cptr = rmp->rm_rptr;
755 		eptr = cptr + len;
756 
757 		if (eptr <= rmp->rm_eptr) {
758 			rmp->rm_rptr = eptr;
759 			bcopy(cptr, ptr, len);
760 			BUMP_CPU_RND_STATS(rmp, rs_urndOut, len);
761 			mutex_exit(&rmp->rm_lock);
762 
763 			return (0);
764 		}
765 		/*
766 		 * End fast path.
767 		 */
768 		rmp->rm_rptr = rmp->rm_buffer;
769 		/*
770 		 * Note:  We assume the generate routine always succeeds
771 		 * in this case (because it does at present..)
772 		 * It also always releases rm_lock.
773 		 */
774 		(void) rnd_generate_pseudo_bytes(rmp, rmp->rm_buffer,
775 		    rndbuf_len);
776 	}
777 }
778 
779 /*
780  * We set up (empty) magazines for all of max_ncpus, possibly wasting a
781  * little memory on big systems that don't have the full set installed.
782  * See above;  "empty" means "rptr equal to eptr"; this will trigger the
783  * refill path in rnd_get_pseudo_bytes above on the first call for each CPU.
784  *
785  * TODO: make rndmag_size tunable at run time!
786  */
787 static void
788 rnd_alloc_magazines()
789 {
790 	rndmag_t *rmp;
791 	int i;
792 
793 	rndbuf_len = roundup(rndbuf_len, HASHSIZE);
794 	if (rndmag_size < rndbuf_len)
795 		rndmag_size = rndbuf_len;
796 	rndmag_size = roundup(rndmag_size, RND_CPU_CACHE_SIZE);
797 
798 	random_max_ncpus = max_ncpus;
799 	rndmag_total = rndmag_size * random_max_ncpus;
800 
801 	rndbuf = kmem_alloc(rndmag_total, KM_SLEEP);
802 	rndmag = kmem_zalloc(sizeof (rndmag_t) * random_max_ncpus, KM_SLEEP);
803 
804 	for (i = 0; i < random_max_ncpus; i++) {
805 		uint8_t *buf;
806 
807 		rmp = &rndmag[i];
808 		mutex_init(&rmp->rm_lock, NULL, MUTEX_DRIVER, NULL);
809 
810 		buf = rndbuf + i * rndmag_size;
811 
812 		rmp->rm_buffer = buf;
813 		rmp->rm_eptr = buf + rndbuf_len;
814 		rmp->rm_rptr = buf + rndbuf_len;
815 		rmp->rm_oblocks = 1;
816 	}
817 }
818 
819 void
820 kcf_rnd_schedule_timeout(boolean_t do_mech2id)
821 {
822 	clock_t ut;	/* time in microseconds */
823 
824 	if (do_mech2id)
825 		rngmech_type = crypto_mech2id(SUN_RANDOM);
826 
827 	/*
828 	 * The new timeout value is taken from the buffer of random bytes.
829 	 * We're merely reading the first 32 bits from the buffer here, not
830 	 * consuming any random bytes.
831 	 * The timeout multiplier value is a random value between 0.5 sec and
832 	 * 1.544480 sec (0.5 sec + 0xFF000 microseconds).
833 	 * The new timeout is TIMEOUT_INTERVAL times that multiplier.
834 	 */
835 	ut = 500000 + (clock_t)((((uint32_t)rndpool[findex]) << 12) & 0xFF000);
836 	kcf_rndtimeout_id = timeout(rnd_handler, NULL,
837 	    TIMEOUT_INTERVAL * drv_usectohz(ut));
838 }
839 
840 /*
841  * &rnd_pollhead is passed in *phpp in order to indicate the calling thread
842  * will block. When enough random bytes are available, later, the timeout
843  * handler routine will issue the pollwakeup() calls.
844  */
845 void
846 kcf_rnd_chpoll(int anyyet, short *reventsp, struct pollhead **phpp)
847 {
848 	/*
849 	 * Sampling of rnbyte_cnt is an atomic
850 	 * operation. Hence we do not need any locking.
851 	 */
852 	if (rnbyte_cnt >= MINEXTRACTBYTES) {
853 		*reventsp |= (POLLIN | POLLRDNORM);
854 	} else {
855 		*reventsp = 0;
856 		if (!anyyet)
857 			*phpp = &rnd_pollhead;
858 	}
859 }
860 
861 /*ARGSUSED*/
862 static void
863 rnd_handler(void *arg)
864 {
865 	int len = 0;
866 
867 	if (!rng_prov_found && rng_ok_to_log) {
868 		cmn_err(CE_WARN, "No randomness provider enabled for "
869 		    "/dev/random. Use cryptoadm(1M) to enable a provider.");
870 		rng_ok_to_log = B_FALSE;
871 	}
872 
873 	if (num_waiters > 0)
874 		len = MAXEXTRACTBYTES;
875 	else if (rnbyte_cnt < RNDPOOLSIZE)
876 		len = MINEXTRACTBYTES;
877 
878 	if (len > 0) {
879 		(void) taskq_dispatch(system_taskq, rngprov_task,
880 		    (void *)(uintptr_t)len, TQ_NOSLEEP);
881 	}
882 
883 	mutex_enter(&rndpool_lock);
884 	/*
885 	 * Wake up threads waiting in poll() or for enough accumulated
886 	 * random bytes to read from /dev/random. In case a poll() is
887 	 * concurrent with a read(), the polling process may be woken up
888 	 * indicating that enough randomness is now available for reading,
889 	 * and another process *steals* the bits from the pool, causing the
890 	 * subsequent read() from the first process to block. It is acceptable
891 	 * since the blocking will eventually end, after the timeout
892 	 * has expired enough times to honor the read.
893 	 *
894 	 * Note - Since we hold the rndpool_lock across the pollwakeup() call
895 	 * we MUST NOT grab the rndpool_lock in kcf_rndchpoll().
896 	 */
897 	if (rnbyte_cnt >= MINEXTRACTBYTES)
898 		pollwakeup(&rnd_pollhead, POLLIN | POLLRDNORM);
899 
900 	if (num_waiters > 0)
901 		cv_broadcast(&rndpool_read_cv);
902 	mutex_exit(&rndpool_lock);
903 
904 	kcf_rnd_schedule_timeout(B_FALSE);
905 }
906 
907 /* Hashing functions */
908 
909 static void
910 hmac_key(uint8_t *key, size_t keylen, void *buf)
911 {
912 	uint32_t *ip, *op;
913 	uint32_t ipad[HMAC_BLOCK_SIZE/sizeof (uint32_t)];
914 	uint32_t opad[HMAC_BLOCK_SIZE/sizeof (uint32_t)];
915 	HASH_CTX *icontext, *ocontext;
916 	int i;
917 	int nints;
918 
919 	icontext = buf;
920 	ocontext = (SHA1_CTX *)((uint8_t *)buf + sizeof (HASH_CTX));
921 
922 	bzero((uchar_t *)ipad, HMAC_BLOCK_SIZE);
923 	bzero((uchar_t *)opad, HMAC_BLOCK_SIZE);
924 	bcopy(key, (uchar_t *)ipad, keylen);
925 	bcopy(key, (uchar_t *)opad, keylen);
926 
927 	/*
928 	 * XOR key with ipad (0x36) and opad (0x5c) as defined
929 	 * in RFC 2104.
930 	 */
931 	ip = ipad;
932 	op = opad;
933 	nints = HMAC_BLOCK_SIZE/sizeof (uint32_t);
934 
935 	for (i = 0; i < nints; i++) {
936 		ip[i] ^= 0x36363636;
937 		op[i] ^= 0x5c5c5c5c;
938 	}
939 
940 	/* Perform hash with ipad */
941 	HashInit(icontext);
942 	HashUpdate(icontext, (uchar_t *)ipad, HMAC_BLOCK_SIZE);
943 
944 	/* Perform hash with opad */
945 	HashInit(ocontext);
946 	HashUpdate(ocontext, (uchar_t *)opad, HMAC_BLOCK_SIZE);
947 }
948 
949 static void
950 hmac_encr(void *ctx, uint8_t *ptr, size_t len, uint8_t *digest)
951 {
952 	HASH_CTX *saved_contexts;
953 	HASH_CTX icontext;
954 	HASH_CTX ocontext;
955 
956 	saved_contexts = (HASH_CTX *)ctx;
957 	icontext = saved_contexts[0];
958 	ocontext = saved_contexts[1];
959 
960 	HashUpdate(&icontext, ptr, len);
961 	HashFinal(digest, &icontext);
962 
963 	/*
964 	 * Perform Hash(K XOR OPAD, DIGEST), where DIGEST is the
965 	 * Hash(K XOR IPAD, DATA).
966 	 */
967 	HashUpdate(&ocontext, digest, HASHSIZE);
968 	HashFinal(digest, &ocontext);
969 }
970 
971 
972 static void
973 rndc_addbytes(uint8_t *ptr, size_t len)
974 {
975 	ASSERT(ptr != NULL && len > 0);
976 	ASSERT(rnbyte_cnt <= RNDPOOLSIZE);
977 
978 	mutex_enter(&rndpool_lock);
979 	while ((len > 0) && (rnbyte_cnt < RNDPOOLSIZE)) {
980 		rndpool[rindex] ^= *ptr;
981 		ptr++; len--;
982 		rindex = (rindex + 1) & (RNDPOOLSIZE - 1);
983 		rnbyte_cnt++;
984 	}
985 
986 	/* Handle buffer full case */
987 	while (len > 0) {
988 		rndpool[rindex] ^= *ptr;
989 		ptr++; len--;
990 		findex = rindex = (rindex + 1) & (RNDPOOLSIZE - 1);
991 	}
992 	mutex_exit(&rndpool_lock);
993 }
994 
995 /*
996  * Caller should check len <= rnbyte_cnt under the
997  * rndpool_lock before calling.
998  */
999 static void
1000 rndc_getbytes(uint8_t *ptr, size_t len)
1001 {
1002 	ASSERT(MUTEX_HELD(&rndpool_lock));
1003 	ASSERT(len <= rnbyte_cnt && rnbyte_cnt <= RNDPOOLSIZE);
1004 
1005 	BUMP_RND_STATS(rs_rndcOut, len);
1006 
1007 	while (len > 0) {
1008 		*ptr = rndpool[findex];
1009 		ptr++; len--;
1010 		findex = (findex + 1) & (RNDPOOLSIZE - 1);
1011 		rnbyte_cnt--;
1012 	}
1013 }
1014 
1015 /* Random number exported entry points */
1016 
1017 /*
1018  * Mix the supplied bytes into the entropy pool of a kCF
1019  * RNG provider.
1020  */
1021 int
1022 random_add_pseudo_entropy(uint8_t *ptr, size_t len, uint_t entropy_est)
1023 {
1024 	if (len < 1)
1025 		return (-1);
1026 
1027 	rngprov_seed(ptr, len, entropy_est, 0);
1028 
1029 	return (0);
1030 }
1031 
1032 /*
1033  * Mix the supplied bytes into the entropy pool of a kCF
1034  * RNG provider. Mix immediately.
1035  */
1036 int
1037 random_add_entropy(uint8_t *ptr, size_t len, uint_t entropy_est)
1038 {
1039 	if (len < 1)
1040 		return (-1);
1041 
1042 	rngprov_seed(ptr, len, entropy_est, CRYPTO_SEED_NOW);
1043 
1044 	return (0);
1045 }
1046 
1047 /*
1048  * Get bytes from the /dev/urandom generator. This function
1049  * always succeeds. Returns 0.
1050  */
1051 int
1052 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
1053 {
1054 	ASSERT(!mutex_owned(&rndpool_lock));
1055 
1056 	if (len < 1)
1057 		return (0);
1058 	return (kcf_rnd_get_pseudo_bytes(ptr, len));
1059 }
1060 
1061 /*
1062  * Get bytes from the /dev/random generator. Returns 0
1063  * on success. Returns EAGAIN if there is insufficient entropy.
1064  */
1065 int
1066 random_get_bytes(uint8_t *ptr, size_t len)
1067 {
1068 	ASSERT(!mutex_owned(&rndpool_lock));
1069 
1070 	if (len < 1)
1071 		return (0);
1072 	return (kcf_rnd_get_bytes(ptr, len, B_TRUE, B_FALSE));
1073 }
1074