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