x509_crt.c 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510
  1. /*
  2. * X.509 certificate parsing and verification
  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. /*
  22. * The ITU-T X.509 standard defines a certificate format for PKI.
  23. *
  24. * http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)
  25. * http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)
  26. * http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)
  27. *
  28. * http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf
  29. * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
  30. *
  31. * [SIRO] https://cabforum.org/wp-content/uploads/Chunghwatelecom201503cabforumV4.pdf
  32. */
  33. #if !defined(MBEDTLS_CONFIG_FILE)
  34. #include "mbedtls/config.h"
  35. #else
  36. #include MBEDTLS_CONFIG_FILE
  37. #endif
  38. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  39. #include "mbedtls/x509_crt.h"
  40. #include "mbedtls/oid.h"
  41. #include "mbedtls/platform_util.h"
  42. #include <stdio.h>
  43. #include <string.h>
  44. #if defined(MBEDTLS_PEM_PARSE_C)
  45. #include "mbedtls/pem.h"
  46. #endif
  47. #if defined(MBEDTLS_PLATFORM_C)
  48. #include "mbedtls/platform.h"
  49. #else
  50. #include <stdlib.h>
  51. #define mbedtls_free free
  52. #define mbedtls_calloc calloc
  53. #define mbedtls_snprintf snprintf
  54. #endif
  55. #if defined(MBEDTLS_THREADING_C)
  56. #include "mbedtls/threading.h"
  57. #endif
  58. #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
  59. #include <windows.h>
  60. #if defined(_MSC_VER) && _MSC_VER <= 1600
  61. /* Visual Studio 2010 and earlier issue a warning when both <stdint.h> and
  62. * <intsafe.h> are included, as they redefine a number of <TYPE>_MAX constants.
  63. * These constants are guaranteed to be the same, though, so we suppress the
  64. * warning when including intsafe.h.
  65. */
  66. #pragma warning( push )
  67. #pragma warning( disable : 4005 )
  68. #endif
  69. #include <intsafe.h>
  70. #if defined(_MSC_VER) && _MSC_VER <= 1600
  71. #pragma warning( pop )
  72. #endif
  73. #else
  74. #include <time.h>
  75. #endif
  76. #if defined(MBEDTLS_FS_IO)
  77. #include <stdio.h>
  78. #if !defined(_WIN32) || defined(EFIX64) || defined(EFI32)
  79. #include <sys/types.h>
  80. #include <sys/stat.h>
  81. #include <dirent.h>
  82. #endif /* !_WIN32 || EFIX64 || EFI32 */
  83. #endif
  84. /*
  85. * Item in a verification chain: cert and flags for it
  86. */
  87. typedef struct {
  88. mbedtls_x509_crt *crt;
  89. uint32_t flags;
  90. } x509_crt_verify_chain_item;
  91. /*
  92. * Max size of verification chain: end-entity + intermediates + trusted root
  93. */
  94. #define X509_MAX_VERIFY_CHAIN_SIZE ( MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2 )
  95. /*
  96. * Default profile
  97. */
  98. const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default =
  99. {
  100. #if defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES)
  101. /* Allow SHA-1 (weak, but still safe in controlled environments) */
  102. MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA1 ) |
  103. #endif
  104. /* Only SHA-2 hashes */
  105. MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 ) |
  106. MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
  107. MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
  108. MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
  109. 0xFFFFFFF, /* Any PK alg */
  110. 0xFFFFFFF, /* Any curve */
  111. 2048,
  112. };
  113. /*
  114. * Next-default profile
  115. */
  116. const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next =
  117. {
  118. /* Hashes from SHA-256 and above */
  119. MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
  120. MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
  121. MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
  122. 0xFFFFFFF, /* Any PK alg */
  123. #if defined(MBEDTLS_ECP_C)
  124. /* Curves at or above 128-bit security level */
  125. MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
  126. MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ) |
  127. MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP521R1 ) |
  128. MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP256R1 ) |
  129. MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP384R1 ) |
  130. MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP512R1 ) |
  131. MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256K1 ),
  132. #else
  133. 0,
  134. #endif
  135. 2048,
  136. };
  137. /*
  138. * NSA Suite B Profile
  139. */
  140. const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb =
  141. {
  142. /* Only SHA-256 and 384 */
  143. MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
  144. MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ),
  145. /* Only ECDSA */
  146. MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECDSA ) |
  147. MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECKEY ),
  148. #if defined(MBEDTLS_ECP_C)
  149. /* Only NIST P-256 and P-384 */
  150. MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
  151. MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ),
  152. #else
  153. 0,
  154. #endif
  155. 0,
  156. };
  157. /*
  158. * Check md_alg against profile
  159. * Return 0 if md_alg is acceptable for this profile, -1 otherwise
  160. */
  161. static int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile,
  162. mbedtls_md_type_t md_alg )
  163. {
  164. if( ( profile->allowed_mds & MBEDTLS_X509_ID_FLAG( md_alg ) ) != 0 )
  165. return( 0 );
  166. return( -1 );
  167. }
  168. /*
  169. * Check pk_alg against profile
  170. * Return 0 if pk_alg is acceptable for this profile, -1 otherwise
  171. */
  172. static int x509_profile_check_pk_alg( const mbedtls_x509_crt_profile *profile,
  173. mbedtls_pk_type_t pk_alg )
  174. {
  175. if( ( profile->allowed_pks & MBEDTLS_X509_ID_FLAG( pk_alg ) ) != 0 )
  176. return( 0 );
  177. return( -1 );
  178. }
  179. /*
  180. * Check key against profile
  181. * Return 0 if pk is acceptable for this profile, -1 otherwise
  182. */
  183. static int x509_profile_check_key( const mbedtls_x509_crt_profile *profile,
  184. const mbedtls_pk_context *pk )
  185. {
  186. const mbedtls_pk_type_t pk_alg = mbedtls_pk_get_type( pk );
  187. #if defined(MBEDTLS_RSA_C)
  188. if( pk_alg == MBEDTLS_PK_RSA || pk_alg == MBEDTLS_PK_RSASSA_PSS )
  189. {
  190. if( mbedtls_pk_get_bitlen( pk ) >= profile->rsa_min_bitlen )
  191. return( 0 );
  192. return( -1 );
  193. }
  194. #endif
  195. #if defined(MBEDTLS_ECP_C)
  196. if( pk_alg == MBEDTLS_PK_ECDSA ||
  197. pk_alg == MBEDTLS_PK_ECKEY ||
  198. pk_alg == MBEDTLS_PK_ECKEY_DH )
  199. {
  200. const mbedtls_ecp_group_id gid = mbedtls_pk_ec( *pk )->grp.id;
  201. if( ( profile->allowed_curves & MBEDTLS_X509_ID_FLAG( gid ) ) != 0 )
  202. return( 0 );
  203. return( -1 );
  204. }
  205. #endif
  206. return( -1 );
  207. }
  208. /*
  209. * Version ::= INTEGER { v1(0), v2(1), v3(2) }
  210. */
  211. static int x509_get_version( unsigned char **p,
  212. const unsigned char *end,
  213. int *ver )
  214. {
  215. int ret;
  216. size_t len;
  217. if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
  218. MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) != 0 )
  219. {
  220. if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
  221. {
  222. *ver = 0;
  223. return( 0 );
  224. }
  225. return( ret );
  226. }
  227. end = *p + len;
  228. if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 )
  229. return( MBEDTLS_ERR_X509_INVALID_VERSION + ret );
  230. if( *p != end )
  231. return( MBEDTLS_ERR_X509_INVALID_VERSION +
  232. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  233. return( 0 );
  234. }
  235. /*
  236. * Validity ::= SEQUENCE {
  237. * notBefore Time,
  238. * notAfter Time }
  239. */
  240. static int x509_get_dates( unsigned char **p,
  241. const unsigned char *end,
  242. mbedtls_x509_time *from,
  243. mbedtls_x509_time *to )
  244. {
  245. int ret;
  246. size_t len;
  247. if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
  248. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  249. return( MBEDTLS_ERR_X509_INVALID_DATE + ret );
  250. end = *p + len;
  251. if( ( ret = mbedtls_x509_get_time( p, end, from ) ) != 0 )
  252. return( ret );
  253. if( ( ret = mbedtls_x509_get_time( p, end, to ) ) != 0 )
  254. return( ret );
  255. if( *p != end )
  256. return( MBEDTLS_ERR_X509_INVALID_DATE +
  257. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  258. return( 0 );
  259. }
  260. /*
  261. * X.509 v2/v3 unique identifier (not parsed)
  262. */
  263. static int x509_get_uid( unsigned char **p,
  264. const unsigned char *end,
  265. mbedtls_x509_buf *uid, int n )
  266. {
  267. int ret;
  268. if( *p == end )
  269. return( 0 );
  270. uid->tag = **p;
  271. if( ( ret = mbedtls_asn1_get_tag( p, end, &uid->len,
  272. MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | n ) ) != 0 )
  273. {
  274. if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
  275. return( 0 );
  276. return( ret );
  277. }
  278. uid->p = *p;
  279. *p += uid->len;
  280. return( 0 );
  281. }
  282. static int x509_get_basic_constraints( unsigned char **p,
  283. const unsigned char *end,
  284. int *ca_istrue,
  285. int *max_pathlen )
  286. {
  287. int ret;
  288. size_t len;
  289. /*
  290. * BasicConstraints ::= SEQUENCE {
  291. * cA BOOLEAN DEFAULT FALSE,
  292. * pathLenConstraint INTEGER (0..MAX) OPTIONAL }
  293. */
  294. *ca_istrue = 0; /* DEFAULT FALSE */
  295. *max_pathlen = 0; /* endless */
  296. if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
  297. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  298. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  299. if( *p == end )
  300. return( 0 );
  301. if( ( ret = mbedtls_asn1_get_bool( p, end, ca_istrue ) ) != 0 )
  302. {
  303. if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
  304. ret = mbedtls_asn1_get_int( p, end, ca_istrue );
  305. if( ret != 0 )
  306. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  307. if( *ca_istrue != 0 )
  308. *ca_istrue = 1;
  309. }
  310. if( *p == end )
  311. return( 0 );
  312. if( ( ret = mbedtls_asn1_get_int( p, end, max_pathlen ) ) != 0 )
  313. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  314. if( *p != end )
  315. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  316. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  317. (*max_pathlen)++;
  318. return( 0 );
  319. }
  320. static int x509_get_ns_cert_type( unsigned char **p,
  321. const unsigned char *end,
  322. unsigned char *ns_cert_type)
  323. {
  324. int ret;
  325. mbedtls_x509_bitstring bs = { 0, 0, NULL };
  326. if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
  327. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  328. if( bs.len != 1 )
  329. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  330. MBEDTLS_ERR_ASN1_INVALID_LENGTH );
  331. /* Get actual bitstring */
  332. *ns_cert_type = *bs.p;
  333. return( 0 );
  334. }
  335. static int x509_get_key_usage( unsigned char **p,
  336. const unsigned char *end,
  337. unsigned int *key_usage)
  338. {
  339. int ret;
  340. size_t i;
  341. mbedtls_x509_bitstring bs = { 0, 0, NULL };
  342. if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
  343. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  344. if( bs.len < 1 )
  345. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  346. MBEDTLS_ERR_ASN1_INVALID_LENGTH );
  347. /* Get actual bitstring */
  348. *key_usage = 0;
  349. for( i = 0; i < bs.len && i < sizeof( unsigned int ); i++ )
  350. {
  351. *key_usage |= (unsigned int) bs.p[i] << (8*i);
  352. }
  353. return( 0 );
  354. }
  355. /*
  356. * ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
  357. *
  358. * KeyPurposeId ::= OBJECT IDENTIFIER
  359. */
  360. static int x509_get_ext_key_usage( unsigned char **p,
  361. const unsigned char *end,
  362. mbedtls_x509_sequence *ext_key_usage)
  363. {
  364. int ret;
  365. if( ( ret = mbedtls_asn1_get_sequence_of( p, end, ext_key_usage, MBEDTLS_ASN1_OID ) ) != 0 )
  366. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  367. /* Sequence length must be >= 1 */
  368. if( ext_key_usage->buf.p == NULL )
  369. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  370. MBEDTLS_ERR_ASN1_INVALID_LENGTH );
  371. return( 0 );
  372. }
  373. /*
  374. * SubjectAltName ::= GeneralNames
  375. *
  376. * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
  377. *
  378. * GeneralName ::= CHOICE {
  379. * otherName [0] OtherName,
  380. * rfc822Name [1] IA5String,
  381. * dNSName [2] IA5String,
  382. * x400Address [3] ORAddress,
  383. * directoryName [4] Name,
  384. * ediPartyName [5] EDIPartyName,
  385. * uniformResourceIdentifier [6] IA5String,
  386. * iPAddress [7] OCTET STRING,
  387. * registeredID [8] OBJECT IDENTIFIER }
  388. *
  389. * OtherName ::= SEQUENCE {
  390. * type-id OBJECT IDENTIFIER,
  391. * value [0] EXPLICIT ANY DEFINED BY type-id }
  392. *
  393. * EDIPartyName ::= SEQUENCE {
  394. * nameAssigner [0] DirectoryString OPTIONAL,
  395. * partyName [1] DirectoryString }
  396. *
  397. * NOTE: we only parse and use dNSName at this point.
  398. */
  399. static int x509_get_subject_alt_name( unsigned char **p,
  400. const unsigned char *end,
  401. mbedtls_x509_sequence *subject_alt_name )
  402. {
  403. int ret;
  404. size_t len, tag_len;
  405. mbedtls_asn1_buf *buf;
  406. unsigned char tag;
  407. mbedtls_asn1_sequence *cur = subject_alt_name;
  408. /* Get main sequence tag */
  409. if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
  410. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  411. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  412. if( *p + len != end )
  413. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  414. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  415. while( *p < end )
  416. {
  417. if( ( end - *p ) < 1 )
  418. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  419. MBEDTLS_ERR_ASN1_OUT_OF_DATA );
  420. tag = **p;
  421. (*p)++;
  422. if( ( ret = mbedtls_asn1_get_len( p, end, &tag_len ) ) != 0 )
  423. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  424. if( ( tag & MBEDTLS_ASN1_TAG_CLASS_MASK ) !=
  425. MBEDTLS_ASN1_CONTEXT_SPECIFIC )
  426. {
  427. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  428. MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
  429. }
  430. /* Skip everything but DNS name */
  431. if( tag != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2 ) )
  432. {
  433. *p += tag_len;
  434. continue;
  435. }
  436. /* Allocate and assign next pointer */
  437. if( cur->buf.p != NULL )
  438. {
  439. if( cur->next != NULL )
  440. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
  441. cur->next = mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) );
  442. if( cur->next == NULL )
  443. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  444. MBEDTLS_ERR_ASN1_ALLOC_FAILED );
  445. cur = cur->next;
  446. }
  447. buf = &(cur->buf);
  448. buf->tag = tag;
  449. buf->p = *p;
  450. buf->len = tag_len;
  451. *p += buf->len;
  452. }
  453. /* Set final sequence entry's next pointer to NULL */
  454. cur->next = NULL;
  455. if( *p != end )
  456. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  457. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  458. return( 0 );
  459. }
  460. /*
  461. * X.509 v3 extensions
  462. *
  463. */
  464. static int x509_get_crt_ext( unsigned char **p,
  465. const unsigned char *end,
  466. mbedtls_x509_crt *crt )
  467. {
  468. int ret;
  469. size_t len;
  470. unsigned char *end_ext_data, *end_ext_octet;
  471. if( ( ret = mbedtls_x509_get_ext( p, end, &crt->v3_ext, 3 ) ) != 0 )
  472. {
  473. if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
  474. return( 0 );
  475. return( ret );
  476. }
  477. while( *p < end )
  478. {
  479. /*
  480. * Extension ::= SEQUENCE {
  481. * extnID OBJECT IDENTIFIER,
  482. * critical BOOLEAN DEFAULT FALSE,
  483. * extnValue OCTET STRING }
  484. */
  485. mbedtls_x509_buf extn_oid = {0, 0, NULL};
  486. int is_critical = 0; /* DEFAULT FALSE */
  487. int ext_type = 0;
  488. if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
  489. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  490. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  491. end_ext_data = *p + len;
  492. /* Get extension ID */
  493. extn_oid.tag = **p;
  494. if( ( ret = mbedtls_asn1_get_tag( p, end, &extn_oid.len, MBEDTLS_ASN1_OID ) ) != 0 )
  495. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  496. extn_oid.p = *p;
  497. *p += extn_oid.len;
  498. if( ( end - *p ) < 1 )
  499. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  500. MBEDTLS_ERR_ASN1_OUT_OF_DATA );
  501. /* Get optional critical */
  502. if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 &&
  503. ( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) )
  504. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  505. /* Data should be octet string type */
  506. if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len,
  507. MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
  508. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  509. end_ext_octet = *p + len;
  510. if( end_ext_octet != end_ext_data )
  511. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  512. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  513. /*
  514. * Detect supported extensions
  515. */
  516. ret = mbedtls_oid_get_x509_ext_type( &extn_oid, &ext_type );
  517. if( ret != 0 )
  518. {
  519. /* No parser found, skip extension */
  520. *p = end_ext_octet;
  521. #if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION)
  522. if( is_critical )
  523. {
  524. /* Data is marked as critical: fail */
  525. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  526. MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
  527. }
  528. #endif
  529. continue;
  530. }
  531. /* Forbid repeated extensions */
  532. if( ( crt->ext_types & ext_type ) != 0 )
  533. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
  534. crt->ext_types |= ext_type;
  535. switch( ext_type )
  536. {
  537. case MBEDTLS_X509_EXT_BASIC_CONSTRAINTS:
  538. /* Parse basic constraints */
  539. if( ( ret = x509_get_basic_constraints( p, end_ext_octet,
  540. &crt->ca_istrue, &crt->max_pathlen ) ) != 0 )
  541. return( ret );
  542. break;
  543. case MBEDTLS_X509_EXT_KEY_USAGE:
  544. /* Parse key usage */
  545. if( ( ret = x509_get_key_usage( p, end_ext_octet,
  546. &crt->key_usage ) ) != 0 )
  547. return( ret );
  548. break;
  549. case MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE:
  550. /* Parse extended key usage */
  551. if( ( ret = x509_get_ext_key_usage( p, end_ext_octet,
  552. &crt->ext_key_usage ) ) != 0 )
  553. return( ret );
  554. break;
  555. case MBEDTLS_X509_EXT_SUBJECT_ALT_NAME:
  556. /* Parse subject alt name */
  557. if( ( ret = x509_get_subject_alt_name( p, end_ext_octet,
  558. &crt->subject_alt_names ) ) != 0 )
  559. return( ret );
  560. break;
  561. case MBEDTLS_X509_EXT_NS_CERT_TYPE:
  562. /* Parse netscape certificate type */
  563. if( ( ret = x509_get_ns_cert_type( p, end_ext_octet,
  564. &crt->ns_cert_type ) ) != 0 )
  565. return( ret );
  566. break;
  567. default:
  568. return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE );
  569. }
  570. }
  571. if( *p != end )
  572. return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  573. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  574. return( 0 );
  575. }
  576. /*
  577. * Parse and fill a single X.509 certificate in DER format
  578. */
  579. static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char *buf,
  580. size_t buflen )
  581. {
  582. int ret;
  583. size_t len;
  584. unsigned char *p, *end, *crt_end;
  585. mbedtls_x509_buf sig_params1, sig_params2, sig_oid2;
  586. memset( &sig_params1, 0, sizeof( mbedtls_x509_buf ) );
  587. memset( &sig_params2, 0, sizeof( mbedtls_x509_buf ) );
  588. memset( &sig_oid2, 0, sizeof( mbedtls_x509_buf ) );
  589. /*
  590. * Check for valid input
  591. */
  592. if( crt == NULL || buf == NULL )
  593. return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  594. // Use the original buffer until we figure out actual length
  595. p = (unsigned char*) buf;
  596. len = buflen;
  597. end = p + len;
  598. /*
  599. * Certificate ::= SEQUENCE {
  600. * tbsCertificate TBSCertificate,
  601. * signatureAlgorithm AlgorithmIdentifier,
  602. * signatureValue BIT STRING }
  603. */
  604. if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
  605. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  606. {
  607. mbedtls_x509_crt_free( crt );
  608. return( MBEDTLS_ERR_X509_INVALID_FORMAT );
  609. }
  610. if( len > (size_t) ( end - p ) )
  611. {
  612. mbedtls_x509_crt_free( crt );
  613. return( MBEDTLS_ERR_X509_INVALID_FORMAT +
  614. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  615. }
  616. crt_end = p + len;
  617. // Create and populate a new buffer for the raw field
  618. crt->raw.len = crt_end - buf;
  619. crt->raw.p = p = mbedtls_calloc( 1, crt->raw.len );
  620. if( p == NULL )
  621. return( MBEDTLS_ERR_X509_ALLOC_FAILED );
  622. memcpy( p, buf, crt->raw.len );
  623. // Direct pointers to the new buffer
  624. p += crt->raw.len - len;
  625. end = crt_end = p + len;
  626. /*
  627. * TBSCertificate ::= SEQUENCE {
  628. */
  629. crt->tbs.p = p;
  630. if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
  631. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  632. {
  633. mbedtls_x509_crt_free( crt );
  634. return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
  635. }
  636. end = p + len;
  637. crt->tbs.len = end - crt->tbs.p;
  638. /*
  639. * Version ::= INTEGER { v1(0), v2(1), v3(2) }
  640. *
  641. * CertificateSerialNumber ::= INTEGER
  642. *
  643. * signature AlgorithmIdentifier
  644. */
  645. if( ( ret = x509_get_version( &p, end, &crt->version ) ) != 0 ||
  646. ( ret = mbedtls_x509_get_serial( &p, end, &crt->serial ) ) != 0 ||
  647. ( ret = mbedtls_x509_get_alg( &p, end, &crt->sig_oid,
  648. &sig_params1 ) ) != 0 )
  649. {
  650. mbedtls_x509_crt_free( crt );
  651. return( ret );
  652. }
  653. if( crt->version < 0 || crt->version > 2 )
  654. {
  655. mbedtls_x509_crt_free( crt );
  656. return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );
  657. }
  658. crt->version++;
  659. if( ( ret = mbedtls_x509_get_sig_alg( &crt->sig_oid, &sig_params1,
  660. &crt->sig_md, &crt->sig_pk,
  661. &crt->sig_opts ) ) != 0 )
  662. {
  663. mbedtls_x509_crt_free( crt );
  664. return( ret );
  665. }
  666. /*
  667. * issuer Name
  668. */
  669. crt->issuer_raw.p = p;
  670. if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
  671. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  672. {
  673. mbedtls_x509_crt_free( crt );
  674. return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
  675. }
  676. if( ( ret = mbedtls_x509_get_name( &p, p + len, &crt->issuer ) ) != 0 )
  677. {
  678. mbedtls_x509_crt_free( crt );
  679. return( ret );
  680. }
  681. crt->issuer_raw.len = p - crt->issuer_raw.p;
  682. /*
  683. * Validity ::= SEQUENCE {
  684. * notBefore Time,
  685. * notAfter Time }
  686. *
  687. */
  688. if( ( ret = x509_get_dates( &p, end, &crt->valid_from,
  689. &crt->valid_to ) ) != 0 )
  690. {
  691. mbedtls_x509_crt_free( crt );
  692. return( ret );
  693. }
  694. /*
  695. * subject Name
  696. */
  697. crt->subject_raw.p = p;
  698. if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
  699. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  700. {
  701. mbedtls_x509_crt_free( crt );
  702. return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
  703. }
  704. if( len && ( ret = mbedtls_x509_get_name( &p, p + len, &crt->subject ) ) != 0 )
  705. {
  706. mbedtls_x509_crt_free( crt );
  707. return( ret );
  708. }
  709. crt->subject_raw.len = p - crt->subject_raw.p;
  710. /*
  711. * SubjectPublicKeyInfo
  712. */
  713. if( ( ret = mbedtls_pk_parse_subpubkey( &p, end, &crt->pk ) ) != 0 )
  714. {
  715. mbedtls_x509_crt_free( crt );
  716. return( ret );
  717. }
  718. /*
  719. * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
  720. * -- If present, version shall be v2 or v3
  721. * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
  722. * -- If present, version shall be v2 or v3
  723. * extensions [3] EXPLICIT Extensions OPTIONAL
  724. * -- If present, version shall be v3
  725. */
  726. if( crt->version == 2 || crt->version == 3 )
  727. {
  728. ret = x509_get_uid( &p, end, &crt->issuer_id, 1 );
  729. if( ret != 0 )
  730. {
  731. mbedtls_x509_crt_free( crt );
  732. return( ret );
  733. }
  734. }
  735. if( crt->version == 2 || crt->version == 3 )
  736. {
  737. ret = x509_get_uid( &p, end, &crt->subject_id, 2 );
  738. if( ret != 0 )
  739. {
  740. mbedtls_x509_crt_free( crt );
  741. return( ret );
  742. }
  743. }
  744. #if !defined(MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3)
  745. if( crt->version == 3 )
  746. #endif
  747. {
  748. ret = x509_get_crt_ext( &p, end, crt );
  749. if( ret != 0 )
  750. {
  751. mbedtls_x509_crt_free( crt );
  752. return( ret );
  753. }
  754. }
  755. if( p != end )
  756. {
  757. mbedtls_x509_crt_free( crt );
  758. return( MBEDTLS_ERR_X509_INVALID_FORMAT +
  759. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  760. }
  761. end = crt_end;
  762. /*
  763. * }
  764. * -- end of TBSCertificate
  765. *
  766. * signatureAlgorithm AlgorithmIdentifier,
  767. * signatureValue BIT STRING
  768. */
  769. if( ( ret = mbedtls_x509_get_alg( &p, end, &sig_oid2, &sig_params2 ) ) != 0 )
  770. {
  771. mbedtls_x509_crt_free( crt );
  772. return( ret );
  773. }
  774. if( crt->sig_oid.len != sig_oid2.len ||
  775. memcmp( crt->sig_oid.p, sig_oid2.p, crt->sig_oid.len ) != 0 ||
  776. sig_params1.len != sig_params2.len ||
  777. ( sig_params1.len != 0 &&
  778. memcmp( sig_params1.p, sig_params2.p, sig_params1.len ) != 0 ) )
  779. {
  780. mbedtls_x509_crt_free( crt );
  781. return( MBEDTLS_ERR_X509_SIG_MISMATCH );
  782. }
  783. if( ( ret = mbedtls_x509_get_sig( &p, end, &crt->sig ) ) != 0 )
  784. {
  785. mbedtls_x509_crt_free( crt );
  786. return( ret );
  787. }
  788. if( p != end )
  789. {
  790. mbedtls_x509_crt_free( crt );
  791. return( MBEDTLS_ERR_X509_INVALID_FORMAT +
  792. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  793. }
  794. return( 0 );
  795. }
  796. /*
  797. * Parse one X.509 certificate in DER format from a buffer and add them to a
  798. * chained list
  799. */
  800. int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf,
  801. size_t buflen )
  802. {
  803. int ret;
  804. mbedtls_x509_crt *crt = chain, *prev = NULL;
  805. /*
  806. * Check for valid input
  807. */
  808. if( crt == NULL || buf == NULL )
  809. return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  810. while( crt->version != 0 && crt->next != NULL )
  811. {
  812. prev = crt;
  813. crt = crt->next;
  814. }
  815. /*
  816. * Add new certificate on the end of the chain if needed.
  817. */
  818. if( crt->version != 0 && crt->next == NULL )
  819. {
  820. crt->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
  821. if( crt->next == NULL )
  822. return( MBEDTLS_ERR_X509_ALLOC_FAILED );
  823. prev = crt;
  824. mbedtls_x509_crt_init( crt->next );
  825. crt = crt->next;
  826. }
  827. if( ( ret = x509_crt_parse_der_core( crt, buf, buflen ) ) != 0 )
  828. {
  829. if( prev )
  830. prev->next = NULL;
  831. if( crt != chain )
  832. mbedtls_free( crt );
  833. return( ret );
  834. }
  835. return( 0 );
  836. }
  837. /*
  838. * Parse one or more PEM certificates from a buffer and add them to the chained
  839. * list
  840. */
  841. int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen )
  842. {
  843. #if defined(MBEDTLS_PEM_PARSE_C)
  844. int success = 0, first_error = 0, total_failed = 0;
  845. int buf_format = MBEDTLS_X509_FORMAT_DER;
  846. #endif
  847. /*
  848. * Check for valid input
  849. */
  850. if( chain == NULL || buf == NULL )
  851. return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  852. /*
  853. * Determine buffer content. Buffer contains either one DER certificate or
  854. * one or more PEM certificates.
  855. */
  856. #if defined(MBEDTLS_PEM_PARSE_C)
  857. if( buflen != 0 && buf[buflen - 1] == '\0' &&
  858. strstr( (const char *) buf, "-----BEGIN CERTIFICATE-----" ) != NULL )
  859. {
  860. buf_format = MBEDTLS_X509_FORMAT_PEM;
  861. }
  862. if( buf_format == MBEDTLS_X509_FORMAT_DER )
  863. return mbedtls_x509_crt_parse_der( chain, buf, buflen );
  864. #else
  865. return mbedtls_x509_crt_parse_der( chain, buf, buflen );
  866. #endif
  867. #if defined(MBEDTLS_PEM_PARSE_C)
  868. if( buf_format == MBEDTLS_X509_FORMAT_PEM )
  869. {
  870. int ret;
  871. mbedtls_pem_context pem;
  872. /* 1 rather than 0 since the terminating NULL byte is counted in */
  873. while( buflen > 1 )
  874. {
  875. size_t use_len;
  876. mbedtls_pem_init( &pem );
  877. /* If we get there, we know the string is null-terminated */
  878. ret = mbedtls_pem_read_buffer( &pem,
  879. "-----BEGIN CERTIFICATE-----",
  880. "-----END CERTIFICATE-----",
  881. buf, NULL, 0, &use_len );
  882. if( ret == 0 )
  883. {
  884. /*
  885. * Was PEM encoded
  886. */
  887. buflen -= use_len;
  888. buf += use_len;
  889. }
  890. else if( ret == MBEDTLS_ERR_PEM_BAD_INPUT_DATA )
  891. {
  892. return( ret );
  893. }
  894. else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
  895. {
  896. mbedtls_pem_free( &pem );
  897. /*
  898. * PEM header and footer were found
  899. */
  900. buflen -= use_len;
  901. buf += use_len;
  902. if( first_error == 0 )
  903. first_error = ret;
  904. total_failed++;
  905. continue;
  906. }
  907. else
  908. break;
  909. ret = mbedtls_x509_crt_parse_der( chain, pem.buf, pem.buflen );
  910. mbedtls_pem_free( &pem );
  911. if( ret != 0 )
  912. {
  913. /*
  914. * Quit parsing on a memory error
  915. */
  916. if( ret == MBEDTLS_ERR_X509_ALLOC_FAILED )
  917. return( ret );
  918. if( first_error == 0 )
  919. first_error = ret;
  920. total_failed++;
  921. continue;
  922. }
  923. success = 1;
  924. }
  925. }
  926. if( success )
  927. return( total_failed );
  928. else if( first_error )
  929. return( first_error );
  930. else
  931. return( MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT );
  932. #endif /* MBEDTLS_PEM_PARSE_C */
  933. }
  934. #if defined(MBEDTLS_FS_IO)
  935. /*
  936. * Load one or more certificates and add them to the chained list
  937. */
  938. int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path )
  939. {
  940. int ret;
  941. size_t n;
  942. unsigned char *buf;
  943. if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )
  944. return( ret );
  945. ret = mbedtls_x509_crt_parse( chain, buf, n );
  946. mbedtls_platform_zeroize( buf, n );
  947. mbedtls_free( buf );
  948. return( ret );
  949. }
  950. int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )
  951. {
  952. int ret = 0;
  953. #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
  954. int w_ret;
  955. WCHAR szDir[MAX_PATH];
  956. char filename[MAX_PATH];
  957. char *p;
  958. size_t len = strlen( path );
  959. int length_as_int = 0;
  960. WIN32_FIND_DATAW file_data;
  961. HANDLE hFind;
  962. if( len > MAX_PATH - 3 )
  963. return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  964. memset( szDir, 0, sizeof(szDir) );
  965. memset( filename, 0, MAX_PATH );
  966. memcpy( filename, path, len );
  967. filename[len++] = '\\';
  968. p = filename + len;
  969. filename[len++] = '*';
  970. if ( FAILED ( SizeTToInt( len, &length_as_int ) ) )
  971. return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
  972. /*
  973. * Note this function uses the code page CP_ACP, and assumes the incoming
  974. * string is encoded in ANSI, before translating it into Unicode. If the
  975. * incoming string were changed to be UTF-8, then the length check needs to
  976. * change to check the number of characters, not the number of bytes, in the
  977. * incoming string are less than MAX_PATH to avoid a buffer overrun with
  978. * MultiByteToWideChar().
  979. */
  980. w_ret = MultiByteToWideChar( CP_ACP, 0, filename, length_as_int, szDir,
  981. MAX_PATH - 3 );
  982. if( w_ret == 0 )
  983. return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  984. hFind = FindFirstFileW( szDir, &file_data );
  985. if( hFind == INVALID_HANDLE_VALUE )
  986. return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
  987. len = MAX_PATH - len;
  988. do
  989. {
  990. memset( p, 0, len );
  991. if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
  992. continue;
  993. if ( FAILED( SizeTToInt( wcslen( file_data.cFileName ), &length_as_int ) ) )
  994. return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
  995. w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName,
  996. length_as_int,
  997. p, (int) len - 1,
  998. NULL, NULL );
  999. if( w_ret == 0 )
  1000. {
  1001. ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
  1002. goto cleanup;
  1003. }
  1004. w_ret = mbedtls_x509_crt_parse_file( chain, filename );
  1005. if( w_ret < 0 )
  1006. ret++;
  1007. else
  1008. ret += w_ret;
  1009. }
  1010. while( FindNextFileW( hFind, &file_data ) != 0 );
  1011. if( GetLastError() != ERROR_NO_MORE_FILES )
  1012. ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
  1013. cleanup:
  1014. FindClose( hFind );
  1015. #else /* _WIN32 */
  1016. int t_ret;
  1017. int snp_ret;
  1018. struct stat sb;
  1019. struct dirent *entry;
  1020. char entry_name[MBEDTLS_X509_MAX_FILE_PATH_LEN];
  1021. DIR *dir = opendir( path );
  1022. if( dir == NULL )
  1023. return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
  1024. #if defined(MBEDTLS_THREADING_C)
  1025. if( ( ret = mbedtls_mutex_lock( &mbedtls_threading_readdir_mutex ) ) != 0 )
  1026. {
  1027. closedir( dir );
  1028. return( ret );
  1029. }
  1030. #endif /* MBEDTLS_THREADING_C */
  1031. while( ( entry = readdir( dir ) ) != NULL )
  1032. {
  1033. snp_ret = mbedtls_snprintf( entry_name, sizeof entry_name,
  1034. "%s/%s", path, entry->d_name );
  1035. if( snp_ret < 0 || (size_t)snp_ret >= sizeof entry_name )
  1036. {
  1037. ret = MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
  1038. goto cleanup;
  1039. }
  1040. else if( stat( entry_name, &sb ) == -1 )
  1041. {
  1042. ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
  1043. goto cleanup;
  1044. }
  1045. if( !S_ISREG( sb.st_mode ) )
  1046. continue;
  1047. // Ignore parse errors
  1048. //
  1049. t_ret = mbedtls_x509_crt_parse_file( chain, entry_name );
  1050. if( t_ret < 0 )
  1051. ret++;
  1052. else
  1053. ret += t_ret;
  1054. }
  1055. cleanup:
  1056. closedir( dir );
  1057. #if defined(MBEDTLS_THREADING_C)
  1058. if( mbedtls_mutex_unlock( &mbedtls_threading_readdir_mutex ) != 0 )
  1059. ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR;
  1060. #endif /* MBEDTLS_THREADING_C */
  1061. #endif /* _WIN32 */
  1062. return( ret );
  1063. }
  1064. #endif /* MBEDTLS_FS_IO */
  1065. static int x509_info_subject_alt_name( char **buf, size_t *size,
  1066. const mbedtls_x509_sequence *subject_alt_name )
  1067. {
  1068. size_t i;
  1069. size_t n = *size;
  1070. char *p = *buf;
  1071. const mbedtls_x509_sequence *cur = subject_alt_name;
  1072. const char *sep = "";
  1073. size_t sep_len = 0;
  1074. while( cur != NULL )
  1075. {
  1076. if( cur->buf.len + sep_len >= n )
  1077. {
  1078. *p = '\0';
  1079. return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );
  1080. }
  1081. n -= cur->buf.len + sep_len;
  1082. for( i = 0; i < sep_len; i++ )
  1083. *p++ = sep[i];
  1084. for( i = 0; i < cur->buf.len; i++ )
  1085. *p++ = cur->buf.p[i];
  1086. sep = ", ";
  1087. sep_len = 2;
  1088. cur = cur->next;
  1089. }
  1090. *p = '\0';
  1091. *size = n;
  1092. *buf = p;
  1093. return( 0 );
  1094. }
  1095. #define PRINT_ITEM(i) \
  1096. { \
  1097. ret = mbedtls_snprintf( p, n, "%s" i, sep ); \
  1098. MBEDTLS_X509_SAFE_SNPRINTF; \
  1099. sep = ", "; \
  1100. }
  1101. #define CERT_TYPE(type,name) \
  1102. if( ns_cert_type & type ) \
  1103. PRINT_ITEM( name );
  1104. static int x509_info_cert_type( char **buf, size_t *size,
  1105. unsigned char ns_cert_type )
  1106. {
  1107. int ret;
  1108. size_t n = *size;
  1109. char *p = *buf;
  1110. const char *sep = "";
  1111. CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT, "SSL Client" );
  1112. CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER, "SSL Server" );
  1113. CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL, "Email" );
  1114. CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING, "Object Signing" );
  1115. CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_RESERVED, "Reserved" );
  1116. CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CA, "SSL CA" );
  1117. CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA, "Email CA" );
  1118. CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA, "Object Signing CA" );
  1119. *size = n;
  1120. *buf = p;
  1121. return( 0 );
  1122. }
  1123. #define KEY_USAGE(code,name) \
  1124. if( key_usage & code ) \
  1125. PRINT_ITEM( name );
  1126. static int x509_info_key_usage( char **buf, size_t *size,
  1127. unsigned int key_usage )
  1128. {
  1129. int ret;
  1130. size_t n = *size;
  1131. char *p = *buf;
  1132. const char *sep = "";
  1133. KEY_USAGE( MBEDTLS_X509_KU_DIGITAL_SIGNATURE, "Digital Signature" );
  1134. KEY_USAGE( MBEDTLS_X509_KU_NON_REPUDIATION, "Non Repudiation" );
  1135. KEY_USAGE( MBEDTLS_X509_KU_KEY_ENCIPHERMENT, "Key Encipherment" );
  1136. KEY_USAGE( MBEDTLS_X509_KU_DATA_ENCIPHERMENT, "Data Encipherment" );
  1137. KEY_USAGE( MBEDTLS_X509_KU_KEY_AGREEMENT, "Key Agreement" );
  1138. KEY_USAGE( MBEDTLS_X509_KU_KEY_CERT_SIGN, "Key Cert Sign" );
  1139. KEY_USAGE( MBEDTLS_X509_KU_CRL_SIGN, "CRL Sign" );
  1140. KEY_USAGE( MBEDTLS_X509_KU_ENCIPHER_ONLY, "Encipher Only" );
  1141. KEY_USAGE( MBEDTLS_X509_KU_DECIPHER_ONLY, "Decipher Only" );
  1142. *size = n;
  1143. *buf = p;
  1144. return( 0 );
  1145. }
  1146. static int x509_info_ext_key_usage( char **buf, size_t *size,
  1147. const mbedtls_x509_sequence *extended_key_usage )
  1148. {
  1149. int ret;
  1150. const char *desc;
  1151. size_t n = *size;
  1152. char *p = *buf;
  1153. const mbedtls_x509_sequence *cur = extended_key_usage;
  1154. const char *sep = "";
  1155. while( cur != NULL )
  1156. {
  1157. if( mbedtls_oid_get_extended_key_usage( &cur->buf, &desc ) != 0 )
  1158. desc = "???";
  1159. ret = mbedtls_snprintf( p, n, "%s%s", sep, desc );
  1160. MBEDTLS_X509_SAFE_SNPRINTF;
  1161. sep = ", ";
  1162. cur = cur->next;
  1163. }
  1164. *size = n;
  1165. *buf = p;
  1166. return( 0 );
  1167. }
  1168. /*
  1169. * Return an informational string about the certificate.
  1170. */
  1171. #define BEFORE_COLON 18
  1172. #define BC "18"
  1173. int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix,
  1174. const mbedtls_x509_crt *crt )
  1175. {
  1176. int ret;
  1177. size_t n;
  1178. char *p;
  1179. char key_size_str[BEFORE_COLON];
  1180. p = buf;
  1181. n = size;
  1182. if( NULL == crt )
  1183. {
  1184. ret = mbedtls_snprintf( p, n, "\nCertificate is uninitialised!\n" );
  1185. MBEDTLS_X509_SAFE_SNPRINTF;
  1186. return( (int) ( size - n ) );
  1187. }
  1188. ret = mbedtls_snprintf( p, n, "%scert. version : %d\n",
  1189. prefix, crt->version );
  1190. MBEDTLS_X509_SAFE_SNPRINTF;
  1191. ret = mbedtls_snprintf( p, n, "%sserial number : ",
  1192. prefix );
  1193. MBEDTLS_X509_SAFE_SNPRINTF;
  1194. ret = mbedtls_x509_serial_gets( p, n, &crt->serial );
  1195. MBEDTLS_X509_SAFE_SNPRINTF;
  1196. ret = mbedtls_snprintf( p, n, "\n%sissuer name : ", prefix );
  1197. MBEDTLS_X509_SAFE_SNPRINTF;
  1198. ret = mbedtls_x509_dn_gets( p, n, &crt->issuer );
  1199. MBEDTLS_X509_SAFE_SNPRINTF;
  1200. ret = mbedtls_snprintf( p, n, "\n%ssubject name : ", prefix );
  1201. MBEDTLS_X509_SAFE_SNPRINTF;
  1202. ret = mbedtls_x509_dn_gets( p, n, &crt->subject );
  1203. MBEDTLS_X509_SAFE_SNPRINTF;
  1204. ret = mbedtls_snprintf( p, n, "\n%sissued on : " \
  1205. "%04d-%02d-%02d %02d:%02d:%02d", prefix,
  1206. crt->valid_from.year, crt->valid_from.mon,
  1207. crt->valid_from.day, crt->valid_from.hour,
  1208. crt->valid_from.min, crt->valid_from.sec );
  1209. MBEDTLS_X509_SAFE_SNPRINTF;
  1210. ret = mbedtls_snprintf( p, n, "\n%sexpires on : " \
  1211. "%04d-%02d-%02d %02d:%02d:%02d", prefix,
  1212. crt->valid_to.year, crt->valid_to.mon,
  1213. crt->valid_to.day, crt->valid_to.hour,
  1214. crt->valid_to.min, crt->valid_to.sec );
  1215. MBEDTLS_X509_SAFE_SNPRINTF;
  1216. ret = mbedtls_snprintf( p, n, "\n%ssigned using : ", prefix );
  1217. MBEDTLS_X509_SAFE_SNPRINTF;
  1218. ret = mbedtls_x509_sig_alg_gets( p, n, &crt->sig_oid, crt->sig_pk,
  1219. crt->sig_md, crt->sig_opts );
  1220. MBEDTLS_X509_SAFE_SNPRINTF;
  1221. /* Key size */
  1222. if( ( ret = mbedtls_x509_key_size_helper( key_size_str, BEFORE_COLON,
  1223. mbedtls_pk_get_name( &crt->pk ) ) ) != 0 )
  1224. {
  1225. return( ret );
  1226. }
  1227. ret = mbedtls_snprintf( p, n, "\n%s%-" BC "s: %d bits", prefix, key_size_str,
  1228. (int) mbedtls_pk_get_bitlen( &crt->pk ) );
  1229. MBEDTLS_X509_SAFE_SNPRINTF;
  1230. /*
  1231. * Optional extensions
  1232. */
  1233. if( crt->ext_types & MBEDTLS_X509_EXT_BASIC_CONSTRAINTS )
  1234. {
  1235. ret = mbedtls_snprintf( p, n, "\n%sbasic constraints : CA=%s", prefix,
  1236. crt->ca_istrue ? "true" : "false" );
  1237. MBEDTLS_X509_SAFE_SNPRINTF;
  1238. if( crt->max_pathlen > 0 )
  1239. {
  1240. ret = mbedtls_snprintf( p, n, ", max_pathlen=%d", crt->max_pathlen - 1 );
  1241. MBEDTLS_X509_SAFE_SNPRINTF;
  1242. }
  1243. }
  1244. if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
  1245. {
  1246. ret = mbedtls_snprintf( p, n, "\n%ssubject alt name : ", prefix );
  1247. MBEDTLS_X509_SAFE_SNPRINTF;
  1248. if( ( ret = x509_info_subject_alt_name( &p, &n,
  1249. &crt->subject_alt_names ) ) != 0 )
  1250. return( ret );
  1251. }
  1252. if( crt->ext_types & MBEDTLS_X509_EXT_NS_CERT_TYPE )
  1253. {
  1254. ret = mbedtls_snprintf( p, n, "\n%scert. type : ", prefix );
  1255. MBEDTLS_X509_SAFE_SNPRINTF;
  1256. if( ( ret = x509_info_cert_type( &p, &n, crt->ns_cert_type ) ) != 0 )
  1257. return( ret );
  1258. }
  1259. if( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE )
  1260. {
  1261. ret = mbedtls_snprintf( p, n, "\n%skey usage : ", prefix );
  1262. MBEDTLS_X509_SAFE_SNPRINTF;
  1263. if( ( ret = x509_info_key_usage( &p, &n, crt->key_usage ) ) != 0 )
  1264. return( ret );
  1265. }
  1266. if( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE )
  1267. {
  1268. ret = mbedtls_snprintf( p, n, "\n%sext key usage : ", prefix );
  1269. MBEDTLS_X509_SAFE_SNPRINTF;
  1270. if( ( ret = x509_info_ext_key_usage( &p, &n,
  1271. &crt->ext_key_usage ) ) != 0 )
  1272. return( ret );
  1273. }
  1274. ret = mbedtls_snprintf( p, n, "\n" );
  1275. MBEDTLS_X509_SAFE_SNPRINTF;
  1276. return( (int) ( size - n ) );
  1277. }
  1278. struct x509_crt_verify_string {
  1279. int code;
  1280. const char *string;
  1281. };
  1282. static const struct x509_crt_verify_string x509_crt_verify_strings[] = {
  1283. { MBEDTLS_X509_BADCERT_EXPIRED, "The certificate validity has expired" },
  1284. { MBEDTLS_X509_BADCERT_REVOKED, "The certificate has been revoked (is on a CRL)" },
  1285. { MBEDTLS_X509_BADCERT_CN_MISMATCH, "The certificate Common Name (CN) does not match with the expected CN" },
  1286. { MBEDTLS_X509_BADCERT_NOT_TRUSTED, "The certificate is not correctly signed by the trusted CA" },
  1287. { MBEDTLS_X509_BADCRL_NOT_TRUSTED, "The CRL is not correctly signed by the trusted CA" },
  1288. { MBEDTLS_X509_BADCRL_EXPIRED, "The CRL is expired" },
  1289. { MBEDTLS_X509_BADCERT_MISSING, "Certificate was missing" },
  1290. { MBEDTLS_X509_BADCERT_SKIP_VERIFY, "Certificate verification was skipped" },
  1291. { MBEDTLS_X509_BADCERT_OTHER, "Other reason (can be used by verify callback)" },
  1292. { MBEDTLS_X509_BADCERT_FUTURE, "The certificate validity starts in the future" },
  1293. { MBEDTLS_X509_BADCRL_FUTURE, "The CRL is from the future" },
  1294. { MBEDTLS_X509_BADCERT_KEY_USAGE, "Usage does not match the keyUsage extension" },
  1295. { MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, "Usage does not match the extendedKeyUsage extension" },
  1296. { MBEDTLS_X509_BADCERT_NS_CERT_TYPE, "Usage does not match the nsCertType extension" },
  1297. { MBEDTLS_X509_BADCERT_BAD_MD, "The certificate is signed with an unacceptable hash." },
  1298. { MBEDTLS_X509_BADCERT_BAD_PK, "The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA)." },
  1299. { MBEDTLS_X509_BADCERT_BAD_KEY, "The certificate is signed with an unacceptable key (eg bad curve, RSA too short)." },
  1300. { MBEDTLS_X509_BADCRL_BAD_MD, "The CRL is signed with an unacceptable hash." },
  1301. { MBEDTLS_X509_BADCRL_BAD_PK, "The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA)." },
  1302. { MBEDTLS_X509_BADCRL_BAD_KEY, "The CRL is signed with an unacceptable key (eg bad curve, RSA too short)." },
  1303. { 0, NULL }
  1304. };
  1305. int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
  1306. uint32_t flags )
  1307. {
  1308. int ret;
  1309. const struct x509_crt_verify_string *cur;
  1310. char *p = buf;
  1311. size_t n = size;
  1312. for( cur = x509_crt_verify_strings; cur->string != NULL ; cur++ )
  1313. {
  1314. if( ( flags & cur->code ) == 0 )
  1315. continue;
  1316. ret = mbedtls_snprintf( p, n, "%s%s\n", prefix, cur->string );
  1317. MBEDTLS_X509_SAFE_SNPRINTF;
  1318. flags ^= cur->code;
  1319. }
  1320. if( flags != 0 )
  1321. {
  1322. ret = mbedtls_snprintf( p, n, "%sUnknown reason "
  1323. "(this should not happen)\n", prefix );
  1324. MBEDTLS_X509_SAFE_SNPRINTF;
  1325. }
  1326. return( (int) ( size - n ) );
  1327. }
  1328. #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
  1329. int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
  1330. unsigned int usage )
  1331. {
  1332. unsigned int usage_must, usage_may;
  1333. unsigned int may_mask = MBEDTLS_X509_KU_ENCIPHER_ONLY
  1334. | MBEDTLS_X509_KU_DECIPHER_ONLY;
  1335. if( ( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE ) == 0 )
  1336. return( 0 );
  1337. usage_must = usage & ~may_mask;
  1338. if( ( ( crt->key_usage & ~may_mask ) & usage_must ) != usage_must )
  1339. return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  1340. usage_may = usage & may_mask;
  1341. if( ( ( crt->key_usage & may_mask ) | usage_may ) != usage_may )
  1342. return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  1343. return( 0 );
  1344. }
  1345. #endif
  1346. #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
  1347. int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
  1348. const char *usage_oid,
  1349. size_t usage_len )
  1350. {
  1351. const mbedtls_x509_sequence *cur;
  1352. /* Extension is not mandatory, absent means no restriction */
  1353. if( ( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE ) == 0 )
  1354. return( 0 );
  1355. /*
  1356. * Look for the requested usage (or wildcard ANY) in our list
  1357. */
  1358. for( cur = &crt->ext_key_usage; cur != NULL; cur = cur->next )
  1359. {
  1360. const mbedtls_x509_buf *cur_oid = &cur->buf;
  1361. if( cur_oid->len == usage_len &&
  1362. memcmp( cur_oid->p, usage_oid, usage_len ) == 0 )
  1363. {
  1364. return( 0 );
  1365. }
  1366. if( MBEDTLS_OID_CMP( MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE, cur_oid ) == 0 )
  1367. return( 0 );
  1368. }
  1369. return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  1370. }
  1371. #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
  1372. #if defined(MBEDTLS_X509_CRL_PARSE_C)
  1373. /*
  1374. * Return 1 if the certificate is revoked, or 0 otherwise.
  1375. */
  1376. int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl )
  1377. {
  1378. const mbedtls_x509_crl_entry *cur = &crl->entry;
  1379. while( cur != NULL && cur->serial.len != 0 )
  1380. {
  1381. if( crt->serial.len == cur->serial.len &&
  1382. memcmp( crt->serial.p, cur->serial.p, crt->serial.len ) == 0 )
  1383. {
  1384. if( mbedtls_x509_time_is_past( &cur->revocation_date ) )
  1385. return( 1 );
  1386. }
  1387. cur = cur->next;
  1388. }
  1389. return( 0 );
  1390. }
  1391. /*
  1392. * Check that the given certificate is not revoked according to the CRL.
  1393. * Skip validation if no CRL for the given CA is present.
  1394. */
  1395. static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
  1396. mbedtls_x509_crl *crl_list,
  1397. const mbedtls_x509_crt_profile *profile )
  1398. {
  1399. int flags = 0;
  1400. unsigned char hash[MBEDTLS_MD_MAX_SIZE];
  1401. const mbedtls_md_info_t *md_info;
  1402. if( ca == NULL )
  1403. return( flags );
  1404. while( crl_list != NULL )
  1405. {
  1406. if( crl_list->version == 0 ||
  1407. crl_list->issuer_raw.len != ca->subject_raw.len ||
  1408. memcmp( crl_list->issuer_raw.p, ca->subject_raw.p,
  1409. crl_list->issuer_raw.len ) != 0 )
  1410. {
  1411. crl_list = crl_list->next;
  1412. continue;
  1413. }
  1414. /*
  1415. * Check if the CA is configured to sign CRLs
  1416. */
  1417. #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
  1418. if( mbedtls_x509_crt_check_key_usage( ca, MBEDTLS_X509_KU_CRL_SIGN ) != 0 )
  1419. {
  1420. flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
  1421. break;
  1422. }
  1423. #endif
  1424. /*
  1425. * Check if CRL is correctly signed by the trusted CA
  1426. */
  1427. if( x509_profile_check_md_alg( profile, crl_list->sig_md ) != 0 )
  1428. flags |= MBEDTLS_X509_BADCRL_BAD_MD;
  1429. if( x509_profile_check_pk_alg( profile, crl_list->sig_pk ) != 0 )
  1430. flags |= MBEDTLS_X509_BADCRL_BAD_PK;
  1431. md_info = mbedtls_md_info_from_type( crl_list->sig_md );
  1432. if( mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash ) != 0 )
  1433. {
  1434. /* Note: this can't happen except after an internal error */
  1435. flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
  1436. break;
  1437. }
  1438. if( x509_profile_check_key( profile, &ca->pk ) != 0 )
  1439. flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
  1440. if( mbedtls_pk_verify_ext( crl_list->sig_pk, crl_list->sig_opts, &ca->pk,
  1441. crl_list->sig_md, hash, mbedtls_md_get_size( md_info ),
  1442. crl_list->sig.p, crl_list->sig.len ) != 0 )
  1443. {
  1444. flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
  1445. break;
  1446. }
  1447. /*
  1448. * Check for validity of CRL (Do not drop out)
  1449. */
  1450. if( mbedtls_x509_time_is_past( &crl_list->next_update ) )
  1451. flags |= MBEDTLS_X509_BADCRL_EXPIRED;
  1452. if( mbedtls_x509_time_is_future( &crl_list->this_update ) )
  1453. flags |= MBEDTLS_X509_BADCRL_FUTURE;
  1454. /*
  1455. * Check if certificate is revoked
  1456. */
  1457. if( mbedtls_x509_crt_is_revoked( crt, crl_list ) )
  1458. {
  1459. flags |= MBEDTLS_X509_BADCERT_REVOKED;
  1460. break;
  1461. }
  1462. crl_list = crl_list->next;
  1463. }
  1464. return( flags );
  1465. }
  1466. #endif /* MBEDTLS_X509_CRL_PARSE_C */
  1467. /*
  1468. * Like memcmp, but case-insensitive and always returns -1 if different
  1469. */
  1470. static int x509_memcasecmp( const void *s1, const void *s2, size_t len )
  1471. {
  1472. size_t i;
  1473. unsigned char diff;
  1474. const unsigned char *n1 = s1, *n2 = s2;
  1475. for( i = 0; i < len; i++ )
  1476. {
  1477. diff = n1[i] ^ n2[i];
  1478. if( diff == 0 )
  1479. continue;
  1480. if( diff == 32 &&
  1481. ( ( n1[i] >= 'a' && n1[i] <= 'z' ) ||
  1482. ( n1[i] >= 'A' && n1[i] <= 'Z' ) ) )
  1483. {
  1484. continue;
  1485. }
  1486. return( -1 );
  1487. }
  1488. return( 0 );
  1489. }
  1490. /*
  1491. * Return 0 if name matches wildcard, -1 otherwise
  1492. */
  1493. static int x509_check_wildcard( const char *cn, const mbedtls_x509_buf *name )
  1494. {
  1495. size_t i;
  1496. size_t cn_idx = 0, cn_len = strlen( cn );
  1497. /* We can't have a match if there is no wildcard to match */
  1498. if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' )
  1499. return( -1 );
  1500. for( i = 0; i < cn_len; ++i )
  1501. {
  1502. if( cn[i] == '.' )
  1503. {
  1504. cn_idx = i;
  1505. break;
  1506. }
  1507. }
  1508. if( cn_idx == 0 )
  1509. return( -1 );
  1510. if( cn_len - cn_idx == name->len - 1 &&
  1511. x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
  1512. {
  1513. return( 0 );
  1514. }
  1515. return( -1 );
  1516. }
  1517. /*
  1518. * Compare two X.509 strings, case-insensitive, and allowing for some encoding
  1519. * variations (but not all).
  1520. *
  1521. * Return 0 if equal, -1 otherwise.
  1522. */
  1523. static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b )
  1524. {
  1525. if( a->tag == b->tag &&
  1526. a->len == b->len &&
  1527. memcmp( a->p, b->p, b->len ) == 0 )
  1528. {
  1529. return( 0 );
  1530. }
  1531. if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
  1532. ( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
  1533. a->len == b->len &&
  1534. x509_memcasecmp( a->p, b->p, b->len ) == 0 )
  1535. {
  1536. return( 0 );
  1537. }
  1538. return( -1 );
  1539. }
  1540. /*
  1541. * Compare two X.509 Names (aka rdnSequence).
  1542. *
  1543. * See RFC 5280 section 7.1, though we don't implement the whole algorithm:
  1544. * we sometimes return unequal when the full algorithm would return equal,
  1545. * but never the other way. (In particular, we don't do Unicode normalisation
  1546. * or space folding.)
  1547. *
  1548. * Return 0 if equal, -1 otherwise.
  1549. */
  1550. static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b )
  1551. {
  1552. /* Avoid recursion, it might not be optimised by the compiler */
  1553. while( a != NULL || b != NULL )
  1554. {
  1555. if( a == NULL || b == NULL )
  1556. return( -1 );
  1557. /* type */
  1558. if( a->oid.tag != b->oid.tag ||
  1559. a->oid.len != b->oid.len ||
  1560. memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 )
  1561. {
  1562. return( -1 );
  1563. }
  1564. /* value */
  1565. if( x509_string_cmp( &a->val, &b->val ) != 0 )
  1566. return( -1 );
  1567. /* structure of the list of sets */
  1568. if( a->next_merged != b->next_merged )
  1569. return( -1 );
  1570. a = a->next;
  1571. b = b->next;
  1572. }
  1573. /* a == NULL == b */
  1574. return( 0 );
  1575. }
  1576. /*
  1577. * Check the signature of a certificate by its parent
  1578. */
  1579. static int x509_crt_check_signature( const mbedtls_x509_crt *child,
  1580. mbedtls_x509_crt *parent )
  1581. {
  1582. const mbedtls_md_info_t *md_info;
  1583. unsigned char hash[MBEDTLS_MD_MAX_SIZE];
  1584. md_info = mbedtls_md_info_from_type( child->sig_md );
  1585. if( mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ) != 0 )
  1586. {
  1587. /* Note: this can't happen except after an internal error */
  1588. return( -1 );
  1589. }
  1590. if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk,
  1591. child->sig_md, hash, mbedtls_md_get_size( md_info ),
  1592. child->sig.p, child->sig.len ) != 0 )
  1593. {
  1594. return( -1 );
  1595. }
  1596. return( 0 );
  1597. }
  1598. /*
  1599. * Check if 'parent' is a suitable parent (signing CA) for 'child'.
  1600. * Return 0 if yes, -1 if not.
  1601. *
  1602. * top means parent is a locally-trusted certificate
  1603. */
  1604. static int x509_crt_check_parent( const mbedtls_x509_crt *child,
  1605. const mbedtls_x509_crt *parent,
  1606. int top )
  1607. {
  1608. int need_ca_bit;
  1609. /* Parent must be the issuer */
  1610. if( x509_name_cmp( &child->issuer, &parent->subject ) != 0 )
  1611. return( -1 );
  1612. /* Parent must have the basicConstraints CA bit set as a general rule */
  1613. need_ca_bit = 1;
  1614. /* Exception: v1/v2 certificates that are locally trusted. */
  1615. if( top && parent->version < 3 )
  1616. need_ca_bit = 0;
  1617. if( need_ca_bit && ! parent->ca_istrue )
  1618. return( -1 );
  1619. #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
  1620. if( need_ca_bit &&
  1621. mbedtls_x509_crt_check_key_usage( parent, MBEDTLS_X509_KU_KEY_CERT_SIGN ) != 0 )
  1622. {
  1623. return( -1 );
  1624. }
  1625. #endif
  1626. return( 0 );
  1627. }
  1628. /*
  1629. * Find a suitable parent for child in candidates, or return NULL.
  1630. *
  1631. * Here suitable is defined as:
  1632. * 1. subject name matches child's issuer
  1633. * 2. if necessary, the CA bit is set and key usage allows signing certs
  1634. * 3. for trusted roots, the signature is correct
  1635. * 4. pathlen constraints are satisfied
  1636. *
  1637. * If there's a suitable candidate which is also time-valid, return the first
  1638. * such. Otherwise, return the first suitable candidate (or NULL if there is
  1639. * none).
  1640. *
  1641. * The rationale for this rule is that someone could have a list of trusted
  1642. * roots with two versions on the same root with different validity periods.
  1643. * (At least one user reported having such a list and wanted it to just work.)
  1644. * The reason we don't just require time-validity is that generally there is
  1645. * only one version, and if it's expired we want the flags to state that
  1646. * rather than NOT_TRUSTED, as would be the case if we required it here.
  1647. *
  1648. * The rationale for rule 3 (signature for trusted roots) is that users might
  1649. * have two versions of the same CA with different keys in their list, and the
  1650. * way we select the correct one is by checking the signature (as we don't
  1651. * rely on key identifier extensions). (This is one way users might choose to
  1652. * handle key rollover, another relies on self-issued certs, see [SIRO].)
  1653. *
  1654. * Arguments:
  1655. * - [in] child: certificate for which we're looking for a parent
  1656. * - [in] candidates: chained list of potential parents
  1657. * - [in] top: 1 if candidates consists of trusted roots, ie we're at the top
  1658. * of the chain, 0 otherwise
  1659. * - [in] path_cnt: number of intermediates seen so far
  1660. * - [in] self_cnt: number of self-signed intermediates seen so far
  1661. * (will never be greater than path_cnt)
  1662. *
  1663. * Return value:
  1664. * - the first suitable parent found (see above regarding time-validity)
  1665. * - NULL if no suitable parent was found
  1666. */
  1667. static mbedtls_x509_crt *x509_crt_find_parent_in( mbedtls_x509_crt *child,
  1668. mbedtls_x509_crt *candidates,
  1669. int top,
  1670. size_t path_cnt,
  1671. size_t self_cnt )
  1672. {
  1673. mbedtls_x509_crt *parent, *badtime_parent = NULL;
  1674. for( parent = candidates; parent != NULL; parent = parent->next )
  1675. {
  1676. /* basic parenting skills (name, CA bit, key usage) */
  1677. if( x509_crt_check_parent( child, parent, top ) != 0 )
  1678. continue;
  1679. /* +1 because stored max_pathlen is 1 higher that the actual value */
  1680. if( parent->max_pathlen > 0 &&
  1681. (size_t) parent->max_pathlen < 1 + path_cnt - self_cnt )
  1682. {
  1683. continue;
  1684. }
  1685. /* Signature */
  1686. if( top && x509_crt_check_signature( child, parent ) != 0 )
  1687. {
  1688. continue;
  1689. }
  1690. /* optional time check */
  1691. if( mbedtls_x509_time_is_past( &parent->valid_to ) ||
  1692. mbedtls_x509_time_is_future( &parent->valid_from ) )
  1693. {
  1694. if( badtime_parent == NULL )
  1695. badtime_parent = parent;
  1696. continue;
  1697. }
  1698. break;
  1699. }
  1700. if( parent == NULL )
  1701. parent = badtime_parent;
  1702. return( parent );
  1703. }
  1704. /*
  1705. * Find a parent in trusted CAs or the provided chain, or return NULL.
  1706. *
  1707. * Searches in trusted CAs first, and return the first suitable parent found
  1708. * (see find_parent_in() for definition of suitable).
  1709. *
  1710. * Arguments:
  1711. * - [in] child: certificate for which we're looking for a parent, followed
  1712. * by a chain of possible intermediates
  1713. * - [in] trust_ca: locally trusted CAs
  1714. * - [out] 1 if parent was found in trust_ca, 0 if found in provided chain
  1715. * - [in] path_cnt: number of intermediates seen so far
  1716. * - [in] self_cnt: number of self-signed intermediates seen so far
  1717. * (will always be no greater than path_cnt)
  1718. *
  1719. * Return value:
  1720. * - the first suitable parent found (see find_parent_in() for "suitable")
  1721. * - NULL if no suitable parent was found
  1722. */
  1723. static mbedtls_x509_crt *x509_crt_find_parent( mbedtls_x509_crt *child,
  1724. mbedtls_x509_crt *trust_ca,
  1725. int *parent_is_trusted,
  1726. size_t path_cnt,
  1727. size_t self_cnt )
  1728. {
  1729. mbedtls_x509_crt *parent;
  1730. /* Look for a parent in trusted CAs */
  1731. *parent_is_trusted = 1;
  1732. parent = x509_crt_find_parent_in( child, trust_ca, 1, path_cnt, self_cnt );
  1733. if( parent != NULL )
  1734. return( parent );
  1735. /* Look for a parent upwards the chain */
  1736. *parent_is_trusted = 0;
  1737. return( x509_crt_find_parent_in( child, child->next, 0, path_cnt, self_cnt ) );
  1738. }
  1739. /*
  1740. * Check if an end-entity certificate is locally trusted
  1741. *
  1742. * Currently we require such certificates to be self-signed (actually only
  1743. * check for self-issued as self-signatures are not checked)
  1744. */
  1745. static int x509_crt_check_ee_locally_trusted(
  1746. mbedtls_x509_crt *crt,
  1747. mbedtls_x509_crt *trust_ca )
  1748. {
  1749. mbedtls_x509_crt *cur;
  1750. /* must be self-issued */
  1751. if( x509_name_cmp( &crt->issuer, &crt->subject ) != 0 )
  1752. return( -1 );
  1753. /* look for an exact match with trusted cert */
  1754. for( cur = trust_ca; cur != NULL; cur = cur->next )
  1755. {
  1756. if( crt->raw.len == cur->raw.len &&
  1757. memcmp( crt->raw.p, cur->raw.p, crt->raw.len ) == 0 )
  1758. {
  1759. return( 0 );
  1760. }
  1761. }
  1762. /* too bad */
  1763. return( -1 );
  1764. }
  1765. /*
  1766. * Build and verify a certificate chain
  1767. *
  1768. * Given a peer-provided list of certificates EE, C1, ..., Cn and
  1769. * a list of trusted certs R1, ... Rp, try to build and verify a chain
  1770. * EE, Ci1, ... Ciq [, Rj]
  1771. * such that every cert in the chain is a child of the next one,
  1772. * jumping to a trusted root as early as possible.
  1773. *
  1774. * Verify that chain and return it with flags for all issues found.
  1775. *
  1776. * Special cases:
  1777. * - EE == Rj -> return a one-element list containing it
  1778. * - EE, Ci1, ..., Ciq cannot be continued with a trusted root
  1779. * -> return that chain with NOT_TRUSTED set on Ciq
  1780. *
  1781. * Arguments:
  1782. * - [in] crt: the cert list EE, C1, ..., Cn
  1783. * - [in] trust_ca: the trusted list R1, ..., Rp
  1784. * - [in] ca_crl, profile: as in verify_with_profile()
  1785. * - [out] ver_chain, chain_len: the built and verified chain
  1786. *
  1787. * Return value:
  1788. * - non-zero if the chain could not be fully built and examined
  1789. * - 0 is the chain was successfully built and examined,
  1790. * even if it was found to be invalid
  1791. */
  1792. static int x509_crt_verify_chain(
  1793. mbedtls_x509_crt *crt,
  1794. mbedtls_x509_crt *trust_ca,
  1795. mbedtls_x509_crl *ca_crl,
  1796. const mbedtls_x509_crt_profile *profile,
  1797. x509_crt_verify_chain_item ver_chain[X509_MAX_VERIFY_CHAIN_SIZE],
  1798. size_t *chain_len )
  1799. {
  1800. uint32_t *flags;
  1801. mbedtls_x509_crt *child;
  1802. mbedtls_x509_crt *parent;
  1803. int parent_is_trusted = 0;
  1804. int child_is_trusted = 0;
  1805. size_t self_cnt = 0;
  1806. child = crt;
  1807. *chain_len = 0;
  1808. while( 1 ) {
  1809. /* Add certificate to the verification chain */
  1810. ver_chain[*chain_len].crt = child;
  1811. flags = &ver_chain[*chain_len].flags;
  1812. ++*chain_len;
  1813. /* Check time-validity (all certificates) */
  1814. if( mbedtls_x509_time_is_past( &child->valid_to ) )
  1815. *flags |= MBEDTLS_X509_BADCERT_EXPIRED;
  1816. if( mbedtls_x509_time_is_future( &child->valid_from ) )
  1817. *flags |= MBEDTLS_X509_BADCERT_FUTURE;
  1818. /* Stop here for trusted roots (but not for trusted EE certs) */
  1819. if( child_is_trusted )
  1820. return( 0 );
  1821. /* Check signature algorithm: MD & PK algs */
  1822. if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )
  1823. *flags |= MBEDTLS_X509_BADCERT_BAD_MD;
  1824. if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )
  1825. *flags |= MBEDTLS_X509_BADCERT_BAD_PK;
  1826. /* Special case: EE certs that are locally trusted */
  1827. if( *chain_len == 1 &&
  1828. x509_crt_check_ee_locally_trusted( child, trust_ca ) == 0 )
  1829. {
  1830. return( 0 );
  1831. }
  1832. /* Look for a parent in trusted CAs or up the chain */
  1833. parent = x509_crt_find_parent( child, trust_ca, &parent_is_trusted,
  1834. *chain_len - 1, self_cnt );
  1835. /* No parent? We're done here */
  1836. if( parent == NULL )
  1837. {
  1838. *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
  1839. return( 0 );
  1840. }
  1841. /* Count intermediate self-issued (not necessarily self-signed) certs.
  1842. * These can occur with some strategies for key rollover, see [SIRO],
  1843. * and should be excluded from max_pathlen checks. */
  1844. if( *chain_len != 1 &&
  1845. x509_name_cmp( &child->issuer, &child->subject ) == 0 )
  1846. {
  1847. self_cnt++;
  1848. }
  1849. /* path_cnt is 0 for the first intermediate CA,
  1850. * and if parent is trusted it's not an intermediate CA */
  1851. if( ! parent_is_trusted &&
  1852. *chain_len > MBEDTLS_X509_MAX_INTERMEDIATE_CA )
  1853. {
  1854. /* return immediately to avoid overflow the chain array */
  1855. return( MBEDTLS_ERR_X509_FATAL_ERROR );
  1856. }
  1857. /* if parent is trusted, the signature was checked by find_parent() */
  1858. if( ! parent_is_trusted && x509_crt_check_signature( child, parent ) != 0 )
  1859. *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
  1860. /* check size of signing key */
  1861. if( x509_profile_check_key( profile, &parent->pk ) != 0 )
  1862. *flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
  1863. #if defined(MBEDTLS_X509_CRL_PARSE_C)
  1864. /* Check trusted CA's CRL for the given crt */
  1865. *flags |= x509_crt_verifycrl( child, parent, ca_crl, profile );
  1866. #else
  1867. (void) ca_crl;
  1868. #endif
  1869. /* prepare for next iteration */
  1870. child = parent;
  1871. parent = NULL;
  1872. child_is_trusted = parent_is_trusted;
  1873. }
  1874. }
  1875. /*
  1876. * Check for CN match
  1877. */
  1878. static int x509_crt_check_cn( const mbedtls_x509_buf *name,
  1879. const char *cn, size_t cn_len )
  1880. {
  1881. /* try exact match */
  1882. if( name->len == cn_len &&
  1883. x509_memcasecmp( cn, name->p, cn_len ) == 0 )
  1884. {
  1885. return( 0 );
  1886. }
  1887. /* try wildcard match */
  1888. if( x509_check_wildcard( cn, name ) == 0 )
  1889. {
  1890. return( 0 );
  1891. }
  1892. return( -1 );
  1893. }
  1894. /*
  1895. * Verify the requested CN - only call this if cn is not NULL!
  1896. */
  1897. static void x509_crt_verify_name( const mbedtls_x509_crt *crt,
  1898. const char *cn,
  1899. uint32_t *flags )
  1900. {
  1901. const mbedtls_x509_name *name;
  1902. const mbedtls_x509_sequence *cur;
  1903. size_t cn_len = strlen( cn );
  1904. if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
  1905. {
  1906. for( cur = &crt->subject_alt_names; cur != NULL; cur = cur->next )
  1907. {
  1908. if( x509_crt_check_cn( &cur->buf, cn, cn_len ) == 0 )
  1909. break;
  1910. }
  1911. if( cur == NULL )
  1912. *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
  1913. }
  1914. else
  1915. {
  1916. for( name = &crt->subject; name != NULL; name = name->next )
  1917. {
  1918. if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 &&
  1919. x509_crt_check_cn( &name->val, cn, cn_len ) == 0 )
  1920. {
  1921. break;
  1922. }
  1923. }
  1924. if( name == NULL )
  1925. *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
  1926. }
  1927. }
  1928. /*
  1929. * Merge the flags for all certs in the chain, after calling callback
  1930. */
  1931. static int x509_crt_merge_flags_with_cb(
  1932. uint32_t *flags,
  1933. x509_crt_verify_chain_item ver_chain[X509_MAX_VERIFY_CHAIN_SIZE],
  1934. size_t chain_len,
  1935. int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  1936. void *p_vrfy )
  1937. {
  1938. int ret;
  1939. size_t i;
  1940. uint32_t cur_flags;
  1941. for( i = chain_len; i != 0; --i )
  1942. {
  1943. cur_flags = ver_chain[i-1].flags;
  1944. if( NULL != f_vrfy )
  1945. if( ( ret = f_vrfy( p_vrfy, ver_chain[i-1].crt, (int) i-1, &cur_flags ) ) != 0 )
  1946. return( ret );
  1947. *flags |= cur_flags;
  1948. }
  1949. return( 0 );
  1950. }
  1951. /*
  1952. * Verify the certificate validity
  1953. */
  1954. int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
  1955. mbedtls_x509_crt *trust_ca,
  1956. mbedtls_x509_crl *ca_crl,
  1957. const char *cn, uint32_t *flags,
  1958. int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  1959. void *p_vrfy )
  1960. {
  1961. return( mbedtls_x509_crt_verify_with_profile( crt, trust_ca, ca_crl,
  1962. &mbedtls_x509_crt_profile_default, cn, flags, f_vrfy, p_vrfy ) );
  1963. }
  1964. /*
  1965. * Verify the certificate validity, with profile
  1966. *
  1967. * This function:
  1968. * - checks the requested CN (if any)
  1969. * - checks the type and size of the EE cert's key,
  1970. * as that isn't done as part of chain building/verification currently
  1971. * - builds and verifies the chain
  1972. * - then calls the callback and merges the flags
  1973. */
  1974. int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
  1975. mbedtls_x509_crt *trust_ca,
  1976. mbedtls_x509_crl *ca_crl,
  1977. const mbedtls_x509_crt_profile *profile,
  1978. const char *cn, uint32_t *flags,
  1979. int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  1980. void *p_vrfy )
  1981. {
  1982. int ret;
  1983. mbedtls_pk_type_t pk_type;
  1984. x509_crt_verify_chain_item ver_chain[X509_MAX_VERIFY_CHAIN_SIZE];
  1985. size_t chain_len;
  1986. uint32_t *ee_flags = &ver_chain[0].flags;
  1987. *flags = 0;
  1988. memset( ver_chain, 0, sizeof( ver_chain ) );
  1989. chain_len = 0;
  1990. if( profile == NULL )
  1991. {
  1992. ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA;
  1993. goto exit;
  1994. }
  1995. /* check name if requested */
  1996. if( cn != NULL )
  1997. x509_crt_verify_name( crt, cn, ee_flags );
  1998. /* Check the type and size of the key */
  1999. pk_type = mbedtls_pk_get_type( &crt->pk );
  2000. if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )
  2001. *ee_flags |= MBEDTLS_X509_BADCERT_BAD_PK;
  2002. if( x509_profile_check_key( profile, &crt->pk ) != 0 )
  2003. *ee_flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
  2004. /* Check the chain */
  2005. ret = x509_crt_verify_chain( crt, trust_ca, ca_crl, profile,
  2006. ver_chain, &chain_len );
  2007. if( ret != 0 )
  2008. goto exit;
  2009. /* Build final flags, calling callback on the way if any */
  2010. ret = x509_crt_merge_flags_with_cb( flags,
  2011. ver_chain, chain_len, f_vrfy, p_vrfy );
  2012. exit:
  2013. /* prevent misuse of the vrfy callback - VERIFY_FAILED would be ignored by
  2014. * the SSL module for authmode optional, but non-zero return from the
  2015. * callback means a fatal error so it shouldn't be ignored */
  2016. if( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED )
  2017. ret = MBEDTLS_ERR_X509_FATAL_ERROR;
  2018. if( ret != 0 )
  2019. {
  2020. *flags = (uint32_t) -1;
  2021. return( ret );
  2022. }
  2023. if( *flags != 0 )
  2024. return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
  2025. return( 0 );
  2026. }
  2027. /*
  2028. * Initialize a certificate chain
  2029. */
  2030. void mbedtls_x509_crt_init( mbedtls_x509_crt *crt )
  2031. {
  2032. memset( crt, 0, sizeof(mbedtls_x509_crt) );
  2033. }
  2034. /*
  2035. * Unallocate all certificate data
  2036. */
  2037. void mbedtls_x509_crt_free( mbedtls_x509_crt *crt )
  2038. {
  2039. mbedtls_x509_crt *cert_cur = crt;
  2040. mbedtls_x509_crt *cert_prv;
  2041. mbedtls_x509_name *name_cur;
  2042. mbedtls_x509_name *name_prv;
  2043. mbedtls_x509_sequence *seq_cur;
  2044. mbedtls_x509_sequence *seq_prv;
  2045. if( crt == NULL )
  2046. return;
  2047. do
  2048. {
  2049. mbedtls_pk_free( &cert_cur->pk );
  2050. #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
  2051. mbedtls_free( cert_cur->sig_opts );
  2052. #endif
  2053. name_cur = cert_cur->issuer.next;
  2054. while( name_cur != NULL )
  2055. {
  2056. name_prv = name_cur;
  2057. name_cur = name_cur->next;
  2058. mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
  2059. mbedtls_free( name_prv );
  2060. }
  2061. name_cur = cert_cur->subject.next;
  2062. while( name_cur != NULL )
  2063. {
  2064. name_prv = name_cur;
  2065. name_cur = name_cur->next;
  2066. mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
  2067. mbedtls_free( name_prv );
  2068. }
  2069. seq_cur = cert_cur->ext_key_usage.next;
  2070. while( seq_cur != NULL )
  2071. {
  2072. seq_prv = seq_cur;
  2073. seq_cur = seq_cur->next;
  2074. mbedtls_platform_zeroize( seq_prv,
  2075. sizeof( mbedtls_x509_sequence ) );
  2076. mbedtls_free( seq_prv );
  2077. }
  2078. seq_cur = cert_cur->subject_alt_names.next;
  2079. while( seq_cur != NULL )
  2080. {
  2081. seq_prv = seq_cur;
  2082. seq_cur = seq_cur->next;
  2083. mbedtls_platform_zeroize( seq_prv,
  2084. sizeof( mbedtls_x509_sequence ) );
  2085. mbedtls_free( seq_prv );
  2086. }
  2087. if( cert_cur->raw.p != NULL )
  2088. {
  2089. mbedtls_platform_zeroize( cert_cur->raw.p, cert_cur->raw.len );
  2090. mbedtls_free( cert_cur->raw.p );
  2091. }
  2092. cert_cur = cert_cur->next;
  2093. }
  2094. while( cert_cur != NULL );
  2095. cert_cur = crt;
  2096. do
  2097. {
  2098. cert_prv = cert_cur;
  2099. cert_cur = cert_cur->next;
  2100. mbedtls_platform_zeroize( cert_prv, sizeof( mbedtls_x509_crt ) );
  2101. if( cert_prv != crt )
  2102. mbedtls_free( cert_prv );
  2103. }
  2104. while( cert_cur != NULL );
  2105. }
  2106. #endif /* MBEDTLS_X509_CRT_PARSE_C */