Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / mbedtls / repo / library / pk_wrap.c
1 /*
2  *  Public Key abstraction layer: wrapper functions
3  *
4  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
5  *  SPDX-License-Identifier: Apache-2.0
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *
19  *  This file is part of mbed TLS (https://tls.mbed.org)
20  */
21
22 #if !defined(MBEDTLS_CONFIG_FILE)
23 #include "mbedtls/config.h"
24 #else
25 #include MBEDTLS_CONFIG_FILE
26 #endif
27
28 #if defined(MBEDTLS_PK_C)
29 #include "mbedtls/pk_internal.h"
30
31 /* Even if RSA not activated, for the sake of RSA-alt */
32 #include "mbedtls/rsa.h"
33
34 #include <string.h>
35
36 #if defined(MBEDTLS_ECP_C)
37 #include "mbedtls/ecp.h"
38 #endif
39
40 #if defined(MBEDTLS_ECDSA_C)
41 #include "mbedtls/ecdsa.h"
42 #endif
43
44 #if defined(MBEDTLS_USE_PSA_CRYPTO)
45 #include "mbedtls/asn1write.h"
46 #endif
47
48 #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
49 #include "mbedtls/platform_util.h"
50 #endif
51
52 #if defined(MBEDTLS_USE_PSA_CRYPTO)
53 #include "psa/crypto.h"
54 #include "mbedtls/psa_util.h"
55 #include "mbedtls/asn1.h"
56 #endif
57
58 #if defined(MBEDTLS_PLATFORM_C)
59 #include "mbedtls/platform.h"
60 #else
61 #include <stdlib.h>
62 #define mbedtls_calloc    calloc
63 #define mbedtls_free       free
64 #endif
65
66 #include <limits.h>
67 #include <stdint.h>
68
69 #if defined(MBEDTLS_RSA_C)
70 static int rsa_can_do( mbedtls_pk_type_t type )
71 {
72     return( type == MBEDTLS_PK_RSA ||
73             type == MBEDTLS_PK_RSASSA_PSS );
74 }
75
76 static size_t rsa_get_bitlen( const void *ctx )
77 {
78     const mbedtls_rsa_context * rsa = (const mbedtls_rsa_context *) ctx;
79     return( 8 * mbedtls_rsa_get_len( rsa ) );
80 }
81
82 static int rsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,
83                    const unsigned char *hash, size_t hash_len,
84                    const unsigned char *sig, size_t sig_len )
85 {
86     int ret;
87     mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx;
88     size_t rsa_len = mbedtls_rsa_get_len( rsa );
89
90 #if SIZE_MAX > UINT_MAX
91     if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len )
92         return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
93 #endif /* SIZE_MAX > UINT_MAX */
94
95     if( sig_len < rsa_len )
96         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
97
98     if( ( ret = mbedtls_rsa_pkcs1_verify( rsa, NULL, NULL,
99                                   MBEDTLS_RSA_PUBLIC, md_alg,
100                                   (unsigned int) hash_len, hash, sig ) ) != 0 )
101         return( ret );
102
103     /* The buffer contains a valid signature followed by extra data.
104      * We have a special error code for that so that so that callers can
105      * use mbedtls_pk_verify() to check "Does the buffer start with a
106      * valid signature?" and not just "Does the buffer contain a valid
107      * signature?". */
108     if( sig_len > rsa_len )
109         return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH );
110
111     return( 0 );
112 }
113
114 static int rsa_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,
115                    const unsigned char *hash, size_t hash_len,
116                    unsigned char *sig, size_t *sig_len,
117                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
118 {
119     mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx;
120
121 #if SIZE_MAX > UINT_MAX
122     if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len )
123         return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
124 #endif /* SIZE_MAX > UINT_MAX */
125
126     *sig_len = mbedtls_rsa_get_len( rsa );
127
128     return( mbedtls_rsa_pkcs1_sign( rsa, f_rng, p_rng, MBEDTLS_RSA_PRIVATE,
129                 md_alg, (unsigned int) hash_len, hash, sig ) );
130 }
131
132 static int rsa_decrypt_wrap( void *ctx,
133                     const unsigned char *input, size_t ilen,
134                     unsigned char *output, size_t *olen, size_t osize,
135                     int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
136 {
137     mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx;
138
139     if( ilen != mbedtls_rsa_get_len( rsa ) )
140         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
141
142     return( mbedtls_rsa_pkcs1_decrypt( rsa, f_rng, p_rng,
143                 MBEDTLS_RSA_PRIVATE, olen, input, output, osize ) );
144 }
145
146 static int rsa_encrypt_wrap( void *ctx,
147                     const unsigned char *input, size_t ilen,
148                     unsigned char *output, size_t *olen, size_t osize,
149                     int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
150 {
151     mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx;
152     *olen = mbedtls_rsa_get_len( rsa );
153
154     if( *olen > osize )
155         return( MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE );
156
157     return( mbedtls_rsa_pkcs1_encrypt( rsa, f_rng, p_rng, MBEDTLS_RSA_PUBLIC,
158                                        ilen, input, output ) );
159 }
160
161 static int rsa_check_pair_wrap( const void *pub, const void *prv )
162 {
163     return( mbedtls_rsa_check_pub_priv( (const mbedtls_rsa_context *) pub,
164                                 (const mbedtls_rsa_context *) prv ) );
165 }
166
167 static void *rsa_alloc_wrap( void )
168 {
169     void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_rsa_context ) );
170
171     if( ctx != NULL )
172         mbedtls_rsa_init( (mbedtls_rsa_context *) ctx, 0, 0 );
173
174     return( ctx );
175 }
176
177 static void rsa_free_wrap( void *ctx )
178 {
179     mbedtls_rsa_free( (mbedtls_rsa_context *) ctx );
180     mbedtls_free( ctx );
181 }
182
183 static void rsa_debug( const void *ctx, mbedtls_pk_debug_item *items )
184 {
185     items->type = MBEDTLS_PK_DEBUG_MPI;
186     items->name = "rsa.N";
187     items->value = &( ((mbedtls_rsa_context *) ctx)->N );
188
189     items++;
190
191     items->type = MBEDTLS_PK_DEBUG_MPI;
192     items->name = "rsa.E";
193     items->value = &( ((mbedtls_rsa_context *) ctx)->E );
194 }
195
196 const mbedtls_pk_info_t mbedtls_rsa_info = {
197     MBEDTLS_PK_RSA,
198     "RSA",
199     rsa_get_bitlen,
200     rsa_can_do,
201     rsa_verify_wrap,
202     rsa_sign_wrap,
203 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
204     NULL,
205     NULL,
206 #endif
207     rsa_decrypt_wrap,
208     rsa_encrypt_wrap,
209     rsa_check_pair_wrap,
210     rsa_alloc_wrap,
211     rsa_free_wrap,
212 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
213     NULL,
214     NULL,
215 #endif
216     rsa_debug,
217 };
218 #endif /* MBEDTLS_RSA_C */
219
220 #if defined(MBEDTLS_ECP_C)
221 /*
222  * Generic EC key
223  */
224 static int eckey_can_do( mbedtls_pk_type_t type )
225 {
226     return( type == MBEDTLS_PK_ECKEY ||
227             type == MBEDTLS_PK_ECKEY_DH ||
228             type == MBEDTLS_PK_ECDSA );
229 }
230
231 static size_t eckey_get_bitlen( const void *ctx )
232 {
233     return( ((mbedtls_ecp_keypair *) ctx)->grp.pbits );
234 }
235
236 #if defined(MBEDTLS_ECDSA_C)
237 /* Forward declarations */
238 static int ecdsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,
239                        const unsigned char *hash, size_t hash_len,
240                        const unsigned char *sig, size_t sig_len );
241
242 static int ecdsa_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,
243                    const unsigned char *hash, size_t hash_len,
244                    unsigned char *sig, size_t *sig_len,
245                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );
246
247 static int eckey_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,
248                        const unsigned char *hash, size_t hash_len,
249                        const unsigned char *sig, size_t sig_len )
250 {
251     int ret;
252     mbedtls_ecdsa_context ecdsa;
253
254     mbedtls_ecdsa_init( &ecdsa );
255
256     if( ( ret = mbedtls_ecdsa_from_keypair( &ecdsa, ctx ) ) == 0 )
257         ret = ecdsa_verify_wrap( &ecdsa, md_alg, hash, hash_len, sig, sig_len );
258
259     mbedtls_ecdsa_free( &ecdsa );
260
261     return( ret );
262 }
263
264 static int eckey_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,
265                    const unsigned char *hash, size_t hash_len,
266                    unsigned char *sig, size_t *sig_len,
267                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
268 {
269     int ret;
270     mbedtls_ecdsa_context ecdsa;
271
272     mbedtls_ecdsa_init( &ecdsa );
273
274     if( ( ret = mbedtls_ecdsa_from_keypair( &ecdsa, ctx ) ) == 0 )
275         ret = ecdsa_sign_wrap( &ecdsa, md_alg, hash, hash_len, sig, sig_len,
276                                f_rng, p_rng );
277
278     mbedtls_ecdsa_free( &ecdsa );
279
280     return( ret );
281 }
282
283 #if defined(MBEDTLS_ECP_RESTARTABLE)
284 /* Forward declarations */
285 static int ecdsa_verify_rs_wrap( void *ctx, mbedtls_md_type_t md_alg,
286                        const unsigned char *hash, size_t hash_len,
287                        const unsigned char *sig, size_t sig_len,
288                        void *rs_ctx );
289
290 static int ecdsa_sign_rs_wrap( void *ctx, mbedtls_md_type_t md_alg,
291                    const unsigned char *hash, size_t hash_len,
292                    unsigned char *sig, size_t *sig_len,
293                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
294                    void *rs_ctx );
295
296 /*
297  * Restart context for ECDSA operations with ECKEY context
298  *
299  * We need to store an actual ECDSA context, as we need to pass the same to
300  * the underlying ecdsa function, so we can't create it on the fly every time.
301  */
302 typedef struct
303 {
304     mbedtls_ecdsa_restart_ctx ecdsa_rs;
305     mbedtls_ecdsa_context ecdsa_ctx;
306 } eckey_restart_ctx;
307
308 static void *eckey_rs_alloc( void )
309 {
310     eckey_restart_ctx *rs_ctx;
311
312     void *ctx = mbedtls_calloc( 1, sizeof( eckey_restart_ctx ) );
313
314     if( ctx != NULL )
315     {
316         rs_ctx = ctx;
317         mbedtls_ecdsa_restart_init( &rs_ctx->ecdsa_rs );
318         mbedtls_ecdsa_init( &rs_ctx->ecdsa_ctx );
319     }
320
321     return( ctx );
322 }
323
324 static void eckey_rs_free( void *ctx )
325 {
326     eckey_restart_ctx *rs_ctx;
327
328     if( ctx == NULL)
329         return;
330
331     rs_ctx = ctx;
332     mbedtls_ecdsa_restart_free( &rs_ctx->ecdsa_rs );
333     mbedtls_ecdsa_free( &rs_ctx->ecdsa_ctx );
334
335     mbedtls_free( ctx );
336 }
337
338 static int eckey_verify_rs_wrap( void *ctx, mbedtls_md_type_t md_alg,
339                        const unsigned char *hash, size_t hash_len,
340                        const unsigned char *sig, size_t sig_len,
341                        void *rs_ctx )
342 {
343     int ret;
344     eckey_restart_ctx *rs = rs_ctx;
345
346     /* Should never happen */
347     if( rs == NULL )
348         return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
349
350     /* set up our own sub-context if needed (that is, on first run) */
351     if( rs->ecdsa_ctx.grp.pbits == 0 )
352         MBEDTLS_MPI_CHK( mbedtls_ecdsa_from_keypair( &rs->ecdsa_ctx, ctx ) );
353
354     MBEDTLS_MPI_CHK( ecdsa_verify_rs_wrap( &rs->ecdsa_ctx,
355                                            md_alg, hash, hash_len,
356                                            sig, sig_len, &rs->ecdsa_rs ) );
357
358 cleanup:
359     return( ret );
360 }
361
362 static int eckey_sign_rs_wrap( void *ctx, mbedtls_md_type_t md_alg,
363                    const unsigned char *hash, size_t hash_len,
364                    unsigned char *sig, size_t *sig_len,
365                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
366                        void *rs_ctx )
367 {
368     int ret;
369     eckey_restart_ctx *rs = rs_ctx;
370
371     /* Should never happen */
372     if( rs == NULL )
373         return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
374
375     /* set up our own sub-context if needed (that is, on first run) */
376     if( rs->ecdsa_ctx.grp.pbits == 0 )
377         MBEDTLS_MPI_CHK( mbedtls_ecdsa_from_keypair( &rs->ecdsa_ctx, ctx ) );
378
379     MBEDTLS_MPI_CHK( ecdsa_sign_rs_wrap( &rs->ecdsa_ctx, md_alg,
380                                          hash, hash_len, sig, sig_len,
381                                          f_rng, p_rng, &rs->ecdsa_rs ) );
382
383 cleanup:
384     return( ret );
385 }
386 #endif /* MBEDTLS_ECP_RESTARTABLE */
387 #endif /* MBEDTLS_ECDSA_C */
388
389 static int eckey_check_pair( const void *pub, const void *prv )
390 {
391     return( mbedtls_ecp_check_pub_priv( (const mbedtls_ecp_keypair *) pub,
392                                 (const mbedtls_ecp_keypair *) prv ) );
393 }
394
395 static void *eckey_alloc_wrap( void )
396 {
397     void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ecp_keypair ) );
398
399     if( ctx != NULL )
400         mbedtls_ecp_keypair_init( ctx );
401
402     return( ctx );
403 }
404
405 static void eckey_free_wrap( void *ctx )
406 {
407     mbedtls_ecp_keypair_free( (mbedtls_ecp_keypair *) ctx );
408     mbedtls_free( ctx );
409 }
410
411 static void eckey_debug( const void *ctx, mbedtls_pk_debug_item *items )
412 {
413     items->type = MBEDTLS_PK_DEBUG_ECP;
414     items->name = "eckey.Q";
415     items->value = &( ((mbedtls_ecp_keypair *) ctx)->Q );
416 }
417
418 const mbedtls_pk_info_t mbedtls_eckey_info = {
419     MBEDTLS_PK_ECKEY,
420     "EC",
421     eckey_get_bitlen,
422     eckey_can_do,
423 #if defined(MBEDTLS_ECDSA_C)
424     eckey_verify_wrap,
425     eckey_sign_wrap,
426 #if defined(MBEDTLS_ECP_RESTARTABLE)
427     eckey_verify_rs_wrap,
428     eckey_sign_rs_wrap,
429 #endif
430 #else /* MBEDTLS_ECDSA_C */
431     NULL,
432     NULL,
433 #endif /* MBEDTLS_ECDSA_C */
434     NULL,
435     NULL,
436     eckey_check_pair,
437     eckey_alloc_wrap,
438     eckey_free_wrap,
439 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
440     eckey_rs_alloc,
441     eckey_rs_free,
442 #endif
443     eckey_debug,
444 };
445
446 /*
447  * EC key restricted to ECDH
448  */
449 static int eckeydh_can_do( mbedtls_pk_type_t type )
450 {
451     return( type == MBEDTLS_PK_ECKEY ||
452             type == MBEDTLS_PK_ECKEY_DH );
453 }
454
455 const mbedtls_pk_info_t mbedtls_eckeydh_info = {
456     MBEDTLS_PK_ECKEY_DH,
457     "EC_DH",
458     eckey_get_bitlen,         /* Same underlying key structure */
459     eckeydh_can_do,
460     NULL,
461     NULL,
462 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
463     NULL,
464     NULL,
465 #endif
466     NULL,
467     NULL,
468     eckey_check_pair,
469     eckey_alloc_wrap,       /* Same underlying key structure */
470     eckey_free_wrap,        /* Same underlying key structure */
471 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
472     NULL,
473     NULL,
474 #endif
475     eckey_debug,            /* Same underlying key structure */
476 };
477 #endif /* MBEDTLS_ECP_C */
478
479 #if defined(MBEDTLS_ECDSA_C)
480 static int ecdsa_can_do( mbedtls_pk_type_t type )
481 {
482     return( type == MBEDTLS_PK_ECDSA );
483 }
484
485 #if defined(MBEDTLS_USE_PSA_CRYPTO)
486 /*
487  * An ASN.1 encoded signature is a sequence of two ASN.1 integers. Parse one of
488  * those integers and convert it to the fixed-length encoding expected by PSA.
489  */
490 static int extract_ecdsa_sig_int( unsigned char **from, const unsigned char *end,
491                                   unsigned char *to, size_t to_len )
492 {
493     int ret;
494     size_t unpadded_len, padding_len;
495
496     if( ( ret = mbedtls_asn1_get_tag( from, end, &unpadded_len,
497                                       MBEDTLS_ASN1_INTEGER ) ) != 0 )
498     {
499         return( ret );
500     }
501
502     while( unpadded_len > 0 && **from == 0x00 )
503     {
504         ( *from )++;
505         unpadded_len--;
506     }
507
508     if( unpadded_len > to_len || unpadded_len == 0 )
509         return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
510
511     padding_len = to_len - unpadded_len;
512     memset( to, 0x00, padding_len );
513     memcpy( to + padding_len, *from, unpadded_len );
514     ( *from ) += unpadded_len;
515
516     return( 0 );
517 }
518
519 /*
520  * Convert a signature from an ASN.1 sequence of two integers
521  * to a raw {r,s} buffer. Note: the provided sig buffer must be at least
522  * twice as big as int_size.
523  */
524 static int extract_ecdsa_sig( unsigned char **p, const unsigned char *end,
525                               unsigned char *sig, size_t int_size )
526 {
527     int ret;
528     size_t tmp_size;
529
530     if( ( ret = mbedtls_asn1_get_tag( p, end, &tmp_size,
531                 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
532         return( ret );
533
534     /* Extract r */
535     if( ( ret = extract_ecdsa_sig_int( p, end, sig, int_size ) ) != 0 )
536         return( ret );
537     /* Extract s */
538     if( ( ret = extract_ecdsa_sig_int( p, end, sig + int_size, int_size ) ) != 0 )
539         return( ret );
540
541     return( 0 );
542 }
543
544 static int ecdsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,
545                        const unsigned char *hash, size_t hash_len,
546                        const unsigned char *sig, size_t sig_len )
547 {
548     int ret;
549     psa_key_handle_t key_slot;
550     psa_key_policy_t policy;
551     psa_key_type_t psa_type;
552     mbedtls_pk_context key;
553     int key_len;
554     /* see ECP_PUB_DER_MAX_BYTES in pkwrite.c */
555     unsigned char buf[30 + 2 * MBEDTLS_ECP_MAX_BYTES];
556     unsigned char *p;
557     mbedtls_pk_info_t pk_info = mbedtls_eckey_info;
558     psa_algorithm_t psa_sig_md, psa_md;
559     psa_ecc_curve_t curve = mbedtls_psa_translate_ecc_group(
560                             ( (mbedtls_ecdsa_context *) ctx )->grp.id );
561     const size_t signature_part_size = ( ( (mbedtls_ecdsa_context *) ctx )->grp.nbits + 7 ) / 8;
562
563     if( curve == 0 )
564         return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
565
566     /* mbedtls_pk_write_pubkey() expects a full PK context;
567      * re-construct one to make it happy */
568     key.pk_info = &pk_info;
569     key.pk_ctx = ctx;
570     p = buf + sizeof( buf );
571     key_len = mbedtls_pk_write_pubkey( &p, buf, &key );
572     if( key_len <= 0 )
573         return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
574
575     psa_md = mbedtls_psa_translate_md( md_alg );
576     if( psa_md == 0 )
577         return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
578     psa_sig_md = PSA_ALG_ECDSA( psa_md );
579     psa_type = PSA_KEY_TYPE_ECC_PUBLIC_KEY( curve );
580
581     if( ( ret = psa_allocate_key( &key_slot ) ) != PSA_SUCCESS )
582           return( mbedtls_psa_err_translate_pk( ret ) );
583
584     policy = psa_key_policy_init();
585     psa_key_policy_set_usage( &policy, PSA_KEY_USAGE_VERIFY, psa_sig_md );
586     if( ( ret = psa_set_key_policy( key_slot, &policy ) ) != PSA_SUCCESS )
587     {
588         ret = mbedtls_psa_err_translate_pk( ret );
589         goto cleanup;
590     }
591
592     if( psa_import_key( key_slot, psa_type, buf + sizeof( buf ) - key_len, key_len )
593          != PSA_SUCCESS )
594     {
595         ret = MBEDTLS_ERR_PK_BAD_INPUT_DATA;
596         goto cleanup;
597     }
598
599     /* We don't need the exported key anymore and can
600      * reuse its buffer for signature extraction. */
601     if( 2 * signature_part_size > sizeof( buf ) )
602     {
603         ret = MBEDTLS_ERR_PK_BAD_INPUT_DATA;
604         goto cleanup;
605     }
606
607     p = (unsigned char*) sig;
608     if( ( ret = extract_ecdsa_sig( &p, sig + sig_len, buf,
609                                    signature_part_size ) ) != 0 )
610     {
611         goto cleanup;
612     }
613
614     if( psa_asymmetric_verify( key_slot, psa_sig_md,
615                                hash, hash_len,
616                                buf, 2 * signature_part_size )
617          != PSA_SUCCESS )
618     {
619          ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;
620          goto cleanup;
621     }
622
623     if( p != sig + sig_len )
624     {
625         ret = MBEDTLS_ERR_PK_SIG_LEN_MISMATCH;
626         goto cleanup;
627     }
628     ret = 0;
629
630 cleanup:
631     psa_destroy_key( key_slot );
632     return( ret );
633 }
634 #else /* MBEDTLS_USE_PSA_CRYPTO */
635 static int ecdsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,
636                        const unsigned char *hash, size_t hash_len,
637                        const unsigned char *sig, size_t sig_len )
638 {
639     int ret;
640     ((void) md_alg);
641
642     ret = mbedtls_ecdsa_read_signature( (mbedtls_ecdsa_context *) ctx,
643                                 hash, hash_len, sig, sig_len );
644
645     if( ret == MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH )
646         return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH );
647
648     return( ret );
649 }
650 #endif /* MBEDTLS_USE_PSA_CRYPTO */
651
652 static int ecdsa_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,
653                    const unsigned char *hash, size_t hash_len,
654                    unsigned char *sig, size_t *sig_len,
655                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
656 {
657     return( mbedtls_ecdsa_write_signature( (mbedtls_ecdsa_context *) ctx,
658                 md_alg, hash, hash_len, sig, sig_len, f_rng, p_rng ) );
659 }
660
661 #if defined(MBEDTLS_ECP_RESTARTABLE)
662 static int ecdsa_verify_rs_wrap( void *ctx, mbedtls_md_type_t md_alg,
663                        const unsigned char *hash, size_t hash_len,
664                        const unsigned char *sig, size_t sig_len,
665                        void *rs_ctx )
666 {
667     int ret;
668     ((void) md_alg);
669
670     ret = mbedtls_ecdsa_read_signature_restartable(
671             (mbedtls_ecdsa_context *) ctx,
672             hash, hash_len, sig, sig_len,
673             (mbedtls_ecdsa_restart_ctx *) rs_ctx );
674
675     if( ret == MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH )
676         return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH );
677
678     return( ret );
679 }
680
681 static int ecdsa_sign_rs_wrap( void *ctx, mbedtls_md_type_t md_alg,
682                    const unsigned char *hash, size_t hash_len,
683                    unsigned char *sig, size_t *sig_len,
684                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
685                    void *rs_ctx )
686 {
687     return( mbedtls_ecdsa_write_signature_restartable(
688                 (mbedtls_ecdsa_context *) ctx,
689                 md_alg, hash, hash_len, sig, sig_len, f_rng, p_rng,
690                 (mbedtls_ecdsa_restart_ctx *) rs_ctx ) );
691
692 }
693 #endif /* MBEDTLS_ECP_RESTARTABLE */
694
695 static void *ecdsa_alloc_wrap( void )
696 {
697     void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ecdsa_context ) );
698
699     if( ctx != NULL )
700         mbedtls_ecdsa_init( (mbedtls_ecdsa_context *) ctx );
701
702     return( ctx );
703 }
704
705 static void ecdsa_free_wrap( void *ctx )
706 {
707     mbedtls_ecdsa_free( (mbedtls_ecdsa_context *) ctx );
708     mbedtls_free( ctx );
709 }
710
711 #if defined(MBEDTLS_ECP_RESTARTABLE)
712 static void *ecdsa_rs_alloc( void )
713 {
714     void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ecdsa_restart_ctx ) );
715
716     if( ctx != NULL )
717         mbedtls_ecdsa_restart_init( ctx );
718
719     return( ctx );
720 }
721
722 static void ecdsa_rs_free( void *ctx )
723 {
724     mbedtls_ecdsa_restart_free( ctx );
725     mbedtls_free( ctx );
726 }
727 #endif /* MBEDTLS_ECP_RESTARTABLE */
728
729 const mbedtls_pk_info_t mbedtls_ecdsa_info = {
730     MBEDTLS_PK_ECDSA,
731     "ECDSA",
732     eckey_get_bitlen,     /* Compatible key structures */
733     ecdsa_can_do,
734     ecdsa_verify_wrap,
735     ecdsa_sign_wrap,
736 #if defined(MBEDTLS_ECP_RESTARTABLE)
737     ecdsa_verify_rs_wrap,
738     ecdsa_sign_rs_wrap,
739 #endif
740     NULL,
741     NULL,
742     eckey_check_pair,   /* Compatible key structures */
743     ecdsa_alloc_wrap,
744     ecdsa_free_wrap,
745 #if defined(MBEDTLS_ECP_RESTARTABLE)
746     ecdsa_rs_alloc,
747     ecdsa_rs_free,
748 #endif
749     eckey_debug,        /* Compatible key structures */
750 };
751 #endif /* MBEDTLS_ECDSA_C */
752
753 #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
754 /*
755  * Support for alternative RSA-private implementations
756  */
757
758 static int rsa_alt_can_do( mbedtls_pk_type_t type )
759 {
760     return( type == MBEDTLS_PK_RSA );
761 }
762
763 static size_t rsa_alt_get_bitlen( const void *ctx )
764 {
765     const mbedtls_rsa_alt_context *rsa_alt = (const mbedtls_rsa_alt_context *) ctx;
766
767     return( 8 * rsa_alt->key_len_func( rsa_alt->key ) );
768 }
769
770 static int rsa_alt_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,
771                    const unsigned char *hash, size_t hash_len,
772                    unsigned char *sig, size_t *sig_len,
773                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
774 {
775     mbedtls_rsa_alt_context *rsa_alt = (mbedtls_rsa_alt_context *) ctx;
776
777 #if SIZE_MAX > UINT_MAX
778     if( UINT_MAX < hash_len )
779         return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
780 #endif /* SIZE_MAX > UINT_MAX */
781
782     *sig_len = rsa_alt->key_len_func( rsa_alt->key );
783
784     return( rsa_alt->sign_func( rsa_alt->key, f_rng, p_rng, MBEDTLS_RSA_PRIVATE,
785                 md_alg, (unsigned int) hash_len, hash, sig ) );
786 }
787
788 static int rsa_alt_decrypt_wrap( void *ctx,
789                     const unsigned char *input, size_t ilen,
790                     unsigned char *output, size_t *olen, size_t osize,
791                     int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
792 {
793     mbedtls_rsa_alt_context *rsa_alt = (mbedtls_rsa_alt_context *) ctx;
794
795     ((void) f_rng);
796     ((void) p_rng);
797
798     if( ilen != rsa_alt->key_len_func( rsa_alt->key ) )
799         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
800
801     return( rsa_alt->decrypt_func( rsa_alt->key,
802                 MBEDTLS_RSA_PRIVATE, olen, input, output, osize ) );
803 }
804
805 #if defined(MBEDTLS_RSA_C)
806 static int rsa_alt_check_pair( const void *pub, const void *prv )
807 {
808     unsigned char sig[MBEDTLS_MPI_MAX_SIZE];
809     unsigned char hash[32];
810     size_t sig_len = 0;
811     int ret;
812
813     if( rsa_alt_get_bitlen( prv ) != rsa_get_bitlen( pub ) )
814         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
815
816     memset( hash, 0x2a, sizeof( hash ) );
817
818     if( ( ret = rsa_alt_sign_wrap( (void *) prv, MBEDTLS_MD_NONE,
819                                    hash, sizeof( hash ),
820                                    sig, &sig_len, NULL, NULL ) ) != 0 )
821     {
822         return( ret );
823     }
824
825     if( rsa_verify_wrap( (void *) pub, MBEDTLS_MD_NONE,
826                          hash, sizeof( hash ), sig, sig_len ) != 0 )
827     {
828         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
829     }
830
831     return( 0 );
832 }
833 #endif /* MBEDTLS_RSA_C */
834
835 static void *rsa_alt_alloc_wrap( void )
836 {
837     void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_rsa_alt_context ) );
838
839     if( ctx != NULL )
840         memset( ctx, 0, sizeof( mbedtls_rsa_alt_context ) );
841
842     return( ctx );
843 }
844
845 static void rsa_alt_free_wrap( void *ctx )
846 {
847     mbedtls_platform_zeroize( ctx, sizeof( mbedtls_rsa_alt_context ) );
848     mbedtls_free( ctx );
849 }
850
851 const mbedtls_pk_info_t mbedtls_rsa_alt_info = {
852     MBEDTLS_PK_RSA_ALT,
853     "RSA-alt",
854     rsa_alt_get_bitlen,
855     rsa_alt_can_do,
856     NULL,
857     rsa_alt_sign_wrap,
858 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
859     NULL,
860     NULL,
861 #endif
862     rsa_alt_decrypt_wrap,
863     NULL,
864 #if defined(MBEDTLS_RSA_C)
865     rsa_alt_check_pair,
866 #else
867     NULL,
868 #endif
869     rsa_alt_alloc_wrap,
870     rsa_alt_free_wrap,
871 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
872     NULL,
873     NULL,
874 #endif
875     NULL,
876 };
877
878 #endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */
879
880 #if defined(MBEDTLS_USE_PSA_CRYPTO)
881
882 static void *pk_opaque_alloc_wrap( void )
883 {
884     void *ctx = mbedtls_calloc( 1, sizeof( psa_key_handle_t ) );
885
886     /* no _init() function to call, an calloc() already zeroized */
887
888     return( ctx );
889 }
890
891 static void pk_opaque_free_wrap( void *ctx )
892 {
893     mbedtls_platform_zeroize( ctx, sizeof( psa_key_handle_t ) );
894     mbedtls_free( ctx );
895 }
896
897 static size_t pk_opaque_get_bitlen( const void *ctx )
898 {
899     const psa_key_handle_t *key = (const psa_key_handle_t *) ctx;
900     size_t bits;
901
902     if( PSA_SUCCESS != psa_get_key_information( *key, NULL, &bits ) )
903         return( 0 );
904
905     return( bits );
906 }
907
908 static int pk_opaque_can_do( mbedtls_pk_type_t type )
909 {
910     /* For now opaque PSA keys can only wrap ECC keypairs,
911      * as checked by setup_psa().
912      * Also, ECKEY_DH does not really make sense with the current API. */
913     return( type == MBEDTLS_PK_ECKEY ||
914             type == MBEDTLS_PK_ECDSA );
915 }
916
917 /*
918  * Simultaneously convert and move raw MPI from the beginning of a buffer
919  * to an ASN.1 MPI at the end of the buffer.
920  * See also mbedtls_asn1_write_mpi().
921  *
922  * p: pointer to the end of the output buffer
923  * start: start of the output buffer, and also of the mpi to write at the end
924  * n_len: length of the mpi to read from start
925  */
926 static int asn1_write_mpibuf( unsigned char **p, unsigned char *start,
927                               size_t n_len )
928 {
929     int ret;
930     size_t len = 0;
931
932     if( (size_t)( *p - start ) < n_len )
933         return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
934
935     len = n_len;
936     *p -= len;
937     memmove( *p, start, len );
938
939     /* ASN.1 DER encoding requires minimal length, so skip leading 0s.
940      * Neither r nor s should be 0, but as a failsafe measure, still detect
941      * that rather than overflowing the buffer in case of a PSA error. */
942     while( len > 0 && **p == 0x00 )
943     {
944         ++(*p);
945         --len;
946     }
947
948     /* this is only reached if the signature was invalid */
949     if( len == 0 )
950         return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED );
951
952     /* if the msb is 1, ASN.1 requires that we prepend a 0.
953      * Neither r nor s can be 0, so we can assume len > 0 at all times. */
954     if( **p & 0x80 )
955     {
956         if( *p - start < 1 )
957             return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
958
959         *--(*p) = 0x00;
960         len += 1;
961     }
962
963     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
964     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start,
965                                                 MBEDTLS_ASN1_INTEGER ) );
966
967     return( (int) len );
968 }
969
970 /* Transcode signature from PSA format to ASN.1 sequence.
971  * See ecdsa_signature_to_asn1 in ecdsa.c, but with byte buffers instead of
972  * MPIs, and in-place.
973  *
974  * [in/out] sig: the signature pre- and post-transcoding
975  * [in/out] sig_len: signature length pre- and post-transcoding
976  * [int] buf_len: the available size the in/out buffer
977  */
978 static int pk_ecdsa_sig_asn1_from_psa( unsigned char *sig, size_t *sig_len,
979                                        size_t buf_len )
980 {
981     int ret;
982     size_t len = 0;
983     const size_t rs_len = *sig_len / 2;
984     unsigned char *p = sig + buf_len;
985
986     MBEDTLS_ASN1_CHK_ADD( len, asn1_write_mpibuf( &p, sig + rs_len, rs_len ) );
987     MBEDTLS_ASN1_CHK_ADD( len, asn1_write_mpibuf( &p, sig, rs_len ) );
988
989     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &p, sig, len ) );
990     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &p, sig,
991                           MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) );
992
993     memmove( sig, p, len );
994     *sig_len = len;
995
996     return( 0 );
997 }
998
999 static int pk_opaque_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,
1000                    const unsigned char *hash, size_t hash_len,
1001                    unsigned char *sig, size_t *sig_len,
1002                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
1003 {
1004     const psa_key_handle_t *key = (const psa_key_handle_t *) ctx;
1005     psa_algorithm_t alg = PSA_ALG_ECDSA( mbedtls_psa_translate_md( md_alg ) );
1006     size_t bits, buf_len;
1007     psa_status_t status;
1008
1009     /* PSA has its own RNG */
1010     (void) f_rng;
1011     (void) p_rng;
1012
1013     /* PSA needs an output buffer of known size, but our API doesn't provide
1014      * that information. Assume that the buffer is large enough for a
1015      * maximal-length signature with that key (otherwise the application is
1016      * buggy anyway). */
1017     status = psa_get_key_information( *key, NULL, &bits );
1018     if( status != PSA_SUCCESS )
1019         return( mbedtls_psa_err_translate_pk( status ) );
1020
1021     buf_len = MBEDTLS_ECDSA_MAX_SIG_LEN( bits );
1022
1023     /* make the signature */
1024     status = psa_asymmetric_sign( *key, alg, hash, hash_len,
1025                                         sig, buf_len, sig_len );
1026     if( status != PSA_SUCCESS )
1027         return( mbedtls_psa_err_translate_pk( status ) );
1028
1029     /* transcode it to ASN.1 sequence */
1030     return( pk_ecdsa_sig_asn1_from_psa( sig, sig_len, buf_len ) );
1031 }
1032
1033 const mbedtls_pk_info_t mbedtls_pk_opaque_info = {
1034     MBEDTLS_PK_OPAQUE,
1035     "Opaque",
1036     pk_opaque_get_bitlen,
1037     pk_opaque_can_do,
1038     NULL, /* verify - will be done later */
1039     pk_opaque_sign_wrap,
1040 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
1041     NULL, /* restartable verify - not relevant */
1042     NULL, /* restartable sign - not relevant */
1043 #endif
1044     NULL, /* decrypt - will be done later */
1045     NULL, /* encrypt - will be done later */
1046     NULL, /* check_pair - could be done later or left NULL */
1047     pk_opaque_alloc_wrap,
1048     pk_opaque_free_wrap,
1049 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
1050     NULL, /* restart alloc - not relevant */
1051     NULL, /* restart free - not relevant */
1052 #endif
1053     NULL, /* debug - could be done later, or even left NULL */
1054 };
1055
1056 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1057
1058 #endif /* MBEDTLS_PK_C */