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