pkparse.c 46 KB

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