pkparse.c 46 KB

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