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