2 * random.c - random number generation
4 * Copyright (C) 2011, 2012 Free Software Initiative of Japan
5 * Author: NIIBE Yutaka <gniibe@fsij.org>
7 * This file is a part of NeuG, a Random Number Generator
8 * implementation (for STM32F103).
10 * NeuG is free software: you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 3 of the License, or
13 * (at your option) any later version.
15 * Gnuk is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
18 * License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include <string.h> /* for memcpy */
31 static Thread *rng_thread;
32 #define ADC_DATA_AVAILABLE ((eventmask_t)1)
34 /* Total number of channels to be sampled by a single ADC operation.*/
35 #define ADC_GRP1_NUM_CHANNELS 2
37 /* Depth of the conversion buffer, channels are sampled one time each.*/
38 #define ADC_GRP1_BUF_DEPTH 4
43 static adcsample_t samp[ADC_GRP1_NUM_CHANNELS * ADC_GRP1_BUF_DEPTH];
45 static void adccb (ADCDriver *adcp, adcsample_t *buffer, size_t n);
46 static void adccb_err (ADCDriver *adcp, adcerror_t err);
49 * ADC conversion group.
50 * Mode: Linear buffer, 4 samples of 2 channels, SW triggered.
51 * Channels: Vref (1.5 cycles sample time, violating the spec.)
52 * Sensor (1.5 cycles sample time, violating the spec.)
54 static const ADCConversionGroup adcgrpcfg = {
56 ADC_GRP1_NUM_CHANNELS,
61 ADC_SMPR1_SMP_SENSOR(ADC_SAMPLE_1P5) | ADC_SMPR1_SMP_VREF(ADC_SAMPLE_1P5),
63 ADC_SQR1_NUM_CH(ADC_GRP1_NUM_CHANNELS),
65 ADC_SQR3_SQ2_N(ADC_CHANNEL_SENSOR) | ADC_SQR3_SQ1_N(ADC_CHANNEL_VREFINT)
69 * ADC end conversion callback.
71 static void adccb (ADCDriver *adcp, adcsample_t *buffer, size_t n)
73 (void) buffer; (void) n;
76 if (adcp->state == ADC_COMPLETE)
77 chEvtSignalFlagsI (rng_thread, ADC_DATA_AVAILABLE);
81 static void adccb_err (ADCDriver *adcp, adcerror_t err)
83 (void)adcp; (void)err;
89 static sha256_context sha256_ctx_data;
90 static uint32_t sha256_output[SHA256_DIGEST_SIZE/sizeof (uint32_t)];
93 * We did an experiment of measuring entropy of ADC output with MUST.
94 * The entropy of a byte by raw sampling of LSBs has more than 6.0 bit/byte.
96 * More tests will be required, but for now we assume min-entropy >= 5.0.
98 * To be a full entropy source, the requirement is to have N samples for
99 * output of 256-bit, where:
101 * N = (256 * 2) / <min-entropy of a sample>
103 * For min-entropy = 5.0, N should be more than 103.
105 * On the other hand, in the section 6.2 "Full Entropy Source Requirements",
108 * At least twice the block size of the underlying cryptographic
109 * primitive shall be provided as input to the conditioning
110 * function to produce full entropy output.
112 * For us, cryptographic primitive is SHA-256 and its blocksize is 512-bit
113 * (64-byte), N >= 128.
115 * We chose N=131, since we love prime number, and we have "additional bits"
116 * of 32-byte for last block (feedback from previous output of SHA-256).
118 * This corresponds to min-entropy >= 3.91.
121 #define NUM_NOISE_INPUTS 131
123 static const uint8_t hash_df_initial_string[5] = {
125 0, 0, 0, 32 /* no_of_bits_returned (big endian) */
128 static void ep_init (void)
130 sha256_start (&sha256_ctx_data);
131 sha256_update (&sha256_ctx_data, hash_df_initial_string, 5);
134 static void ep_add (uint8_t entropy_bits)
136 sha256_update (&sha256_ctx_data, &entropy_bits, 1);
139 #define PROBABILITY_50_BY_TICK() ((SysTick->VAL & 0x02) != 0)
141 static const uint32_t *ep_output (void)
143 int n = (SHA256_BLOCK_SIZE - 9) -
144 ((5 + NUM_NOISE_INPUTS) % SHA256_BLOCK_SIZE);
146 if (PROBABILITY_50_BY_TICK ())
149 sha256_update (&sha256_ctx_data, (uint8_t *)sha256_output, n);
150 sha256_finish (&sha256_ctx_data, (uint8_t *)sha256_output);
152 return sha256_output;
155 #define REPETITION_COUNT 1
156 #define ADAPTIVE_PROPORTION_64 2
157 #define ADAPTIVE_PROPORTION_4096 4
159 uint32_t neug_err_state;
161 static void noise_source_error_reset (void)
166 static void noise_source_error (uint32_t err)
168 neug_err_state |= err;
170 #if defined(BOARD_STBEE_MINI)
171 palClearPad (GPIOA, GPIOA_LED2);
176 /* Cuttoff = 9, when min-entropy = 4.0, W= 2^-30 */
177 /* ceiling of (1+30/4.0) */
178 #define REPITITION_COUNT_TEST_CUTOFF 9
180 static uint8_t rct_a;
181 static uint8_t rct_b;
183 static void repetition_count_test (uint8_t sample)
188 if (rct_b >= REPITITION_COUNT_TEST_CUTOFF)
189 noise_source_error (REPETITION_COUNT);
198 /* Cuttoff = 20, when min-entropy = 4.0, W= 2^-30 */
199 /* With R, qbinom(1-2^-30,64,2^-4.0) */
200 #define ADAPTIVE_PROPORTION_64_TEST_CUTOFF 20
202 static uint8_t ap64t_a;
203 static uint8_t ap64t_b;
204 static uint8_t ap64t_s;
206 static void adaptive_proportion_64_test (uint8_t sample)
217 if (ap64t_a == sample)
220 if (ap64t_b > ADAPTIVE_PROPORTION_64_TEST_CUTOFF)
221 noise_source_error (ADAPTIVE_PROPORTION_64);
226 /* Cuttoff = 354, when min-entropy = 4.0, W= 2^-30 */
227 /* With R, qbinom(1-2^-30,4096,2^-4.0) */
228 #define ADAPTIVE_PROPORTION_4096_TEST_CUTOFF 354
230 static uint8_t ap4096t_a;
231 static uint16_t ap4096t_b;
232 static uint16_t ap4096t_s;
234 static void adaptive_proportion_4096_test (uint8_t sample)
236 if (ap4096t_s >= 4096)
245 if (ap4096t_a == sample)
248 if (ap4096t_b > ADAPTIVE_PROPORTION_4096_TEST_CUTOFF)
249 noise_source_error (ADAPTIVE_PROPORTION_4096);
254 static void noise_source_continuous_test (uint8_t noise)
256 repetition_count_test (noise);
257 adaptive_proportion_64_test (noise);
258 adaptive_proportion_4096_test (noise);
262 * Ring buffer, filled by generator, consumed by neug_get routine.
267 CondVar data_available;
268 CondVar space_available;
271 unsigned int full :1;
272 unsigned int empty :1;
275 static void rb_init (struct rng_rb *rb, uint32_t *p, uint8_t size)
280 chCondInit (&rb->data_available);
281 chCondInit (&rb->space_available);
282 rb->head = rb->tail = 0;
287 static void rb_add (struct rng_rb *rb, uint32_t v)
289 rb->buf[rb->tail++] = v;
290 if (rb->tail == rb->size)
292 if (rb->tail == rb->head)
297 static uint32_t rb_del (struct rng_rb *rb)
299 uint32_t v = rb->buf[rb->head++];
301 if (rb->head == rb->size)
303 if (rb->head == rb->tail)
310 static uint8_t neug_raw;
313 * @brief Random number generation from ADC sampling.
314 * @param RB: Pointer to ring buffer structure
315 * @return -1 when failure, 0 otherwise.
316 * @note Called holding the mutex, with RB->full == 0.
317 * Keep generating until RB->full == 1.
319 static int rng_gen (struct rng_rb *rb)
328 chEvtWaitOne (ADC_DATA_AVAILABLE);
330 /* Got an ADC sampling data */
331 b = (((samp[0] & 0x01) << 0) | ((samp[1] & 0x01) << 1)
332 | ((samp[2] & 0x01) << 2) | ((samp[3] & 0x01) << 3)
333 | ((samp[4] & 0x01) << 4) | ((samp[5] & 0x01) << 5)
334 | ((samp[6] & 0x01) << 6) | ((samp[7] & 0x01) << 7));
336 adcStartConversion (&ADCD1, &adcgrpcfg, samp, ADC_GRP1_BUF_DEPTH);
338 noise_source_continuous_test (b);
341 v |= (b << (round * 8));
355 * Put a random byte to entropy pool.
359 if (round >= NUM_NOISE_INPUTS)
362 * We have enough entropy in the pool.
363 * Thus, we pull the random bits from the pool.
366 const uint32_t *vp = ep_output ();
368 /* We get the random bits, add it to the ring buffer. */
369 for (i = 0; i < SHA256_DIGEST_SIZE / 4; i++)
382 return 0; /* success */
386 * @brief Random number generation thread.
388 static msg_t rng (void *arg)
390 struct rng_rb *rb = (struct rng_rb *)arg;
392 rng_thread = chThdSelf ();
394 adcStart (&ADCD1, NULL);
395 adcStartConversion (&ADCD1, &adcgrpcfg, samp, ADC_GRP1_BUF_DEPTH);
397 while (!chThdShouldTerminate ())
401 chCondWait (&rb->space_available);
403 chCondSignal (&rb->data_available);
410 static struct rng_rb the_ring_buffer;
411 static WORKING_AREA(wa_rng, 256);
414 * @brief Initialize NeuG.
417 neug_init (uint32_t *buf, uint8_t size)
419 struct rng_rb *rb = &the_ring_buffer;
423 rb_init (rb, buf, size);
424 chThdCreateStatic (wa_rng, sizeof (wa_rng), NORMALPRIO, rng, rb);
428 * @breif Flush random bytes.
433 struct rng_rb *rb = &the_ring_buffer;
438 chCondSignal (&rb->space_available);
444 * @brief Wakes up RNG thread to generate random numbers.
447 neug_kick_filling (void)
449 struct rng_rb *rb = &the_ring_buffer;
453 chCondSignal (&rb->space_available);
458 * @brief Get random word (32-bit) from NeuG.
459 * @detail With NEUG_KICK_FILLING, it wakes up RNG thread.
460 * With NEUG_NO_KICK, it doesn't wake up RNG thread automatically,
461 * it is needed to call neug_kick_filling later.
466 struct rng_rb *rb = &the_ring_buffer;
471 chCondWait (&rb->data_available);
474 chCondSignal (&rb->space_available);
481 neug_wait_full (void)
483 struct rng_rb *rb = &the_ring_buffer;
487 chCondWait (&rb->data_available);
496 chThdTerminate (rng_thread);
498 chThdWait (rng_thread);
504 neug_select (uint8_t raw)