pkparse.c 46 KB

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