x509_crt.c 79 KB

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