1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (C) 2018, Linaro Limited
4  */
5 
6 /*
7  * Developerbox doesn't provide a hardware based true random number
8  * generator. So this pseudo TA provides a good source of entropy using
9  * noise from 7 thermal sensors. Its suitable for entropy required
10  * during boot, seeding kernel entropy pool, cryptographic use etc.
11  *
12  * Assumption
13  * ==========
14  *
15  * We have assumed the entropy of the sensor is better than 8 bits per
16  * 14 sensor readings. This entropy estimate is based on our simple
17  * minimal entropy estimates done on 2.1G bytes of raw samples collected
18  * from thermal sensors.
19  *
20  * We believe our estimate to be conservative and have designed to
21  * health tests to trigger if a sensor does not achieve at least
22  * 8 bits in 16 sensor reading (we use 16 rather than 14 to prevent
23  * spurious failures on edge cases).
24  *
25  * Theory of operation
26  * ===================
27  *
28  * This routine uses secure timer interrupt to sample raw thermal sensor
29  * readings. As thermal sensor refresh rate is every 2ms, so interrupt
30  * fires every 2ms. It implements continuous health test counting rising
31  * and falling edges to report if sensors fail to provide entropy.
32  *
33  * It uses vetted conditioner as SHA512/256 (approved hash algorithm)
34  * to condense entropy. As per NIST.SP.800-90B spec, to get full entropy
35  * from vetted conditioner, we need to supply double of input entropy.
36  * According to assumption above and requirement for vetted conditioner,
37  * we need to supply 28 raw sensor readings to get 1 byte of full
38  * entropy as output. So for 32 bytes of conditioner output, we need to
39  * supply 896 bytes of raw sensor readings.
40  *
41  * Interfaces -> Input
42  * -------------------
43  *
44  * void rng_collect_entropy(void);
45  *
46  * Called as part of secure timer interrupt handler to sample raw
47  * thermal sensor readings and add entropy to the pool.
48  *
49  * Interfaces -> Output
50  * --------------------
51  *
52  * TEE_Result rng_get_entropy(uint32_t types,
53  *                            TEE_Param params[TEE_NUM_PARAMS]);
54  *
55  * Invoke command to expose an entropy interface to normal world.
56  *
57  * Testing
58  * =======
59  *
60  * Passes FIPS 140-2 rngtest.
61  *
62  * Limitations
63  * ===========
64  *
65  * Output rate is limited to approx. 125 bytes per second.
66  *
67  * Our entropy estimation was not reached using any approved or
68  * published estimation framework such as NIST.SP.800-90B and was tested
69  * on a very small set of physical samples. Instead we have adopted what
70  * we believe to be a conservative estimate and partnered it with a
71  * fairly agressive health check.
72  *
73  * Generating the SHA512/256 hash takes 24uS and will be run by an
74  * interrupt handler that pre-empts the normal world.
75  */
76 
77 #include <crypto/crypto.h>
78 #include <kernel/delay.h>
79 #include <kernel/pseudo_ta.h>
80 #include <kernel/spinlock.h>
81 #include <kernel/timer.h>
82 #include <mm/core_memprot.h>
83 #include <io.h>
84 #include <string.h>
85 #include <rng_pta.h>
86 #include <rng_pta_client.h>
87 
88 #define PTA_NAME "rng.pta"
89 
90 #define THERMAL_SENSOR_BASE0		0x54190800
91 #define THERMAL_SENSOR_OFFSET		0x80
92 #define NUM_SENSORS			7
93 #define NUM_SLOTS			((NUM_SENSORS * 2) - 1)
94 
95 #define TEMP_DATA_REG_OFFSET		0x34
96 
97 #define ENTROPY_POOL_SIZE		4096
98 
99 #define SENSOR_DATA_SIZE		128
100 #define CONDITIONER_PAYLOAD		(SENSOR_DATA_SIZE * NUM_SENSORS)
101 
102 /*
103  * The health test monitors each sensor's least significant bit and counts
104  * the number of rising and falling edges. It verifies that both counts
105  * lie within interval of between 12.5% and 37.5% of the samples.
106  * For true random data with 8 bits of entropy per byte, both counts would
107  * be close to 25%.
108  */
109 #define MAX_BIT_FLIP_EDGE_COUNT		((3 * SENSOR_DATA_SIZE) / 8)
110 #define MIN_BIT_FLIP_EDGE_COUNT		(SENSOR_DATA_SIZE / 8)
111 
112 static uint8_t entropy_pool[ENTROPY_POOL_SIZE] = {0};
113 static uint32_t entropy_size;
114 
115 static uint8_t sensors_data[NUM_SLOTS][SENSOR_DATA_SIZE] = {0};
116 static uint8_t sensors_data_slot_idx;
117 static uint8_t sensors_data_idx;
118 
119 static uint32_t health_test_fail_cnt;
120 static uint32_t health_test_cnt;
121 
122 static unsigned int entropy_lock = SPINLOCK_UNLOCK;
123 
pool_add_entropy(uint8_t * entropy,uint32_t size)124 static void pool_add_entropy(uint8_t *entropy, uint32_t size)
125 {
126 	uint32_t copy_size;
127 
128 	if (entropy_size >= ENTROPY_POOL_SIZE)
129 		return;
130 
131 	if ((ENTROPY_POOL_SIZE - entropy_size) >= size)
132 		copy_size = size;
133 	else
134 		copy_size = ENTROPY_POOL_SIZE - entropy_size;
135 
136 	memcpy((entropy_pool + entropy_size), entropy, copy_size);
137 
138 	entropy_size += copy_size;
139 }
140 
pool_get_entropy(uint8_t * buf,uint32_t size)141 static void pool_get_entropy(uint8_t *buf, uint32_t size)
142 {
143 	uint32_t off;
144 
145 	if (size > entropy_size)
146 		return;
147 
148 	off = entropy_size - size;
149 
150 	memcpy(buf, &entropy_pool[off], size);
151 	entropy_size -= size;
152 }
153 
health_test(uint8_t sensor_id)154 static bool health_test(uint8_t sensor_id)
155 {
156 	uint32_t falling_edge_count = 0, rising_edge_count = 0;
157 	uint32_t lo_edge_count, hi_edge_count;
158 	uint32_t i;
159 
160 	for (i = 0; i < (SENSOR_DATA_SIZE - 1); i++) {
161 		if ((sensors_data[sensor_id][i] ^
162 		     sensors_data[sensor_id][i + 1]) & 0x1) {
163 			falling_edge_count += (sensors_data[sensor_id][i] &
164 					       0x1);
165 			rising_edge_count += (sensors_data[sensor_id][i + 1] &
166 					      0x1);
167 		}
168 	}
169 
170 	lo_edge_count = rising_edge_count < falling_edge_count ?
171 			rising_edge_count : falling_edge_count;
172 	hi_edge_count = rising_edge_count < falling_edge_count ?
173 			falling_edge_count : rising_edge_count;
174 
175 	return (lo_edge_count >= MIN_BIT_FLIP_EDGE_COUNT) &&
176 	       (hi_edge_count <= MAX_BIT_FLIP_EDGE_COUNT);
177 }
178 
pool_check_add_entropy(void)179 static uint8_t pool_check_add_entropy(void)
180 {
181 	uint32_t i;
182 	uint8_t entropy_sha512_256[TEE_SHA256_HASH_SIZE];
183 	uint8_t pool_status = 0;
184 	TEE_Result res;
185 
186 	for (i = 0; i < NUM_SENSORS; i++) {
187 		/* Check if particular sensor data passes health test */
188 		if (health_test(sensors_data_slot_idx) == true) {
189 			sensors_data_slot_idx++;
190 		} else {
191 			health_test_fail_cnt++;
192 			memmove(sensors_data[sensors_data_slot_idx],
193 				sensors_data[sensors_data_slot_idx + 1],
194 				(SENSOR_DATA_SIZE * (NUM_SENSORS - i - 1)));
195 		}
196 	}
197 
198 	health_test_cnt += NUM_SENSORS;
199 
200 	/* Check if sensors_data have enough pass data for conditioning */
201 	if (sensors_data_slot_idx >= NUM_SENSORS) {
202 		/*
203 		 * Use vetted conditioner SHA512/256 as per
204 		 * NIST.SP.800-90B to condition raw data from entropy
205 		 * source.
206 		 */
207 		sensors_data_slot_idx -= NUM_SENSORS;
208 		res = hash_sha512_256_compute(entropy_sha512_256,
209 					sensors_data[sensors_data_slot_idx],
210 					CONDITIONER_PAYLOAD);
211 		if (res == TEE_SUCCESS)
212 			pool_add_entropy(entropy_sha512_256,
213 					 TEE_SHA256_HASH_SIZE);
214 	}
215 
216 	if (entropy_size >= ENTROPY_POOL_SIZE)
217 		pool_status = 1;
218 
219 	return pool_status;
220 }
221 
rng_collect_entropy(void)222 void rng_collect_entropy(void)
223 {
224 	uint8_t i, pool_full = 0;
225 	void *vaddr;
226 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_ALL);
227 
228 	cpu_spin_lock(&entropy_lock);
229 
230 	for (i = 0; i < NUM_SENSORS; i++) {
231 		vaddr = phys_to_virt_io(THERMAL_SENSOR_BASE0 +
232 					(THERMAL_SENSOR_OFFSET * i) +
233 					TEMP_DATA_REG_OFFSET,
234 					sizeof(uint32_t));
235 		sensors_data[sensors_data_slot_idx + i][sensors_data_idx] =
236 					(uint8_t)io_read32((vaddr_t)vaddr);
237 	}
238 
239 	sensors_data_idx++;
240 
241 	if (sensors_data_idx >= SENSOR_DATA_SIZE) {
242 		pool_full = pool_check_add_entropy();
243 		sensors_data_idx = 0;
244 	}
245 
246 	if (pool_full)
247 		generic_timer_stop();
248 
249 	cpu_spin_unlock(&entropy_lock);
250 	thread_set_exceptions(exceptions);
251 }
252 
rng_get_entropy(uint32_t types,TEE_Param params[TEE_NUM_PARAMS])253 static TEE_Result rng_get_entropy(uint32_t types,
254 				  TEE_Param params[TEE_NUM_PARAMS])
255 {
256 	uint8_t *e = NULL;
257 	uint32_t pool_size = 0, rq_size = 0;
258 	uint32_t exceptions;
259 	TEE_Result res = TEE_SUCCESS;
260 
261 	if (types != TEE_PARAM_TYPES(TEE_PARAM_TYPE_MEMREF_INOUT,
262 				     TEE_PARAM_TYPE_NONE,
263 				     TEE_PARAM_TYPE_NONE,
264 				     TEE_PARAM_TYPE_NONE)) {
265 		EMSG("bad parameters types: 0x%" PRIx32, types);
266 		return TEE_ERROR_BAD_PARAMETERS;
267 	}
268 
269 	rq_size = params[0].memref.size;
270 
271 	if ((rq_size == 0) || (rq_size > ENTROPY_POOL_SIZE))
272 		return TEE_ERROR_NOT_SUPPORTED;
273 
274 	e = (uint8_t *)params[0].memref.buffer;
275 	if (!e)
276 		return TEE_ERROR_BAD_PARAMETERS;
277 
278 	exceptions = thread_mask_exceptions(THREAD_EXCP_ALL);
279 	cpu_spin_lock(&entropy_lock);
280 
281 	/*
282 	 * Report health test failure to normal world in case fail count
283 	 * exceeds 1% of pass count.
284 	 */
285 	if (health_test_fail_cnt > ((health_test_cnt + 100) / 100)) {
286 		res = TEE_ERROR_HEALTH_TEST_FAIL;
287 		params[0].memref.size = 0;
288 		health_test_cnt = 0;
289 		health_test_fail_cnt = 0;
290 		goto exit;
291 	}
292 
293 	pool_size = entropy_size;
294 
295 	if (pool_size < rq_size) {
296 		params[0].memref.size = pool_size;
297 		pool_get_entropy(e, pool_size);
298 	} else {
299 		params[0].memref.size = rq_size;
300 		pool_get_entropy(e, rq_size);
301 	}
302 
303 exit:
304 	/* Enable timer FIQ to fetch entropy */
305 	generic_timer_start(TIMER_PERIOD_MS);
306 
307 	cpu_spin_unlock(&entropy_lock);
308 	thread_set_exceptions(exceptions);
309 
310 	return res;
311 }
312 
rng_get_info(uint32_t types,TEE_Param params[TEE_NUM_PARAMS])313 static TEE_Result rng_get_info(uint32_t types,
314 			       TEE_Param params[TEE_NUM_PARAMS])
315 {
316 	if (types != TEE_PARAM_TYPES(TEE_PARAM_TYPE_VALUE_OUTPUT,
317 				     TEE_PARAM_TYPE_NONE,
318 				     TEE_PARAM_TYPE_NONE,
319 				     TEE_PARAM_TYPE_NONE)) {
320 		EMSG("bad parameters types: 0x%" PRIx32, types);
321 		return TEE_ERROR_BAD_PARAMETERS;
322 	}
323 
324 	/* Output RNG rate (per second) */
325 	params[0].value.a = 125;
326 
327 	/*
328 	 * Quality/entropy per 1024 bit of output data. As we have used
329 	 * a vetted conditioner as per NIST.SP.800-90B to provide full
330 	 * entropy given our assumption of entropy estimate for raw sensor
331 	 * data.
332 	 */
333 	params[0].value.b = 1024;
334 
335 	return TEE_SUCCESS;
336 }
337 
invoke_command(void * pSessionContext __unused,uint32_t nCommandID,uint32_t nParamTypes,TEE_Param pParams[TEE_NUM_PARAMS])338 static TEE_Result invoke_command(void *pSessionContext __unused,
339 				 uint32_t nCommandID, uint32_t nParamTypes,
340 				 TEE_Param pParams[TEE_NUM_PARAMS])
341 {
342 	FMSG("command entry point for pseudo-TA \"%s\"", PTA_NAME);
343 
344 	switch (nCommandID) {
345 	case PTA_CMD_GET_ENTROPY:
346 		return rng_get_entropy(nParamTypes, pParams);
347 	case PTA_CMD_GET_RNG_INFO:
348 		return rng_get_info(nParamTypes, pParams);
349 	default:
350 		break;
351 	}
352 
353 	return TEE_ERROR_NOT_IMPLEMENTED;
354 }
355 
356 pseudo_ta_register(.uuid = PTA_RNG_UUID, .name = PTA_NAME,
357 		   .flags = PTA_DEFAULT_FLAGS | TA_FLAG_DEVICE_ENUM,
358 		   .invoke_command_entry_point = invoke_command);
359