xref: /reactos/dll/3rdparty/mbedtls/pkparse.c (revision 019f21ee)
1 /*
2  *  Public Key layer for parsing key files and structures
3  *
4  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
5  *  SPDX-License-Identifier: GPL-2.0
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License along
18  *  with this program; if not, write to the Free Software Foundation, Inc.,
19  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  *  This file is part of mbed TLS (https://tls.mbed.org)
22  */
23 
24 #if !defined(MBEDTLS_CONFIG_FILE)
25 #include "mbedtls/config.h"
26 #else
27 #include MBEDTLS_CONFIG_FILE
28 #endif
29 
30 #if defined(MBEDTLS_PK_PARSE_C)
31 
32 #include "mbedtls/pk.h"
33 #include "mbedtls/asn1.h"
34 #include "mbedtls/oid.h"
35 
36 #include <string.h>
37 
38 #if defined(MBEDTLS_RSA_C)
39 #include "mbedtls/rsa.h"
40 #endif
41 #if defined(MBEDTLS_ECP_C)
42 #include "mbedtls/ecp.h"
43 #endif
44 #if defined(MBEDTLS_ECDSA_C)
45 #include "mbedtls/ecdsa.h"
46 #endif
47 #if defined(MBEDTLS_PEM_PARSE_C)
48 #include "mbedtls/pem.h"
49 #endif
50 #if defined(MBEDTLS_PKCS5_C)
51 #include "mbedtls/pkcs5.h"
52 #endif
53 #if defined(MBEDTLS_PKCS12_C)
54 #include "mbedtls/pkcs12.h"
55 #endif
56 
57 #if defined(MBEDTLS_PLATFORM_C)
58 #include "mbedtls/platform.h"
59 #else
60 #include <stdlib.h>
61 #define mbedtls_calloc    calloc
62 #define mbedtls_free       free
63 #endif
64 
65 #if defined(MBEDTLS_FS_IO) || \
66     defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
67 /* Implementation that should never be optimized out by the compiler */
68 static void mbedtls_zeroize( void *v, size_t n ) {
69     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
70 }
71 #endif
72 
73 #if defined(MBEDTLS_FS_IO)
74 /*
75  * Load all data from a file into a given buffer.
76  *
77  * The file is expected to contain either PEM or DER encoded data.
78  * A terminating null byte is always appended. It is included in the announced
79  * length only if the data looks like it is PEM encoded.
80  */
81 int mbedtls_pk_load_file( const char *path, unsigned char **buf, size_t *n )
82 {
83     FILE *f;
84     long size;
85 
86     if( ( f = fopen( path, "rb" ) ) == NULL )
87         return( MBEDTLS_ERR_PK_FILE_IO_ERROR );
88 
89     fseek( f, 0, SEEK_END );
90     if( ( size = ftell( f ) ) == -1 )
91     {
92         fclose( f );
93         return( MBEDTLS_ERR_PK_FILE_IO_ERROR );
94     }
95     fseek( f, 0, SEEK_SET );
96 
97     *n = (size_t) size;
98 
99     if( *n + 1 == 0 ||
100         ( *buf = mbedtls_calloc( 1, *n + 1 ) ) == NULL )
101     {
102         fclose( f );
103         return( MBEDTLS_ERR_PK_ALLOC_FAILED );
104     }
105 
106     if( fread( *buf, 1, *n, f ) != *n )
107     {
108         fclose( f );
109 
110         mbedtls_zeroize( *buf, *n );
111         mbedtls_free( *buf );
112 
113         return( MBEDTLS_ERR_PK_FILE_IO_ERROR );
114     }
115 
116     fclose( f );
117 
118     (*buf)[*n] = '\0';
119 
120     if( strstr( (const char *) *buf, "-----BEGIN " ) != NULL )
121         ++*n;
122 
123     return( 0 );
124 }
125 
126 /*
127  * Load and parse a private key
128  */
129 int mbedtls_pk_parse_keyfile( mbedtls_pk_context *ctx,
130                       const char *path, const char *pwd )
131 {
132     int ret;
133     size_t n;
134     unsigned char *buf;
135 
136     if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )
137         return( ret );
138 
139     if( pwd == NULL )
140         ret = mbedtls_pk_parse_key( ctx, buf, n, NULL, 0 );
141     else
142         ret = mbedtls_pk_parse_key( ctx, buf, n,
143                 (const unsigned char *) pwd, strlen( pwd ) );
144 
145     mbedtls_zeroize( buf, n );
146     mbedtls_free( buf );
147 
148     return( ret );
149 }
150 
151 /*
152  * Load and parse a public key
153  */
154 int mbedtls_pk_parse_public_keyfile( mbedtls_pk_context *ctx, const char *path )
155 {
156     int ret;
157     size_t n;
158     unsigned char *buf;
159 
160     if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )
161         return( ret );
162 
163     ret = mbedtls_pk_parse_public_key( ctx, buf, n );
164 
165     mbedtls_zeroize( buf, n );
166     mbedtls_free( buf );
167 
168     return( ret );
169 }
170 #endif /* MBEDTLS_FS_IO */
171 
172 #if defined(MBEDTLS_ECP_C)
173 /* Minimally parse an ECParameters buffer to and mbedtls_asn1_buf
174  *
175  * ECParameters ::= CHOICE {
176  *   namedCurve         OBJECT IDENTIFIER
177  *   specifiedCurve     SpecifiedECDomain -- = SEQUENCE { ... }
178  *   -- implicitCurve   NULL
179  * }
180  */
181 static int pk_get_ecparams( unsigned char **p, const unsigned char *end,
182                             mbedtls_asn1_buf *params )
183 {
184     int ret;
185 
186     if ( end - *p < 1 )
187         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +
188                 MBEDTLS_ERR_ASN1_OUT_OF_DATA );
189 
190     /* Tag may be either OID or SEQUENCE */
191     params->tag = **p;
192     if( params->tag != MBEDTLS_ASN1_OID
193 #if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
194             && params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE )
195 #endif
196             )
197     {
198         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +
199                 MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
200     }
201 
202     if( ( ret = mbedtls_asn1_get_tag( p, end, &params->len, params->tag ) ) != 0 )
203     {
204         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
205     }
206 
207     params->p = *p;
208     *p += params->len;
209 
210     if( *p != end )
211         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +
212                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
213 
214     return( 0 );
215 }
216 
217 #if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
218 /*
219  * Parse a SpecifiedECDomain (SEC 1 C.2) and (mostly) fill the group with it.
220  * WARNING: the resulting group should only be used with
221  * pk_group_id_from_specified(), since its base point may not be set correctly
222  * if it was encoded compressed.
223  *
224  *  SpecifiedECDomain ::= SEQUENCE {
225  *      version SpecifiedECDomainVersion(ecdpVer1 | ecdpVer2 | ecdpVer3, ...),
226  *      fieldID FieldID {{FieldTypes}},
227  *      curve Curve,
228  *      base ECPoint,
229  *      order INTEGER,
230  *      cofactor INTEGER OPTIONAL,
231  *      hash HashAlgorithm OPTIONAL,
232  *      ...
233  *  }
234  *
235  * We only support prime-field as field type, and ignore hash and cofactor.
236  */
237 static int pk_group_from_specified( const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp )
238 {
239     int ret;
240     unsigned char *p = params->p;
241     const unsigned char * const end = params->p + params->len;
242     const unsigned char *end_field, *end_curve;
243     size_t len;
244     int ver;
245 
246     /* SpecifiedECDomainVersion ::= INTEGER { 1, 2, 3 } */
247     if( ( ret = mbedtls_asn1_get_int( &p, end, &ver ) ) != 0 )
248         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
249 
250     if( ver < 1 || ver > 3 )
251         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
252 
253     /*
254      * FieldID { FIELD-ID:IOSet } ::= SEQUENCE { -- Finite field
255      *       fieldType FIELD-ID.&id({IOSet}),
256      *       parameters FIELD-ID.&Type({IOSet}{@fieldType})
257      * }
258      */
259     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
260             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
261         return( ret );
262 
263     end_field = p + len;
264 
265     /*
266      * FIELD-ID ::= TYPE-IDENTIFIER
267      * FieldTypes FIELD-ID ::= {
268      *       { Prime-p IDENTIFIED BY prime-field } |
269      *       { Characteristic-two IDENTIFIED BY characteristic-two-field }
270      * }
271      * prime-field OBJECT IDENTIFIER ::= { id-fieldType 1 }
272      */
273     if( ( ret = mbedtls_asn1_get_tag( &p, end_field, &len, MBEDTLS_ASN1_OID ) ) != 0 )
274         return( ret );
275 
276     if( len != MBEDTLS_OID_SIZE( MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD ) ||
277         memcmp( p, MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD, len ) != 0 )
278     {
279         return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
280     }
281 
282     p += len;
283 
284     /* Prime-p ::= INTEGER -- Field of size p. */
285     if( ( ret = mbedtls_asn1_get_mpi( &p, end_field, &grp->P ) ) != 0 )
286         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
287 
288     grp->pbits = mbedtls_mpi_bitlen( &grp->P );
289 
290     if( p != end_field )
291         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +
292                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
293 
294     /*
295      * Curve ::= SEQUENCE {
296      *       a FieldElement,
297      *       b FieldElement,
298      *       seed BIT STRING OPTIONAL
299      *       -- Shall be present if used in SpecifiedECDomain
300      *       -- with version equal to ecdpVer2 or ecdpVer3
301      * }
302      */
303     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
304             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
305         return( ret );
306 
307     end_curve = p + len;
308 
309     /*
310      * FieldElement ::= OCTET STRING
311      * containing an integer in the case of a prime field
312      */
313     if( ( ret = mbedtls_asn1_get_tag( &p, end_curve, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ||
314         ( ret = mbedtls_mpi_read_binary( &grp->A, p, len ) ) != 0 )
315     {
316         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
317     }
318 
319     p += len;
320 
321     if( ( ret = mbedtls_asn1_get_tag( &p, end_curve, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ||
322         ( ret = mbedtls_mpi_read_binary( &grp->B, p, len ) ) != 0 )
323     {
324         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
325     }
326 
327     p += len;
328 
329     /* Ignore seed BIT STRING OPTIONAL */
330     if( ( ret = mbedtls_asn1_get_tag( &p, end_curve, &len, MBEDTLS_ASN1_BIT_STRING ) ) == 0 )
331         p += len;
332 
333     if( p != end_curve )
334         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +
335                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
336 
337     /*
338      * ECPoint ::= OCTET STRING
339      */
340     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
341         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
342 
343     if( ( ret = mbedtls_ecp_point_read_binary( grp, &grp->G,
344                                       ( const unsigned char *) p, len ) ) != 0 )
345     {
346         /*
347          * If we can't read the point because it's compressed, cheat by
348          * reading only the X coordinate and the parity bit of Y.
349          */
350         if( ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ||
351             ( p[0] != 0x02 && p[0] != 0x03 ) ||
352             len != mbedtls_mpi_size( &grp->P ) + 1 ||
353             mbedtls_mpi_read_binary( &grp->G.X, p + 1, len - 1 ) != 0 ||
354             mbedtls_mpi_lset( &grp->G.Y, p[0] - 2 ) != 0 ||
355             mbedtls_mpi_lset( &grp->G.Z, 1 ) != 0 )
356         {
357             return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
358         }
359     }
360 
361     p += len;
362 
363     /*
364      * order INTEGER
365      */
366     if( ( ret = mbedtls_asn1_get_mpi( &p, end, &grp->N ) ) != 0 )
367         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
368 
369     grp->nbits = mbedtls_mpi_bitlen( &grp->N );
370 
371     /*
372      * Allow optional elements by purposefully not enforcing p == end here.
373      */
374 
375     return( 0 );
376 }
377 
378 /*
379  * Find the group id associated with an (almost filled) group as generated by
380  * pk_group_from_specified(), or return an error if unknown.
381  */
382 static int pk_group_id_from_group( const mbedtls_ecp_group *grp, mbedtls_ecp_group_id *grp_id )
383 {
384     int ret = 0;
385     mbedtls_ecp_group ref;
386     const mbedtls_ecp_group_id *id;
387 
388     mbedtls_ecp_group_init( &ref );
389 
390     for( id = mbedtls_ecp_grp_id_list(); *id != MBEDTLS_ECP_DP_NONE; id++ )
391     {
392         /* Load the group associated to that id */
393         mbedtls_ecp_group_free( &ref );
394         MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &ref, *id ) );
395 
396         /* Compare to the group we were given, starting with easy tests */
397         if( grp->pbits == ref.pbits && grp->nbits == ref.nbits &&
398             mbedtls_mpi_cmp_mpi( &grp->P, &ref.P ) == 0 &&
399             mbedtls_mpi_cmp_mpi( &grp->A, &ref.A ) == 0 &&
400             mbedtls_mpi_cmp_mpi( &grp->B, &ref.B ) == 0 &&
401             mbedtls_mpi_cmp_mpi( &grp->N, &ref.N ) == 0 &&
402             mbedtls_mpi_cmp_mpi( &grp->G.X, &ref.G.X ) == 0 &&
403             mbedtls_mpi_cmp_mpi( &grp->G.Z, &ref.G.Z ) == 0 &&
404             /* For Y we may only know the parity bit, so compare only that */
405             mbedtls_mpi_get_bit( &grp->G.Y, 0 ) == mbedtls_mpi_get_bit( &ref.G.Y, 0 ) )
406         {
407             break;
408         }
409 
410     }
411 
412 cleanup:
413     mbedtls_ecp_group_free( &ref );
414 
415     *grp_id = *id;
416 
417     if( ret == 0 && *id == MBEDTLS_ECP_DP_NONE )
418         ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
419 
420     return( ret );
421 }
422 
423 /*
424  * Parse a SpecifiedECDomain (SEC 1 C.2) and find the associated group ID
425  */
426 static int pk_group_id_from_specified( const mbedtls_asn1_buf *params,
427                                        mbedtls_ecp_group_id *grp_id )
428 {
429     int ret;
430     mbedtls_ecp_group grp;
431 
432     mbedtls_ecp_group_init( &grp );
433 
434     if( ( ret = pk_group_from_specified( params, &grp ) ) != 0 )
435         goto cleanup;
436 
437     ret = pk_group_id_from_group( &grp, grp_id );
438 
439 cleanup:
440     mbedtls_ecp_group_free( &grp );
441 
442     return( ret );
443 }
444 #endif /* MBEDTLS_PK_PARSE_EC_EXTENDED */
445 
446 /*
447  * Use EC parameters to initialise an EC group
448  *
449  * ECParameters ::= CHOICE {
450  *   namedCurve         OBJECT IDENTIFIER
451  *   specifiedCurve     SpecifiedECDomain -- = SEQUENCE { ... }
452  *   -- implicitCurve   NULL
453  */
454 static int pk_use_ecparams( const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp )
455 {
456     int ret;
457     mbedtls_ecp_group_id grp_id;
458 
459     if( params->tag == MBEDTLS_ASN1_OID )
460     {
461         if( mbedtls_oid_get_ec_grp( params, &grp_id ) != 0 )
462             return( MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE );
463     }
464     else
465     {
466 #if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
467         if( ( ret = pk_group_id_from_specified( params, &grp_id ) ) != 0 )
468             return( ret );
469 #else
470         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
471 #endif
472     }
473 
474     /*
475      * grp may already be initilialized; if so, make sure IDs match
476      */
477     if( grp->id != MBEDTLS_ECP_DP_NONE && grp->id != grp_id )
478         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
479 
480     if( ( ret = mbedtls_ecp_group_load( grp, grp_id ) ) != 0 )
481         return( ret );
482 
483     return( 0 );
484 }
485 
486 /*
487  * EC public key is an EC point
488  *
489  * The caller is responsible for clearing the structure upon failure if
490  * desired. Take care to pass along the possible ECP_FEATURE_UNAVAILABLE
491  * return code of mbedtls_ecp_point_read_binary() and leave p in a usable state.
492  */
493 static int pk_get_ecpubkey( unsigned char **p, const unsigned char *end,
494                             mbedtls_ecp_keypair *key )
495 {
496     int ret;
497 
498     if( ( ret = mbedtls_ecp_point_read_binary( &key->grp, &key->Q,
499                     (const unsigned char *) *p, end - *p ) ) == 0 )
500     {
501         ret = mbedtls_ecp_check_pubkey( &key->grp, &key->Q );
502     }
503 
504     /*
505      * We know mbedtls_ecp_point_read_binary consumed all bytes or failed
506      */
507     *p = (unsigned char *) end;
508 
509     return( ret );
510 }
511 #endif /* MBEDTLS_ECP_C */
512 
513 #if defined(MBEDTLS_RSA_C)
514 /*
515  *  RSAPublicKey ::= SEQUENCE {
516  *      modulus           INTEGER,  -- n
517  *      publicExponent    INTEGER   -- e
518  *  }
519  */
520 static int pk_get_rsapubkey( unsigned char **p,
521                              const unsigned char *end,
522                              mbedtls_rsa_context *rsa )
523 {
524     int ret;
525     size_t len;
526 
527     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
528             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
529         return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret );
530 
531     if( *p + len != end )
532         return( MBEDTLS_ERR_PK_INVALID_PUBKEY +
533                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
534 
535     /* Import N */
536     if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 )
537         return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret );
538 
539     if( ( ret = mbedtls_rsa_import_raw( rsa, *p, len, NULL, 0, NULL, 0,
540                                         NULL, 0, NULL, 0 ) ) != 0 )
541         return( MBEDTLS_ERR_PK_INVALID_PUBKEY );
542 
543     *p += len;
544 
545     /* Import E */
546     if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 )
547         return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret );
548 
549     if( ( ret = mbedtls_rsa_import_raw( rsa, NULL, 0, NULL, 0, NULL, 0,
550                                         NULL, 0, *p, len ) ) != 0 )
551         return( MBEDTLS_ERR_PK_INVALID_PUBKEY );
552 
553     *p += len;
554 
555     if( mbedtls_rsa_complete( rsa ) != 0 ||
556         mbedtls_rsa_check_pubkey( rsa ) != 0 )
557     {
558         return( MBEDTLS_ERR_PK_INVALID_PUBKEY );
559     }
560 
561     if( *p != end )
562         return( MBEDTLS_ERR_PK_INVALID_PUBKEY +
563                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
564 
565     return( 0 );
566 }
567 #endif /* MBEDTLS_RSA_C */
568 
569 /* Get a PK algorithm identifier
570  *
571  *  AlgorithmIdentifier  ::=  SEQUENCE  {
572  *       algorithm               OBJECT IDENTIFIER,
573  *       parameters              ANY DEFINED BY algorithm OPTIONAL  }
574  */
575 static int pk_get_pk_alg( unsigned char **p,
576                           const unsigned char *end,
577                           mbedtls_pk_type_t *pk_alg, mbedtls_asn1_buf *params )
578 {
579     int ret;
580     mbedtls_asn1_buf alg_oid;
581 
582     memset( params, 0, sizeof(mbedtls_asn1_buf) );
583 
584     if( ( ret = mbedtls_asn1_get_alg( p, end, &alg_oid, params ) ) != 0 )
585         return( MBEDTLS_ERR_PK_INVALID_ALG + ret );
586 
587     if( mbedtls_oid_get_pk_alg( &alg_oid, pk_alg ) != 0 )
588         return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );
589 
590     /*
591      * No parameters with RSA (only for EC)
592      */
593     if( *pk_alg == MBEDTLS_PK_RSA &&
594             ( ( params->tag != MBEDTLS_ASN1_NULL && params->tag != 0 ) ||
595                 params->len != 0 ) )
596     {
597         return( MBEDTLS_ERR_PK_INVALID_ALG );
598     }
599 
600     return( 0 );
601 }
602 
603 /*
604  *  SubjectPublicKeyInfo  ::=  SEQUENCE  {
605  *       algorithm            AlgorithmIdentifier,
606  *       subjectPublicKey     BIT STRING }
607  */
608 int mbedtls_pk_parse_subpubkey( unsigned char **p, const unsigned char *end,
609                         mbedtls_pk_context *pk )
610 {
611     int ret;
612     size_t len;
613     mbedtls_asn1_buf alg_params;
614     mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
615     const mbedtls_pk_info_t *pk_info;
616 
617     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
618                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
619     {
620         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
621     }
622 
623     end = *p + len;
624 
625     if( ( ret = pk_get_pk_alg( p, end, &pk_alg, &alg_params ) ) != 0 )
626         return( ret );
627 
628     if( ( ret = mbedtls_asn1_get_bitstring_null( p, end, &len ) ) != 0 )
629         return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret );
630 
631     if( *p + len != end )
632         return( MBEDTLS_ERR_PK_INVALID_PUBKEY +
633                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
634 
635     if( ( pk_info = mbedtls_pk_info_from_type( pk_alg ) ) == NULL )
636         return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );
637 
638     if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 )
639         return( ret );
640 
641 #if defined(MBEDTLS_RSA_C)
642     if( pk_alg == MBEDTLS_PK_RSA )
643     {
644         ret = pk_get_rsapubkey( p, end, mbedtls_pk_rsa( *pk ) );
645     } else
646 #endif /* MBEDTLS_RSA_C */
647 #if defined(MBEDTLS_ECP_C)
648     if( pk_alg == MBEDTLS_PK_ECKEY_DH || pk_alg == MBEDTLS_PK_ECKEY )
649     {
650         ret = pk_use_ecparams( &alg_params, &mbedtls_pk_ec( *pk )->grp );
651         if( ret == 0 )
652             ret = pk_get_ecpubkey( p, end, mbedtls_pk_ec( *pk ) );
653     } else
654 #endif /* MBEDTLS_ECP_C */
655         ret = MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
656 
657     if( ret == 0 && *p != end )
658         ret = MBEDTLS_ERR_PK_INVALID_PUBKEY
659               MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
660 
661     if( ret != 0 )
662         mbedtls_pk_free( pk );
663 
664     return( ret );
665 }
666 
667 #if defined(MBEDTLS_RSA_C)
668 /*
669  * Wrapper around mbedtls_asn1_get_mpi() that rejects zero.
670  *
671  * The value zero is:
672  * - never a valid value for an RSA parameter
673  * - interpreted as "omitted, please reconstruct" by mbedtls_rsa_complete().
674  *
675  * Since values can't be omitted in PKCS#1, passing a zero value to
676  * rsa_complete() would be incorrect, so reject zero values early.
677  */
678 static int asn1_get_nonzero_mpi( unsigned char **p,
679                                  const unsigned char *end,
680                                  mbedtls_mpi *X )
681 {
682     int ret;
683 
684     ret = mbedtls_asn1_get_mpi( p, end, X );
685     if( ret != 0 )
686         return( ret );
687 
688     if( mbedtls_mpi_cmp_int( X, 0 ) == 0 )
689         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
690 
691     return( 0 );
692 }
693 
694 /*
695  * Parse a PKCS#1 encoded private RSA key
696  */
697 static int pk_parse_key_pkcs1_der( mbedtls_rsa_context *rsa,
698                                    const unsigned char *key,
699                                    size_t keylen )
700 {
701     int ret, version;
702     size_t len;
703     unsigned char *p, *end;
704 
705     mbedtls_mpi T;
706     mbedtls_mpi_init( &T );
707 
708     p = (unsigned char *) key;
709     end = p + keylen;
710 
711     /*
712      * This function parses the RSAPrivateKey (PKCS#1)
713      *
714      *  RSAPrivateKey ::= SEQUENCE {
715      *      version           Version,
716      *      modulus           INTEGER,  -- n
717      *      publicExponent    INTEGER,  -- e
718      *      privateExponent   INTEGER,  -- d
719      *      prime1            INTEGER,  -- p
720      *      prime2            INTEGER,  -- q
721      *      exponent1         INTEGER,  -- d mod (p-1)
722      *      exponent2         INTEGER,  -- d mod (q-1)
723      *      coefficient       INTEGER,  -- (inverse of q) mod p
724      *      otherPrimeInfos   OtherPrimeInfos OPTIONAL
725      *  }
726      */
727     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
728             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
729     {
730         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
731     }
732 
733     end = p + len;
734 
735     if( ( ret = mbedtls_asn1_get_int( &p, end, &version ) ) != 0 )
736     {
737         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
738     }
739 
740     if( version != 0 )
741     {
742         return( MBEDTLS_ERR_PK_KEY_INVALID_VERSION );
743     }
744 
745     /* Import N */
746     if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
747         ( ret = mbedtls_rsa_import( rsa, &T, NULL, NULL,
748                                         NULL, NULL ) ) != 0 )
749         goto cleanup;
750 
751     /* Import E */
752     if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
753         ( ret = mbedtls_rsa_import( rsa, NULL, NULL, NULL,
754                                         NULL, &T ) ) != 0 )
755         goto cleanup;
756 
757     /* Import D */
758     if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
759         ( ret = mbedtls_rsa_import( rsa, NULL, NULL, NULL,
760                                         &T, NULL ) ) != 0 )
761         goto cleanup;
762 
763     /* Import P */
764     if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
765         ( ret = mbedtls_rsa_import( rsa, NULL, &T, NULL,
766                                         NULL, NULL ) ) != 0 )
767         goto cleanup;
768 
769     /* Import Q */
770     if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
771         ( ret = mbedtls_rsa_import( rsa, NULL, NULL, &T,
772                                         NULL, NULL ) ) != 0 )
773         goto cleanup;
774 
775 #if !defined(MBEDTLS_RSA_NO_CRT) && !defined(MBEDTLS_RSA_ALT)
776     /*
777     * The RSA CRT parameters DP, DQ and QP are nominally redundant, in
778     * that they can be easily recomputed from D, P and Q. However by
779     * parsing them from the PKCS1 structure it is possible to avoid
780     * recalculating them which both reduces the overhead of loading
781     * RSA private keys into memory and also avoids side channels which
782     * can arise when computing those values, since all of D, P, and Q
783     * are secret. See https://eprint.iacr.org/2020/055 for a
784     * description of one such attack.
785     */
786 
787     /* Import DP */
788     if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
789         ( ret = mbedtls_mpi_copy( &rsa->DP, &T ) ) != 0 )
790        goto cleanup;
791 
792     /* Import DQ */
793     if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
794         ( ret = mbedtls_mpi_copy( &rsa->DQ, &T ) ) != 0 )
795        goto cleanup;
796 
797     /* Import QP */
798     if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
799         ( ret = mbedtls_mpi_copy( &rsa->QP, &T ) ) != 0 )
800        goto cleanup;
801 
802 #else
803     /* Verify existance of the CRT params */
804     if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
805         ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
806         ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 )
807        goto cleanup;
808 #endif
809 
810     /* rsa_complete() doesn't complete anything with the default
811      * implementation but is still called:
812      * - for the benefit of alternative implementation that may want to
813      *   pre-compute stuff beyond what's provided (eg Montgomery factors)
814      * - as is also sanity-checks the key
815      *
816      * Furthermore, we also check the public part for consistency with
817      * mbedtls_pk_parse_pubkey(), as it includes size minima for example.
818      */
819     if( ( ret = mbedtls_rsa_complete( rsa ) ) != 0 ||
820         ( ret = mbedtls_rsa_check_pubkey( rsa ) ) != 0 )
821     {
822         goto cleanup;
823     }
824 
825     if( p != end )
826     {
827         ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +
828               MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ;
829     }
830 
831 cleanup:
832 
833     mbedtls_mpi_free( &T );
834 
835     if( ret != 0 )
836     {
837         /* Wrap error code if it's coming from a lower level */
838         if( ( ret & 0xff80 ) == 0 )
839             ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret;
840         else
841             ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
842 
843         mbedtls_rsa_free( rsa );
844     }
845 
846     return( ret );
847 }
848 #endif /* MBEDTLS_RSA_C */
849 
850 #if defined(MBEDTLS_ECP_C)
851 /*
852  * Parse a SEC1 encoded private EC key
853  */
854 static int pk_parse_key_sec1_der( mbedtls_ecp_keypair *eck,
855                                   const unsigned char *key,
856                                   size_t keylen )
857 {
858     int ret;
859     int version, pubkey_done;
860     size_t len;
861     mbedtls_asn1_buf params;
862     unsigned char *p = (unsigned char *) key;
863     unsigned char *end = p + keylen;
864     unsigned char *end2;
865 
866     /*
867      * RFC 5915, or SEC1 Appendix C.4
868      *
869      * ECPrivateKey ::= SEQUENCE {
870      *      version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
871      *      privateKey     OCTET STRING,
872      *      parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
873      *      publicKey  [1] BIT STRING OPTIONAL
874      *    }
875      */
876     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
877             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
878     {
879         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
880     }
881 
882     end = p + len;
883 
884     if( ( ret = mbedtls_asn1_get_int( &p, end, &version ) ) != 0 )
885         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
886 
887     if( version != 1 )
888         return( MBEDTLS_ERR_PK_KEY_INVALID_VERSION );
889 
890     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
891         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
892 
893     if( ( ret = mbedtls_mpi_read_binary( &eck->d, p, len ) ) != 0 )
894     {
895         mbedtls_ecp_keypair_free( eck );
896         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
897     }
898 
899     p += len;
900 
901     pubkey_done = 0;
902     if( p != end )
903     {
904         /*
905          * Is 'parameters' present?
906          */
907         if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
908                         MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) == 0 )
909         {
910             if( ( ret = pk_get_ecparams( &p, p + len, &params) ) != 0 ||
911                 ( ret = pk_use_ecparams( &params, &eck->grp )  ) != 0 )
912             {
913                 mbedtls_ecp_keypair_free( eck );
914                 return( ret );
915             }
916         }
917         else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
918         {
919             mbedtls_ecp_keypair_free( eck );
920             return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
921         }
922     }
923 
924     if( p != end )
925     {
926         /*
927          * Is 'publickey' present? If not, or if we can't read it (eg because it
928          * is compressed), create it from the private key.
929          */
930         if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
931                         MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 1 ) ) == 0 )
932         {
933             end2 = p + len;
934 
935             if( ( ret = mbedtls_asn1_get_bitstring_null( &p, end2, &len ) ) != 0 )
936                 return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
937 
938             if( p + len != end2 )
939                 return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +
940                         MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
941 
942             if( ( ret = pk_get_ecpubkey( &p, end2, eck ) ) == 0 )
943                 pubkey_done = 1;
944             else
945             {
946                 /*
947                  * The only acceptable failure mode of pk_get_ecpubkey() above
948                  * is if the point format is not recognized.
949                  */
950                 if( ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE )
951                     return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
952             }
953         }
954         else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
955         {
956             mbedtls_ecp_keypair_free( eck );
957             return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
958         }
959     }
960 
961     if( ! pubkey_done &&
962         ( ret = mbedtls_ecp_mul( &eck->grp, &eck->Q, &eck->d, &eck->grp.G,
963                                                       NULL, NULL ) ) != 0 )
964     {
965         mbedtls_ecp_keypair_free( eck );
966         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
967     }
968 
969     if( ( ret = mbedtls_ecp_check_privkey( &eck->grp, &eck->d ) ) != 0 )
970     {
971         mbedtls_ecp_keypair_free( eck );
972         return( ret );
973     }
974 
975     return( 0 );
976 }
977 #endif /* MBEDTLS_ECP_C */
978 
979 /*
980  * Parse an unencrypted PKCS#8 encoded private key
981  *
982  * Notes:
983  *
984  * - This function does not own the key buffer. It is the
985  *   responsibility of the caller to take care of zeroizing
986  *   and freeing it after use.
987  *
988  * - The function is responsible for freeing the provided
989  *   PK context on failure.
990  *
991  */
992 static int pk_parse_key_pkcs8_unencrypted_der(
993                                     mbedtls_pk_context *pk,
994                                     const unsigned char* key,
995                                     size_t keylen )
996 {
997     int ret, version;
998     size_t len;
999     mbedtls_asn1_buf params;
1000     unsigned char *p = (unsigned char *) key;
1001     unsigned char *end = p + keylen;
1002     mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
1003     const mbedtls_pk_info_t *pk_info;
1004 
1005     /*
1006      * This function parses the PrivateKeyInfo object (PKCS#8 v1.2 = RFC 5208)
1007      *
1008      *    PrivateKeyInfo ::= SEQUENCE {
1009      *      version                   Version,
1010      *      privateKeyAlgorithm       PrivateKeyAlgorithmIdentifier,
1011      *      privateKey                PrivateKey,
1012      *      attributes           [0]  IMPLICIT Attributes OPTIONAL }
1013      *
1014      *    Version ::= INTEGER
1015      *    PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
1016      *    PrivateKey ::= OCTET STRING
1017      *
1018      *  The PrivateKey OCTET STRING is a SEC1 ECPrivateKey
1019      */
1020 
1021     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
1022             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
1023     {
1024         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
1025     }
1026 
1027     end = p + len;
1028 
1029     if( ( ret = mbedtls_asn1_get_int( &p, end, &version ) ) != 0 )
1030         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
1031 
1032     if( version != 0 )
1033         return( MBEDTLS_ERR_PK_KEY_INVALID_VERSION + ret );
1034 
1035     if( ( ret = pk_get_pk_alg( &p, end, &pk_alg, &params ) ) != 0 )
1036         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
1037 
1038     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
1039         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
1040 
1041     if( len < 1 )
1042         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +
1043                 MBEDTLS_ERR_ASN1_OUT_OF_DATA );
1044 
1045     if( ( pk_info = mbedtls_pk_info_from_type( pk_alg ) ) == NULL )
1046         return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );
1047 
1048     if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 )
1049         return( ret );
1050 
1051 #if defined(MBEDTLS_RSA_C)
1052     if( pk_alg == MBEDTLS_PK_RSA )
1053     {
1054         if( ( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ), p, len ) ) != 0 )
1055         {
1056             mbedtls_pk_free( pk );
1057             return( ret );
1058         }
1059     } else
1060 #endif /* MBEDTLS_RSA_C */
1061 #if defined(MBEDTLS_ECP_C)
1062     if( pk_alg == MBEDTLS_PK_ECKEY || pk_alg == MBEDTLS_PK_ECKEY_DH )
1063     {
1064         if( ( ret = pk_use_ecparams( &params, &mbedtls_pk_ec( *pk )->grp ) ) != 0 ||
1065             ( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ), p, len )  ) != 0 )
1066         {
1067             mbedtls_pk_free( pk );
1068             return( ret );
1069         }
1070     } else
1071 #endif /* MBEDTLS_ECP_C */
1072         return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );
1073 
1074     return( 0 );
1075 }
1076 
1077 /*
1078  * Parse an encrypted PKCS#8 encoded private key
1079  *
1080  * To save space, the decryption happens in-place on the given key buffer.
1081  * Also, while this function may modify the keybuffer, it doesn't own it,
1082  * and instead it is the responsibility of the caller to zeroize and properly
1083  * free it after use.
1084  *
1085  */
1086 #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
1087 static int pk_parse_key_pkcs8_encrypted_der(
1088                                     mbedtls_pk_context *pk,
1089                                     unsigned char *key, size_t keylen,
1090                                     const unsigned char *pwd, size_t pwdlen )
1091 {
1092     int ret, decrypted = 0;
1093     size_t len;
1094     unsigned char *buf;
1095     unsigned char *p, *end;
1096     mbedtls_asn1_buf pbe_alg_oid, pbe_params;
1097 #if defined(MBEDTLS_PKCS12_C)
1098     mbedtls_cipher_type_t cipher_alg;
1099     mbedtls_md_type_t md_alg;
1100 #endif
1101 
1102     p = key;
1103     end = p + keylen;
1104 
1105     if( pwdlen == 0 )
1106         return( MBEDTLS_ERR_PK_PASSWORD_REQUIRED );
1107 
1108     /*
1109      * This function parses the EncryptedPrivateKeyInfo object (PKCS#8)
1110      *
1111      *  EncryptedPrivateKeyInfo ::= SEQUENCE {
1112      *    encryptionAlgorithm  EncryptionAlgorithmIdentifier,
1113      *    encryptedData        EncryptedData
1114      *  }
1115      *
1116      *  EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
1117      *
1118      *  EncryptedData ::= OCTET STRING
1119      *
1120      *  The EncryptedData OCTET STRING is a PKCS#8 PrivateKeyInfo
1121      *
1122      */
1123     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
1124             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
1125     {
1126         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
1127     }
1128 
1129     end = p + len;
1130 
1131     if( ( ret = mbedtls_asn1_get_alg( &p, end, &pbe_alg_oid, &pbe_params ) ) != 0 )
1132         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
1133 
1134     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
1135         return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
1136 
1137     buf = p;
1138 
1139     /*
1140      * Decrypt EncryptedData with appropriate PBE
1141      */
1142 #if defined(MBEDTLS_PKCS12_C)
1143     if( mbedtls_oid_get_pkcs12_pbe_alg( &pbe_alg_oid, &md_alg, &cipher_alg ) == 0 )
1144     {
1145         if( ( ret = mbedtls_pkcs12_pbe( &pbe_params, MBEDTLS_PKCS12_PBE_DECRYPT,
1146                                 cipher_alg, md_alg,
1147                                 pwd, pwdlen, p, len, buf ) ) != 0 )
1148         {
1149             if( ret == MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH )
1150                 return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );
1151 
1152             return( ret );
1153         }
1154 
1155         decrypted = 1;
1156     }
1157     else if( MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_128, &pbe_alg_oid ) == 0 )
1158     {
1159         if( ( ret = mbedtls_pkcs12_pbe_sha1_rc4_128( &pbe_params,
1160                                              MBEDTLS_PKCS12_PBE_DECRYPT,
1161                                              pwd, pwdlen,
1162                                              p, len, buf ) ) != 0 )
1163         {
1164             return( ret );
1165         }
1166 
1167         // Best guess for password mismatch when using RC4. If first tag is
1168         // not MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE
1169         //
1170         if( *buf != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )
1171             return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );
1172 
1173         decrypted = 1;
1174     }
1175     else
1176 #endif /* MBEDTLS_PKCS12_C */
1177 #if defined(MBEDTLS_PKCS5_C)
1178     if( MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS5_PBES2, &pbe_alg_oid ) == 0 )
1179     {
1180         if( ( ret = mbedtls_pkcs5_pbes2( &pbe_params, MBEDTLS_PKCS5_DECRYPT, pwd, pwdlen,
1181                                   p, len, buf ) ) != 0 )
1182         {
1183             if( ret == MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH )
1184                 return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );
1185 
1186             return( ret );
1187         }
1188 
1189         decrypted = 1;
1190     }
1191     else
1192 #endif /* MBEDTLS_PKCS5_C */
1193     {
1194         ((void) pwd);
1195     }
1196 
1197     if( decrypted == 0 )
1198         return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
1199 
1200     return( pk_parse_key_pkcs8_unencrypted_der( pk, buf, len ) );
1201 }
1202 #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
1203 
1204 /*
1205  * Parse a private key
1206  */
1207 int mbedtls_pk_parse_key( mbedtls_pk_context *pk,
1208                   const unsigned char *key, size_t keylen,
1209                   const unsigned char *pwd, size_t pwdlen )
1210 {
1211     int ret;
1212     const mbedtls_pk_info_t *pk_info;
1213 
1214 #if defined(MBEDTLS_PEM_PARSE_C)
1215     size_t len;
1216     mbedtls_pem_context pem;
1217 
1218     mbedtls_pem_init( &pem );
1219 
1220 #if defined(MBEDTLS_RSA_C)
1221     /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1222     if( keylen == 0 || key[keylen - 1] != '\0' )
1223         ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1224     else
1225         ret = mbedtls_pem_read_buffer( &pem,
1226                                "-----BEGIN RSA PRIVATE KEY-----",
1227                                "-----END RSA PRIVATE KEY-----",
1228                                key, pwd, pwdlen, &len );
1229 
1230     if( ret == 0 )
1231     {
1232         pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA );
1233         if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||
1234             ( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ),
1235                                             pem.buf, pem.buflen ) ) != 0 )
1236         {
1237             mbedtls_pk_free( pk );
1238         }
1239 
1240         mbedtls_pem_free( &pem );
1241         return( ret );
1242     }
1243     else if( ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH )
1244         return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );
1245     else if( ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED )
1246         return( MBEDTLS_ERR_PK_PASSWORD_REQUIRED );
1247     else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
1248         return( ret );
1249 #endif /* MBEDTLS_RSA_C */
1250 
1251 #if defined(MBEDTLS_ECP_C)
1252     /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1253     if( keylen == 0 || key[keylen - 1] != '\0' )
1254         ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1255     else
1256         ret = mbedtls_pem_read_buffer( &pem,
1257                                "-----BEGIN EC PRIVATE KEY-----",
1258                                "-----END EC PRIVATE KEY-----",
1259                                key, pwd, pwdlen, &len );
1260     if( ret == 0 )
1261     {
1262         pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY );
1263 
1264         if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||
1265             ( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ),
1266                                            pem.buf, pem.buflen ) ) != 0 )
1267         {
1268             mbedtls_pk_free( pk );
1269         }
1270 
1271         mbedtls_pem_free( &pem );
1272         return( ret );
1273     }
1274     else if( ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH )
1275         return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );
1276     else if( ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED )
1277         return( MBEDTLS_ERR_PK_PASSWORD_REQUIRED );
1278     else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
1279         return( ret );
1280 #endif /* MBEDTLS_ECP_C */
1281 
1282     /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1283     if( keylen == 0 || key[keylen - 1] != '\0' )
1284         ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1285     else
1286         ret = mbedtls_pem_read_buffer( &pem,
1287                                "-----BEGIN PRIVATE KEY-----",
1288                                "-----END PRIVATE KEY-----",
1289                                key, NULL, 0, &len );
1290     if( ret == 0 )
1291     {
1292         if( ( ret = pk_parse_key_pkcs8_unencrypted_der( pk,
1293                                                 pem.buf, pem.buflen ) ) != 0 )
1294         {
1295             mbedtls_pk_free( pk );
1296         }
1297 
1298         mbedtls_pem_free( &pem );
1299         return( ret );
1300     }
1301     else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
1302         return( ret );
1303 
1304 #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
1305     /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1306     if( keylen == 0 || key[keylen - 1] != '\0' )
1307         ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1308     else
1309         ret = mbedtls_pem_read_buffer( &pem,
1310                                "-----BEGIN ENCRYPTED PRIVATE KEY-----",
1311                                "-----END ENCRYPTED PRIVATE KEY-----",
1312                                key, NULL, 0, &len );
1313     if( ret == 0 )
1314     {
1315         if( ( ret = pk_parse_key_pkcs8_encrypted_der( pk,
1316                                                       pem.buf, pem.buflen,
1317                                                       pwd, pwdlen ) ) != 0 )
1318         {
1319             mbedtls_pk_free( pk );
1320         }
1321 
1322         mbedtls_pem_free( &pem );
1323         return( ret );
1324     }
1325     else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
1326         return( ret );
1327 #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
1328 #else
1329     ((void) pwd);
1330     ((void) pwdlen);
1331 #endif /* MBEDTLS_PEM_PARSE_C */
1332 
1333     /*
1334      * At this point we only know it's not a PEM formatted key. Could be any
1335      * of the known DER encoded private key formats
1336      *
1337      * We try the different DER format parsers to see if one passes without
1338      * error
1339      */
1340 #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
1341     {
1342         unsigned char *key_copy;
1343 
1344         if( keylen == 0 )
1345             return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
1346 
1347         if( ( key_copy = mbedtls_calloc( 1, keylen ) ) == NULL )
1348             return( MBEDTLS_ERR_PK_ALLOC_FAILED );
1349 
1350         memcpy( key_copy, key, keylen );
1351 
1352         ret = pk_parse_key_pkcs8_encrypted_der( pk, key_copy, keylen,
1353                                                 pwd, pwdlen );
1354 
1355         mbedtls_zeroize( key_copy, keylen );
1356         mbedtls_free( key_copy );
1357     }
1358 
1359     if( ret == 0 )
1360         return( 0 );
1361 
1362     mbedtls_pk_free( pk );
1363     mbedtls_pk_init( pk );
1364 
1365     if( ret == MBEDTLS_ERR_PK_PASSWORD_MISMATCH )
1366     {
1367         return( ret );
1368     }
1369 #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
1370 
1371     if( ( ret = pk_parse_key_pkcs8_unencrypted_der( pk, key, keylen ) ) == 0 )
1372         return( 0 );
1373 
1374     mbedtls_pk_free( pk );
1375     mbedtls_pk_init( pk );
1376 
1377 #if defined(MBEDTLS_RSA_C)
1378 
1379     pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA );
1380     if( mbedtls_pk_setup( pk, pk_info ) == 0 &&
1381         pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ), key, keylen ) == 0 )
1382     {
1383         return( 0 );
1384     }
1385 
1386     mbedtls_pk_free( pk );
1387     mbedtls_pk_init( pk );
1388 #endif /* MBEDTLS_RSA_C */
1389 
1390 #if defined(MBEDTLS_ECP_C)
1391     pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY );
1392     if( mbedtls_pk_setup( pk, pk_info ) == 0 &&
1393         pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ),
1394                                key, keylen ) == 0 )
1395     {
1396         return( 0 );
1397     }
1398     mbedtls_pk_free( pk );
1399 #endif /* MBEDTLS_ECP_C */
1400 
1401     /* If MBEDTLS_RSA_C is defined but MBEDTLS_ECP_C isn't,
1402      * it is ok to leave the PK context initialized but not
1403      * freed: It is the caller's responsibility to call pk_init()
1404      * before calling this function, and to call pk_free()
1405      * when it fails. If MBEDTLS_ECP_C is defined but MBEDTLS_RSA_C
1406      * isn't, this leads to mbedtls_pk_free() being called
1407      * twice, once here and once by the caller, but this is
1408      * also ok and in line with the mbedtls_pk_free() calls
1409      * on failed PEM parsing attempts. */
1410 
1411     return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
1412 }
1413 
1414 /*
1415  * Parse a public key
1416  */
1417 int mbedtls_pk_parse_public_key( mbedtls_pk_context *ctx,
1418                          const unsigned char *key, size_t keylen )
1419 {
1420     int ret;
1421     unsigned char *p;
1422 #if defined(MBEDTLS_PEM_PARSE_C)
1423     size_t len;
1424     mbedtls_pem_context pem;
1425 
1426     mbedtls_pem_init( &pem );
1427 
1428     /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1429     if( keylen == 0 || key[keylen - 1] != '\0' )
1430         ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1431     else
1432         ret = mbedtls_pem_read_buffer( &pem,
1433                 "-----BEGIN PUBLIC KEY-----",
1434                 "-----END PUBLIC KEY-----",
1435                 key, NULL, 0, &len );
1436 
1437     if( ret == 0 )
1438     {
1439         /*
1440          * Was PEM encoded
1441          */
1442         key = pem.buf;
1443         keylen = pem.buflen;
1444     }
1445     else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
1446     {
1447         mbedtls_pem_free( &pem );
1448         return( ret );
1449     }
1450 #endif /* MBEDTLS_PEM_PARSE_C */
1451     p = (unsigned char *) key;
1452 
1453     ret = mbedtls_pk_parse_subpubkey( &p, p + keylen, ctx );
1454 
1455 #if defined(MBEDTLS_PEM_PARSE_C)
1456     mbedtls_pem_free( &pem );
1457 #endif
1458 
1459     return( ret );
1460 }
1461 
1462 #endif /* MBEDTLS_PK_PARSE_C */
1463