1 /*
2 * Copyright (c) 2019 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28
29 #include <libkern/crypto/sha2.h>
30 #include <libkern/crypto/crypto.h>
31 #include <os/atomic_private.h>
32 #include <kern/assert.h>
33 #include <kern/percpu.h>
34 #include <kern/zalloc.h>
35 #include <kern/lock_group.h>
36 #include <kern/locks.h>
37 #include <kern/misc_protos.h>
38 #include <pexpert/pexpert.h>
39 #include <prng/entropy.h>
40 #include <machine/machine_routines.h>
41 #include <libkern/section_keywords.h>
42 #include <sys/cdefs.h>
43
44 // The number of samples we can hold in an entropy buffer.
45 #define ENTROPY_MAX_SAMPLE_COUNT (2048)
46
47 // The length of a bitmap_t array with one bit per sample of an
48 // entropy buffer.
49 #define ENTROPY_MAX_FILTER_COUNT (BITMAP_LEN(ENTROPY_MAX_SAMPLE_COUNT))
50
51 // The threshold of approximate linearity used in the entropy
52 // filter. See the entropy_filter function for more discussion.
53 #define ENTROPY_FILTER_THRESHOLD (8)
54
55 // The state for a per-CPU entropy buffer.
56 typedef struct entropy_cpu_data {
57 // A buffer to hold entropy samples.
58 entropy_sample_t samples[ENTROPY_MAX_SAMPLE_COUNT];
59
60 // A count of samples resident in the buffer. It also functions as
61 // an index to the buffer. All entries at indices less than the
62 // sample count are considered valid for consumption by the
63 // reader. The reader resets this to zero after consuming the
64 // available entropy.
65 uint32_t _Atomic sample_count;
66 } entropy_cpu_data_t;
67
68 // This structure holds the state for an instance of a FIPS continuous
69 // health test. In practice, we do not expect these tests to fail.
70 typedef struct entropy_health_test {
71 // The initial sample observed in this test instance. Tests look
72 // for some repetition of the sample, either consecutively or
73 // within a window.
74 entropy_sample_t init_observation;
75
76 // The count of times the initial observation has recurred within
77 // the span of the current test.
78 uint64_t observation_count;
79
80 // The statistics are only relevant for telemetry and parameter
81 // tuning. They do not drive any actual logic in the module.
82 entropy_health_stats_t *stats;
83 } entropy_health_test_t;
84
85 typedef enum health_test_result {
86 health_test_failure,
87 health_test_success
88 } health_test_result_t;
89
90 // Along with various counters and the buffer itself, this includes
91 // the state for two FIPS continuous health tests.
92 typedef struct entropy_data {
93 // State for a SHA512 computation. This is used to accumulate
94 // entropy samples from across all CPUs. It is finalized when
95 // entropy is provided to the consumer of this module.
96 SHA512_CTX sha512_ctx;
97
98 // A buffer to hold a bitmap with one bit per sample of an entropy
99 // buffer. We are able to reuse this instance across all the
100 // per-CPU entropy buffers to save space.
101 bitmap_t filter[ENTROPY_MAX_FILTER_COUNT];
102
103 // A total count of entropy samples that have passed through this
104 // structure. It is incremented as new samples are accumulated
105 // from the various per-CPU structures. The "current" count of
106 // samples is the difference between this field and the "read"
107 // sample count below (which see).
108 uint64_t total_sample_count;
109
110 // Initially zero, this flag is reset to the current sample count
111 // if and when we fail a health test. We consider the startup
112 // health tests to be complete when the difference between the
113 // total sample count and this field is at least 1024. In other
114 // words, we must accumulate 1024 good samples to demonstrate
115 // viability. We refuse to provide any entropy before that
116 // threshold is reached.
117 uint64_t startup_sample_count;
118
119 // The count of samples from the last time we provided entropy to
120 // the kernel RNG. We use this to compute how many new samples we
121 // have to contribute. This value is also reset to the current
122 // sample count in case of health test failure.
123 uint64_t read_sample_count;
124
125 // The lock group for this structure; see below.
126 lck_grp_t lock_group;
127
128 // This structure accumulates entropy samples from across all CPUs
129 // for a single point of consumption protected by a mutex.
130 lck_mtx_t mutex;
131
132 // State for the Repetition Count Test.
133 entropy_health_test_t repetition_count_test;
134
135 // State for the Adaptive Proportion Test.
136 entropy_health_test_t adaptive_proportion_test;
137 } entropy_data_t;
138
139 static entropy_cpu_data_t PERCPU_DATA(entropy_cpu_data);
140
141 int entropy_health_startup_done;
142 entropy_health_stats_t entropy_health_rct_stats;
143 entropy_health_stats_t entropy_health_apt_stats;
144 uint64_t entropy_filter_accepted_sample_count;
145 uint64_t entropy_filter_rejected_sample_count;
146 uint64_t entropy_filter_total_sample_count;
147
148 static entropy_data_t entropy_data = {
149 .repetition_count_test = {
150 .init_observation = -1,
151 .stats = &entropy_health_rct_stats,
152 },
153 .adaptive_proportion_test = {
154 .init_observation = -1,
155 .stats = &entropy_health_apt_stats,
156 },
157 };
158
159 #if ENTROPY_ANALYSIS_SUPPORTED
160
161 __security_const_late int entropy_analysis_enabled;
162 __security_const_late entropy_sample_t *entropy_analysis_buffer;
163 __security_const_late uint32_t entropy_analysis_buffer_size;
164 __security_const_late uint32_t entropy_analysis_filter_size;
165 __security_const_late uint32_t entropy_analysis_max_sample_count;
166 uint32_t entropy_analysis_sample_count;
167
168 __startup_func
169 static void
entropy_analysis_init(uint32_t sample_count)170 entropy_analysis_init(uint32_t sample_count)
171 {
172 entropy_analysis_enabled = 1;
173 entropy_analysis_max_sample_count = sample_count;
174 entropy_analysis_buffer_size = sample_count * sizeof(entropy_sample_t);
175 entropy_analysis_buffer = zalloc_permanent(entropy_analysis_buffer_size, ZALIGN(entropy_sample_t));
176 entropy_analysis_filter_size = (uint32_t) BITMAP_SIZE(entropy_analysis_max_sample_count);
177 }
178
179 static void
entropy_analysis_store(entropy_sample_t sample)180 entropy_analysis_store(entropy_sample_t sample)
181 {
182 uint32_t sample_count;
183 uint32_t next_sample_count;
184
185 os_atomic_rmw_loop(&entropy_analysis_sample_count, sample_count, next_sample_count, relaxed, {
186 if (sample_count >= entropy_analysis_max_sample_count) {
187 os_atomic_rmw_loop_give_up(return );
188 }
189
190 next_sample_count = sample_count + 1;
191 });
192
193 entropy_analysis_buffer[sample_count] = sample;
194 }
195
196 #endif // ENTROPY_ANALYSIS_SUPPORTED
197
198 __startup_func
199 void
entropy_init(size_t seed_size,uint8_t * seed)200 entropy_init(size_t seed_size, uint8_t *seed)
201 {
202 SHA512_Init(&entropy_data.sha512_ctx);
203 SHA512_Update(&entropy_data.sha512_ctx, seed, seed_size);
204
205 lck_grp_init(&entropy_data.lock_group, "entropy-data", LCK_GRP_ATTR_NULL);
206 lck_mtx_init(&entropy_data.mutex, &entropy_data.lock_group, LCK_ATTR_NULL);
207
208 #if ENTROPY_ANALYSIS_SUPPORTED
209 // The below path is used only for testing. This boot arg is used
210 // to collect raw entropy samples for offline analysis.
211 uint32_t sample_count = 0;
212 if (__improbable(PE_parse_boot_argn(ENTROPY_ANALYSIS_BOOTARG, &sample_count, sizeof(sample_count)))) {
213 entropy_analysis_init(sample_count);
214 }
215 #endif // ENTROPY_ANALYSIS_SUPPORTED
216 }
217
218 void
entropy_collect(void)219 entropy_collect(void)
220 {
221 // This function is called from within the interrupt handler, so
222 // we do not need to disable interrupts.
223
224 entropy_cpu_data_t *e = PERCPU_GET(entropy_cpu_data);
225
226 uint32_t sample_count = os_atomic_load(&e->sample_count, relaxed);
227
228 assert3u(sample_count, <=, ENTROPY_MAX_SAMPLE_COUNT);
229
230 // If the buffer is full, we return early without collecting
231 // entropy.
232 if (sample_count == ENTROPY_MAX_SAMPLE_COUNT) {
233 return;
234 }
235
236 entropy_sample_t sample = (entropy_sample_t)ml_get_timebase_entropy();
237 e->samples[sample_count] = sample;
238
239 // If the consumer has reset the sample count on us, the only
240 // consequence is a dropped sample. We effectively abort the
241 // entropy collection in this case.
242 (void)os_atomic_cmpxchg(&e->sample_count, sample_count, sample_count + 1, release);
243
244 #if ENTROPY_ANALYSIS_SUPPORTED
245 // This code path is only used for testing. Its use is governed by
246 // a boot arg; see its initialization above.
247 if (__improbable(entropy_analysis_buffer)) {
248 entropy_analysis_store(sample);
249 }
250 #endif // ENTROPY_ANALYSIS_SUPPORTED
251 }
252
253 // This filter looks at the 1st differential (differences of subsequent
254 // timestamp values) and the 2nd differential (differences of subsequent
255 // 1st differentials). This filter will detect sequences of timestamps
256 // that are linear (that is, the 2nd differential is close to zero).
257 // Timestamps with a 2nd differential above the threshold ENTROPY_FILTER_THRESHOLD
258 // will be marked in the filter bitmap. 2nd differentials below the threshold
259 // will not be counted nor included in the filter bitmap.
260 //
261 // For example imagine the following sequence of 8-bit timestamps:
262 //
263 // [25, 100, 175, 250, 69, 144, 219, 38, 113, 188]
264 //
265 // The 1st differential between timestamps is as follows:
266 //
267 // [75, 75, 75, 75, 75, 75, 75, 75, 75]
268 //
269 // The 2nd differential is as follows:
270 //
271 // [0, 0, 0, 0, 0, 0, 0, 0]
272 //
273 // The first two samples of any set of samples are always included as
274 // there is no 2nd differential to compare against. Thus all but
275 // the first two samples in this example will be removed.
276 uint32_t
entropy_filter(uint32_t sample_count,entropy_sample_t * samples,__assert_only uint32_t filter_count,bitmap_t * filter)277 entropy_filter(uint32_t sample_count, entropy_sample_t *samples, __assert_only uint32_t filter_count, bitmap_t *filter)
278 {
279 assert3u(filter_count, >=, BITMAP_LEN(sample_count));
280
281 bitmap_zero(filter, sample_count);
282
283 // We always keep the first one (or two) sample(s) if we have at least one (or more) samples
284 if (sample_count == 0) {
285 return 0;
286 } else if (sample_count == 1) {
287 bitmap_set(filter, 0);
288 return 1;
289 } else if (sample_count == 2) {
290 bitmap_set(filter, 0);
291 bitmap_set(filter, 1);
292 return 2;
293 } else {
294 bitmap_set(filter, 0);
295 bitmap_set(filter, 1);
296 }
297
298 uint32_t filtered_sample_count = 2;
299
300 // We don't care about underflows when computing any differential
301 entropy_sample_t prev_1st_differential = samples[1] - samples[0];
302
303 for (uint i = 2; i < sample_count; i++) {
304 entropy_sample_t curr_1st_differential = samples[i] - samples[i - 1];
305
306 entropy_sample_t curr_2nd_differential = curr_1st_differential - prev_1st_differential;
307
308 if (curr_2nd_differential > ENTROPY_FILTER_THRESHOLD && curr_2nd_differential < ((entropy_sample_t) -ENTROPY_FILTER_THRESHOLD)) {
309 bitmap_set(filter, i);
310 filtered_sample_count += 1;
311 }
312
313 prev_1st_differential = curr_1st_differential;
314 }
315
316 return filtered_sample_count;
317 }
318
319 // For information on the following tests, see NIST SP 800-90B 4
320 // Health Tests. These tests are intended to detect catastrophic
321 // degradations in entropy. As noted in that document:
322 //
323 // > Health tests are expected to raise an alarm in three cases:
324 // > 1. When there is a significant decrease in the entropy of the
325 // > outputs,
326 // > 2. When noise source failures occur, or
327 // > 3. When hardware fails, and implementations do not work
328 // > correctly.
329 //
330 // Each entropy accumulator declines to release entropy until the
331 // startup tests required by NIST are complete. In the event that a
332 // health test does fail, all entropy accumulators are reset and
333 // decline to release further entropy until their startup tests can be
334 // repeated.
335
336 static health_test_result_t
add_observation(entropy_health_test_t * t,uint64_t bound)337 add_observation(entropy_health_test_t *t, uint64_t bound)
338 {
339 t->observation_count += 1;
340 t->stats->max_observation_count = MAX(t->stats->max_observation_count, (uint32_t)t->observation_count);
341 if (__improbable(t->observation_count >= bound)) {
342 t->stats->failure_count += 1;
343 return health_test_failure;
344 }
345
346 return health_test_success;
347 }
348
349 static void
reset_test(entropy_health_test_t * t,entropy_sample_t observation)350 reset_test(entropy_health_test_t *t, entropy_sample_t observation)
351 {
352 t->stats->reset_count += 1;
353 t->init_observation = observation;
354 t->observation_count = 1;
355 t->stats->max_observation_count = MAX(t->stats->max_observation_count, (uint32_t)t->observation_count);
356 }
357
358 // 4.4.1 Repetition Count Test
359 //
360 // Like the name implies, this test counts consecutive occurrences of
361 // the same value.
362 //
363 // We compute the bound C as:
364 //
365 // A = 2^-40
366 // H = 1
367 // C = 1 + ceil(-log(A, 2) / H) = 41
368 //
369 // With A the acceptable chance of false positive and H a conservative
370 // estimate for the min-entropy (in bits) of each sample.
371 //
372 // For more information, see tools/entropy_health_test_bounds.py.
373
374 #define REPETITION_COUNT_BOUND (41)
375
376 static health_test_result_t
repetition_count_test(entropy_sample_t observation)377 repetition_count_test(entropy_sample_t observation)
378 {
379 entropy_health_test_t *t = &entropy_data.repetition_count_test;
380
381 if (t->init_observation == observation) {
382 return add_observation(t, REPETITION_COUNT_BOUND);
383 } else {
384 reset_test(t, observation);
385 }
386
387 return health_test_success;
388 }
389
390 // 4.4.2 Adaptive Proportion Test
391 //
392 // This test counts occurrences of a value within a window of samples.
393 //
394 // We use a non-binary alphabet, giving us a window size of 512. (In
395 // particular, we consider the least-significant byte of each time
396 // sample.)
397 //
398 // Assuming one bit of entropy, we can compute the binomial cumulative
399 // distribution function over 512 trials and choose a bound such that
400 // the false positive rate is less than our target.
401 //
402 // For false positive rate and min-entropy estimate as above:
403 //
404 // A = 2^-40
405 // H = 1
406 //
407 // We have our bound:
408 //
409 // C = 336
410 //
411 // For more information, see tools/entropy_health_test_bounds.py.
412
413 #define ADAPTIVE_PROPORTION_BOUND (336)
414 #define ADAPTIVE_PROPORTION_WINDOW (512)
415
416 // This mask definition requires the window be a power of two.
417 static_assert(__builtin_popcount(ADAPTIVE_PROPORTION_WINDOW) == 1);
418 #define ADAPTIVE_PROPORTION_INDEX_MASK (ADAPTIVE_PROPORTION_WINDOW - 1)
419
420 static health_test_result_t
adaptive_proportion_test(entropy_sample_t observation,uint32_t offset)421 adaptive_proportion_test(entropy_sample_t observation, uint32_t offset)
422 {
423 entropy_health_test_t *t = &entropy_data.adaptive_proportion_test;
424
425 // We work in windows of size ADAPTIVE_PROPORTION_WINDOW, so we
426 // can compute our index by taking the entropy buffer's overall
427 // sample count plus the offset of this observation modulo the
428 // window size.
429 uint32_t index = (entropy_data.total_sample_count + offset) & ADAPTIVE_PROPORTION_INDEX_MASK;
430
431 if (index == 0) {
432 reset_test(t, observation);
433 } else if (t->init_observation == observation) {
434 return add_observation(t, ADAPTIVE_PROPORTION_BOUND);
435 }
436
437 return health_test_success;
438 }
439
440 static health_test_result_t
entropy_health_test(uint32_t sample_count,entropy_sample_t * samples,__assert_only uint32_t filter_count,bitmap_t * filter)441 entropy_health_test(uint32_t sample_count, entropy_sample_t *samples, __assert_only uint32_t filter_count, bitmap_t *filter)
442 {
443 health_test_result_t result = health_test_success;
444
445 assert3u(filter_count, >=, BITMAP_LEN(sample_count));
446
447 for (uint32_t i = 0; i < sample_count; i += 1) {
448 // We use the filter to determine if a given sample "counts"
449 // or not. We skip the health tests on those samples that
450 // failed the filter, since they are not expected to provide
451 // any entropy.
452 if (!bitmap_test(filter, i)) {
453 continue;
454 }
455
456 // We only consider the low bits of each sample, since that is
457 // where we expect the entropy to be concentrated.
458 entropy_sample_t observation = samples[i] & 0xff;
459
460 if (__improbable(repetition_count_test(observation) == health_test_failure)) {
461 result = health_test_failure;
462 }
463
464 if (__improbable(adaptive_proportion_test(observation, i) == health_test_failure)) {
465 result = health_test_failure;
466 }
467 }
468
469 return result;
470 }
471
472 int32_t
entropy_provide(size_t * entropy_size,void * entropy,__unused void * arg)473 entropy_provide(size_t *entropy_size, void *entropy, __unused void *arg)
474 {
475 #if (DEVELOPMENT || DEBUG)
476 if (*entropy_size < SHA512_DIGEST_LENGTH) {
477 panic("[entropy_provide] recipient entropy buffer is too small");
478 }
479 #endif
480
481 int32_t sample_count = 0;
482 *entropy_size = 0;
483
484 // There is only one consumer (the kernel PRNG), but they could
485 // try to consume entropy from different threads. We simply fail
486 // if a consumption is already in progress.
487 if (!lck_mtx_try_lock(&entropy_data.mutex)) {
488 return sample_count;
489 }
490
491 health_test_result_t health_test_result = health_test_success;
492
493 // We accumulate entropy from all CPUs.
494 percpu_foreach(e, entropy_cpu_data) {
495 // On each CPU, the sample count functions as an index into
496 // the entropy buffer. All samples before that index are valid
497 // for consumption.
498 uint32_t cpu_sample_count = os_atomic_load(&e->sample_count, acquire);
499
500 assert3u(cpu_sample_count, <=, ENTROPY_MAX_SAMPLE_COUNT);
501
502 // We'll calculate how many samples that we would filter out
503 // and only add that many to the total_sample_count. The bitmap
504 // is not used during this operation.
505 uint32_t filtered_sample_count = entropy_filter(cpu_sample_count, e->samples, ENTROPY_MAX_FILTER_COUNT, entropy_data.filter);
506 assert3u(filtered_sample_count, <=, cpu_sample_count);
507
508 entropy_filter_total_sample_count += cpu_sample_count;
509 entropy_filter_accepted_sample_count += filtered_sample_count;
510 entropy_filter_rejected_sample_count += (cpu_sample_count - filtered_sample_count);
511
512 // The health test depends in part on the current state of
513 // the entropy data, so we test the new sample before
514 // accumulating it.
515 health_test_result_t cpu_health_test_result = entropy_health_test(cpu_sample_count, e->samples, ENTROPY_MAX_FILTER_COUNT, entropy_data.filter);
516 if (__improbable(cpu_health_test_result == health_test_failure)) {
517 health_test_result = health_test_failure;
518 }
519
520 // We accumulate the samples regardless of whether the test
521 // failed or a particular sample was filtered. It cannot hurt.
522 entropy_data.total_sample_count += filtered_sample_count;
523 SHA512_Update(&entropy_data.sha512_ctx, e->samples, cpu_sample_count * sizeof(e->samples[0]));
524
525 // "Drain" the per-CPU buffer by resetting its sample count.
526 os_atomic_store(&e->sample_count, 0, relaxed);
527 }
528
529 // We expect this never to happen.
530 //
531 // But if it does happen, we need to return negative to signal the
532 // consumer (i.e. the kernel PRNG) that there has been a failure.
533 if (__improbable(health_test_result == health_test_failure)) {
534 entropy_health_startup_done = 0;
535 entropy_data.startup_sample_count = entropy_data.total_sample_count;
536 entropy_data.read_sample_count = entropy_data.total_sample_count;
537 sample_count = -1;
538 goto out;
539 }
540
541 // FIPS requires we pass our startup health tests before providing
542 // any entropy. This condition is only true during startup and in
543 // case of reset due to test failure.
544 if (__improbable((entropy_data.total_sample_count - entropy_data.startup_sample_count) < 1024)) {
545 goto out;
546 }
547
548 entropy_health_startup_done = 1;
549
550 // The count of new samples from the consumer's perspective.
551 int32_t n = (int32_t)(entropy_data.total_sample_count - entropy_data.read_sample_count);
552
553 // Assuming one bit of entropy per sample, we buffer at least 512
554 // samples before delivering a high-entropy payload. In theory,
555 // each payload will be a 512-bit seed with full entropy.
556 //
557 // We buffer an additional 64 bits of entropy to satisfy
558 // over-sampling requirements in FIPS 140-3 IG.
559 if (n < (512 + 64)) {
560 goto out;
561 }
562
563 // Extract the entropy seed from the digest context and adjust
564 // counters accordingly.
565 SHA512_Final(entropy, &entropy_data.sha512_ctx);
566 entropy_data.read_sample_count = entropy_data.total_sample_count;
567 sample_count = n;
568 *entropy_size = SHA512_DIGEST_LENGTH;
569
570 // Reinitialize the digest context for future entropy
571 // conditioning.
572 SHA512_Init(&entropy_data.sha512_ctx);
573
574 // To harden the entropy conditioner against an attacker with
575 // partial or temporary control of interrupts, we roll the
576 // extracted seed back into the new digest context. Assuming
577 // we are able to reach a threshold of entropy, we can prevent
578 // the attacker from predicting future output seeds.
579 //
580 // Along with the seed, we mix in a fixed label to personalize
581 // this context.
582 const char label[SHA512_BLOCK_LENGTH - SHA512_DIGEST_LENGTH] = "xnu entropy extract seed";
583
584 // We need the combined size of our inputs to equal the
585 // internal SHA512 block size. This will force an additional
586 // compression to provide backtracking resistance.
587 assert3u(sizeof(label) + *entropy_size, ==, SHA512_BLOCK_LENGTH);
588 SHA512_Update(&entropy_data.sha512_ctx, label, sizeof(label));
589 SHA512_Update(&entropy_data.sha512_ctx, entropy, *entropy_size);
590
591 out:
592 lck_mtx_unlock(&entropy_data.mutex);
593
594 return sample_count;
595 }
596