xref: /rk3399_ARM-atf/drivers/auth/mbedtls/mbedtls_psa_crypto.c (revision 484b58696d627c68869d86e2c401a9088392659e)
1 /*
2  * Copyright (c) 2023, Arm Limited. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include <assert.h>
8 #include <stddef.h>
9 #include <string.h>
10 
11 /* mbed TLS headers */
12 #include <mbedtls/gcm.h>
13 #include <mbedtls/md.h>
14 #include <mbedtls/memory_buffer_alloc.h>
15 #include <mbedtls/oid.h>
16 #include <mbedtls/platform.h>
17 #include <mbedtls/version.h>
18 #include <mbedtls/x509.h>
19 #include <psa/crypto.h>
20 #include <psa/crypto_platform.h>
21 #include <psa/crypto_types.h>
22 #include <psa/crypto_values.h>
23 
24 #include <common/debug.h>
25 #include <drivers/auth/crypto_mod.h>
26 #include <drivers/auth/mbedtls/mbedtls_common.h>
27 #include <plat/common/platform.h>
28 
29 #define LIB_NAME		"mbed TLS PSA"
30 
31 #if CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY || \
32 CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC
33 /*
34  * CRYPTO_MD_MAX_SIZE value is as per current stronger algorithm available
35  * so make sure that mbed TLS MD maximum size must be lesser than this.
36  */
37 CASSERT(CRYPTO_MD_MAX_SIZE >= MBEDTLS_MD_MAX_SIZE,
38 	assert_mbedtls_md_size_overflow);
39 
40 #endif /*
41 	* CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY || \
42 	* CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC
43 	*/
44 
45 static inline psa_algorithm_t mbedtls_md_psa_alg_from_type(
46 						mbedtls_md_type_t md_type)
47 {
48 	assert((md_type == MBEDTLS_MD_SHA256) ||
49 	       (md_type == MBEDTLS_MD_SHA384) ||
50 	       (md_type == MBEDTLS_MD_SHA512));
51 
52 	return PSA_ALG_CATEGORY_HASH | (psa_algorithm_t) (md_type + 0x5);
53 }
54 
55 /*
56  * AlgorithmIdentifier  ::=  SEQUENCE  {
57  *     algorithm               OBJECT IDENTIFIER,
58  *     parameters              ANY DEFINED BY algorithm OPTIONAL
59  * }
60  *
61  * SubjectPublicKeyInfo  ::=  SEQUENCE  {
62  *     algorithm            AlgorithmIdentifier,
63  *     subjectPublicKey     BIT STRING
64  * }
65  *
66  * DigestInfo ::= SEQUENCE {
67  *     digestAlgorithm AlgorithmIdentifier,
68  *     digest OCTET STRING
69  * }
70  */
71 
72 /*
73  * We pretend using an external RNG (through MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG
74  * mbedTLS config option) so we need to provide an implementation of
75  * mbedtls_psa_external_get_random(). Provide a fake one, since we do not
76  * actually have any external RNG and TF-A itself doesn't engage in
77  * cryptographic operations that demands randomness.
78  */
79 psa_status_t mbedtls_psa_external_get_random(
80 			mbedtls_psa_external_random_context_t *context,
81 			uint8_t *output, size_t output_size,
82 			size_t *output_length)
83 {
84 	return PSA_ERROR_INSUFFICIENT_ENTROPY;
85 }
86 
87 /*
88  * Initialize the library and export the descriptor
89  */
90 static void init(void)
91 {
92 	/* Initialize mbed TLS */
93 	mbedtls_init();
94 
95 	/* Initialise PSA mbedTLS */
96 	psa_status_t status = psa_crypto_init();
97 
98 	if (status != PSA_SUCCESS) {
99 		ERROR("Failed to initialize %s crypto (%d).\n", LIB_NAME, status);
100 		panic();
101 	}
102 
103 	INFO("PSA crypto initialized successfully!\n");
104 }
105 
106 #if CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_ONLY || \
107 CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC
108 /*
109  * Verify a signature.
110  *
111  * Parameters are passed using the DER encoding format following the ASN.1
112  * structures detailed above.
113  */
114 static int verify_signature(void *data_ptr, unsigned int data_len,
115 			    void *sig_ptr, unsigned int sig_len,
116 			    void *sig_alg, unsigned int sig_alg_len,
117 			    void *pk_ptr, unsigned int pk_len)
118 {
119 	mbedtls_asn1_buf sig_oid, sig_params;
120 	mbedtls_asn1_buf signature;
121 	mbedtls_md_type_t md_alg;
122 	mbedtls_pk_type_t pk_alg;
123 	mbedtls_pk_context pk = {0};
124 	int rc;
125 	void *sig_opts = NULL;
126 	const mbedtls_md_info_t *md_info;
127 	unsigned char *p, *end;
128 	unsigned char hash[MBEDTLS_MD_MAX_SIZE];
129 
130 	/* Get pointers to signature OID and parameters */
131 	p = (unsigned char *)sig_alg;
132 	end = (unsigned char *)(p + sig_alg_len);
133 	rc = mbedtls_asn1_get_alg(&p, end, &sig_oid, &sig_params);
134 	if (rc != 0) {
135 		return CRYPTO_ERR_SIGNATURE;
136 	}
137 
138 	/* Get the actual signature algorithm (MD + PK) */
139 	rc = mbedtls_x509_get_sig_alg(&sig_oid, &sig_params, &md_alg, &pk_alg, &sig_opts);
140 	if (rc != 0) {
141 		return CRYPTO_ERR_SIGNATURE;
142 	}
143 
144 	/* Parse the public key */
145 	mbedtls_pk_init(&pk);
146 	p = (unsigned char *)pk_ptr;
147 	end = (unsigned char *)(p + pk_len);
148 	rc = mbedtls_pk_parse_subpubkey(&p, end, &pk);
149 	if (rc != 0) {
150 		rc = CRYPTO_ERR_SIGNATURE;
151 		goto end2;
152 	}
153 
154 	/* Get the signature (bitstring) */
155 	p = (unsigned char *)sig_ptr;
156 	end = (unsigned char *)(p + sig_len);
157 	signature.tag = *p;
158 	rc = mbedtls_asn1_get_bitstring_null(&p, end, &signature.len);
159 	if ((rc != 0) || ((size_t)(end - p) != signature.len)) {
160 		rc = CRYPTO_ERR_SIGNATURE;
161 		goto end1;
162 	}
163 	signature.p = p;
164 
165 	/* Calculate the hash of the data */
166 	md_info = mbedtls_md_info_from_type(md_alg);
167 	if (md_info == NULL) {
168 		rc = CRYPTO_ERR_SIGNATURE;
169 		goto end1;
170 	}
171 	p = (unsigned char *)data_ptr;
172 	rc = mbedtls_md(md_info, p, data_len, hash);
173 	if (rc != 0) {
174 		rc = CRYPTO_ERR_SIGNATURE;
175 		goto end1;
176 	}
177 
178 	/* Verify the signature */
179 	rc = mbedtls_pk_verify_ext(pk_alg, sig_opts, &pk, md_alg, hash,
180 			mbedtls_md_get_size(md_info),
181 			signature.p, signature.len);
182 	if (rc != 0) {
183 		rc = CRYPTO_ERR_SIGNATURE;
184 		goto end1;
185 	}
186 
187 	/* Signature verification success */
188 	rc = CRYPTO_SUCCESS;
189 
190 end1:
191 	mbedtls_pk_free(&pk);
192 end2:
193 	mbedtls_free(sig_opts);
194 	return rc;
195 }
196 
197 /*
198  * Match a hash
199  *
200  * Digest info is passed in DER format following the ASN.1 structure detailed
201  * above.
202  */
203 static int verify_hash(void *data_ptr, unsigned int data_len,
204 		       void *digest_info_ptr, unsigned int digest_info_len)
205 {
206 	mbedtls_asn1_buf hash_oid, params;
207 	mbedtls_md_type_t md_alg;
208 	unsigned char *p, *end, *hash;
209 	size_t len;
210 	int rc;
211 	psa_status_t status;
212 	psa_algorithm_t psa_md_alg;
213 
214 	/*
215 	 * Digest info should be an MBEDTLS_ASN1_SEQUENCE, but padding after
216 	 * it is allowed.  This is necessary to support multiple hash
217 	 * algorithms.
218 	 */
219 	p = (unsigned char *)digest_info_ptr;
220 	end = p + digest_info_len;
221 	rc = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED |
222 				  MBEDTLS_ASN1_SEQUENCE);
223 	if (rc != 0) {
224 		return CRYPTO_ERR_HASH;
225 	}
226 
227 	end = p + len;
228 
229 	/* Get the hash algorithm */
230 	rc = mbedtls_asn1_get_alg(&p, end, &hash_oid, &params);
231 	if (rc != 0) {
232 		return CRYPTO_ERR_HASH;
233 	}
234 
235 	/* Hash should be octet string type and consume all bytes */
236 	rc = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING);
237 	if ((rc != 0) || ((size_t)(end - p) != len)) {
238 		return CRYPTO_ERR_HASH;
239 	}
240 	hash = p;
241 
242 	rc = mbedtls_oid_get_md_alg(&hash_oid, &md_alg);
243 	if (rc != 0) {
244 		return CRYPTO_ERR_HASH;
245 	}
246 
247 	/* convert the md_alg to psa_algo */
248 	psa_md_alg = mbedtls_md_psa_alg_from_type(md_alg);
249 
250 	/* Length of hash must match the algorithm's size */
251 	if (len != PSA_HASH_LENGTH(psa_md_alg)) {
252 		return CRYPTO_ERR_HASH;
253 	}
254 
255 	/*
256 	 * Calculate Hash and compare it against the retrieved hash from
257 	 * the certificate (one shot API).
258 	 */
259 	status = psa_hash_compare(psa_md_alg,
260 				  data_ptr, (size_t)data_len,
261 				  (const uint8_t *)hash, len);
262 
263 	if (status != PSA_SUCCESS) {
264 		return CRYPTO_ERR_HASH;
265 	}
266 
267 	return CRYPTO_SUCCESS;
268 }
269 #endif /*
270 	* CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_ONLY || \
271 	* CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC
272 	*/
273 
274 #if CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY || \
275 CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC
276 /*
277  * Map a generic crypto message digest algorithm to the corresponding macro used
278  * by Mbed TLS.
279  */
280 static inline mbedtls_md_type_t md_type(enum crypto_md_algo algo)
281 {
282 	switch (algo) {
283 	case CRYPTO_MD_SHA512:
284 		return MBEDTLS_MD_SHA512;
285 	case CRYPTO_MD_SHA384:
286 		return MBEDTLS_MD_SHA384;
287 	case CRYPTO_MD_SHA256:
288 		return MBEDTLS_MD_SHA256;
289 	default:
290 		/* Invalid hash algorithm. */
291 		return MBEDTLS_MD_NONE;
292 	}
293 }
294 
295 /*
296  * Calculate a hash
297  *
298  * output points to the computed hash
299  */
300 static int calc_hash(enum crypto_md_algo md_algo, void *data_ptr,
301 		     unsigned int data_len,
302 		     unsigned char output[CRYPTO_MD_MAX_SIZE])
303 {
304 	size_t hash_length;
305 	psa_status_t status;
306 	psa_algorithm_t psa_md_alg;
307 
308 	/* convert the md_alg to psa_algo */
309 	psa_md_alg = mbedtls_md_psa_alg_from_type(md_type(md_algo));
310 
311 	/*
312 	 * Calculate the hash of the data, it is safe to pass the
313 	 * 'output' hash buffer pointer considering its size is always
314 	 * bigger than or equal to MBEDTLS_MD_MAX_SIZE.
315 	 */
316 	status = psa_hash_compute(psa_md_alg, data_ptr, (size_t)data_len,
317 				  (uint8_t *)output, CRYPTO_MD_MAX_SIZE,
318 				  &hash_length);
319 	if (status != PSA_SUCCESS) {
320 		return CRYPTO_ERR_HASH;
321 	}
322 
323 	return CRYPTO_SUCCESS;
324 }
325 #endif /*
326 	* CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY || \
327 	* CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC
328 	*/
329 
330 #if TF_MBEDTLS_USE_AES_GCM
331 /*
332  * Stack based buffer allocation for decryption operation. It could
333  * be configured to balance stack usage vs execution speed.
334  */
335 #define DEC_OP_BUF_SIZE		128
336 
337 static int aes_gcm_decrypt(void *data_ptr, size_t len, const void *key,
338 			   unsigned int key_len, const void *iv,
339 			   unsigned int iv_len, const void *tag,
340 			   unsigned int tag_len)
341 {
342 	mbedtls_gcm_context ctx;
343 	mbedtls_cipher_id_t cipher = MBEDTLS_CIPHER_ID_AES;
344 	unsigned char buf[DEC_OP_BUF_SIZE];
345 	unsigned char tag_buf[CRYPTO_MAX_TAG_SIZE];
346 	unsigned char *pt = data_ptr;
347 	size_t dec_len;
348 	int diff, i, rc;
349 	size_t output_length __unused;
350 
351 	mbedtls_gcm_init(&ctx);
352 
353 	rc = mbedtls_gcm_setkey(&ctx, cipher, key, key_len * 8);
354 	if (rc != 0) {
355 		rc = CRYPTO_ERR_DECRYPTION;
356 		goto exit_gcm;
357 	}
358 
359 #if (MBEDTLS_VERSION_MAJOR < 3)
360 	rc = mbedtls_gcm_starts(&ctx, MBEDTLS_GCM_DECRYPT, iv, iv_len, NULL, 0);
361 #else
362 	rc = mbedtls_gcm_starts(&ctx, MBEDTLS_GCM_DECRYPT, iv, iv_len);
363 #endif
364 	if (rc != 0) {
365 		rc = CRYPTO_ERR_DECRYPTION;
366 		goto exit_gcm;
367 	}
368 
369 	while (len > 0) {
370 		dec_len = MIN(sizeof(buf), len);
371 
372 #if (MBEDTLS_VERSION_MAJOR < 3)
373 		rc = mbedtls_gcm_update(&ctx, dec_len, pt, buf);
374 #else
375 		rc = mbedtls_gcm_update(&ctx, pt, dec_len, buf, sizeof(buf), &output_length);
376 #endif
377 
378 		if (rc != 0) {
379 			rc = CRYPTO_ERR_DECRYPTION;
380 			goto exit_gcm;
381 		}
382 
383 		memcpy(pt, buf, dec_len);
384 		pt += dec_len;
385 		len -= dec_len;
386 	}
387 
388 #if (MBEDTLS_VERSION_MAJOR < 3)
389 	rc = mbedtls_gcm_finish(&ctx, tag_buf, sizeof(tag_buf));
390 #else
391 	rc = mbedtls_gcm_finish(&ctx, NULL, 0, &output_length, tag_buf, sizeof(tag_buf));
392 #endif
393 
394 	if (rc != 0) {
395 		rc = CRYPTO_ERR_DECRYPTION;
396 		goto exit_gcm;
397 	}
398 
399 	/* Check tag in "constant-time" */
400 	for (diff = 0, i = 0; i < tag_len; i++)
401 		diff |= ((const unsigned char *)tag)[i] ^ tag_buf[i];
402 
403 	if (diff != 0) {
404 		rc = CRYPTO_ERR_DECRYPTION;
405 		goto exit_gcm;
406 	}
407 
408 	/* GCM decryption success */
409 	rc = CRYPTO_SUCCESS;
410 
411 exit_gcm:
412 	mbedtls_gcm_free(&ctx);
413 	return rc;
414 }
415 
416 /*
417  * Authenticated decryption of an image
418  */
419 static int auth_decrypt(enum crypto_dec_algo dec_algo, void *data_ptr,
420 			size_t len, const void *key, unsigned int key_len,
421 			unsigned int key_flags, const void *iv,
422 			unsigned int iv_len, const void *tag,
423 			unsigned int tag_len)
424 {
425 	int rc;
426 
427 	assert((key_flags & ENC_KEY_IS_IDENTIFIER) == 0);
428 
429 	switch (dec_algo) {
430 	case CRYPTO_GCM_DECRYPT:
431 		rc = aes_gcm_decrypt(data_ptr, len, key, key_len, iv, iv_len,
432 				     tag, tag_len);
433 		if (rc != 0)
434 			return rc;
435 		break;
436 	default:
437 		return CRYPTO_ERR_DECRYPTION;
438 	}
439 
440 	return CRYPTO_SUCCESS;
441 }
442 #endif /* TF_MBEDTLS_USE_AES_GCM */
443 
444 /*
445  * Register crypto library descriptor
446  */
447 #if CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC
448 #if TF_MBEDTLS_USE_AES_GCM
449 REGISTER_CRYPTO_LIB(LIB_NAME, init, verify_signature, verify_hash, calc_hash,
450 		    auth_decrypt, NULL);
451 #else
452 REGISTER_CRYPTO_LIB(LIB_NAME, init, verify_signature, verify_hash, calc_hash,
453 		    NULL, NULL);
454 #endif
455 #elif CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_ONLY
456 #if TF_MBEDTLS_USE_AES_GCM
457 REGISTER_CRYPTO_LIB(LIB_NAME, init, verify_signature, verify_hash, NULL,
458 		    auth_decrypt, NULL);
459 #else
460 REGISTER_CRYPTO_LIB(LIB_NAME, init, verify_signature, verify_hash, NULL,
461 		    NULL, NULL);
462 #endif
463 #elif CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY
464 REGISTER_CRYPTO_LIB(LIB_NAME, init, NULL, NULL, calc_hash, NULL, NULL);
465 #endif /* CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC */
466