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