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