x509_crt.c 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730
  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. *r_parent = parent;
  1745. *r_signature_is_good = signature_is_good;
  1746. break;
  1747. }
  1748. if( parent == NULL )
  1749. {
  1750. *r_parent = fallback_parent;
  1751. *r_signature_is_good = fallback_signature_is_good;
  1752. }
  1753. return( 0 );
  1754. }
  1755. /*
  1756. * Find a parent in trusted CAs or the provided chain, or return NULL.
  1757. *
  1758. * Searches in trusted CAs first, and return the first suitable parent found
  1759. * (see find_parent_in() for definition of suitable).
  1760. *
  1761. * Arguments:
  1762. * - [in] child: certificate for which we're looking for a parent, followed
  1763. * by a chain of possible intermediates
  1764. * - [in] trust_ca: list of locally trusted certificates
  1765. * - [out] parent: parent found (or NULL)
  1766. * - [out] parent_is_trusted: 1 if returned `parent` is trusted, or 0
  1767. * - [out] signature_is_good: 1 if child signature by parent is valid, or 0
  1768. * - [in] path_cnt: number of links in the chain so far (EE -> ... -> child)
  1769. * - [in] self_cnt: number of self-signed certs in the chain so far
  1770. * (will always be no greater than path_cnt)
  1771. * - [in-out] rs_ctx: context for restarting operations
  1772. *
  1773. * Return value:
  1774. * - 0 on success
  1775. * - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise
  1776. */
  1777. static int x509_crt_find_parent(
  1778. mbedtls_x509_crt *child,
  1779. mbedtls_x509_crt *trust_ca,
  1780. mbedtls_x509_crt **parent,
  1781. int *parent_is_trusted,
  1782. int *signature_is_good,
  1783. unsigned path_cnt,
  1784. unsigned self_cnt,
  1785. mbedtls_x509_crt_restart_ctx *rs_ctx )
  1786. {
  1787. int ret;
  1788. mbedtls_x509_crt *search_list;
  1789. *parent_is_trusted = 1;
  1790. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  1791. /* restore then clear saved state if we have some stored */
  1792. if( rs_ctx != NULL && rs_ctx->parent_is_trusted != -1 )
  1793. {
  1794. *parent_is_trusted = rs_ctx->parent_is_trusted;
  1795. rs_ctx->parent_is_trusted = -1;
  1796. }
  1797. #endif
  1798. while( 1 ) {
  1799. search_list = *parent_is_trusted ? trust_ca : child->next;
  1800. ret = x509_crt_find_parent_in( child, search_list,
  1801. parent, signature_is_good,
  1802. *parent_is_trusted,
  1803. path_cnt, self_cnt, rs_ctx );
  1804. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  1805. if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
  1806. {
  1807. /* save state */
  1808. rs_ctx->parent_is_trusted = *parent_is_trusted;
  1809. return( ret );
  1810. }
  1811. #else
  1812. (void) ret;
  1813. #endif
  1814. /* stop here if found or already in second iteration */
  1815. if( *parent != NULL || *parent_is_trusted == 0 )
  1816. break;
  1817. /* prepare second iteration */
  1818. *parent_is_trusted = 0;
  1819. }
  1820. /* extra precaution against mistakes in the caller */
  1821. if( *parent == NULL )
  1822. {
  1823. *parent_is_trusted = 0;
  1824. *signature_is_good = 0;
  1825. }
  1826. return( 0 );
  1827. }
  1828. /*
  1829. * Check if an end-entity certificate is locally trusted
  1830. *
  1831. * Currently we require such certificates to be self-signed (actually only
  1832. * check for self-issued as self-signatures are not checked)
  1833. */
  1834. static int x509_crt_check_ee_locally_trusted(
  1835. mbedtls_x509_crt *crt,
  1836. mbedtls_x509_crt *trust_ca )
  1837. {
  1838. mbedtls_x509_crt *cur;
  1839. /* must be self-issued */
  1840. if( x509_name_cmp( &crt->issuer, &crt->subject ) != 0 )
  1841. return( -1 );
  1842. /* look for an exact match with trusted cert */
  1843. for( cur = trust_ca; cur != NULL; cur = cur->next )
  1844. {
  1845. if( crt->raw.len == cur->raw.len &&
  1846. memcmp( crt->raw.p, cur->raw.p, crt->raw.len ) == 0 )
  1847. {
  1848. return( 0 );
  1849. }
  1850. }
  1851. /* too bad */
  1852. return( -1 );
  1853. }
  1854. /*
  1855. * Build and verify a certificate chain
  1856. *
  1857. * Given a peer-provided list of certificates EE, C1, ..., Cn and
  1858. * a list of trusted certs R1, ... Rp, try to build and verify a chain
  1859. * EE, Ci1, ... Ciq [, Rj]
  1860. * such that every cert in the chain is a child of the next one,
  1861. * jumping to a trusted root as early as possible.
  1862. *
  1863. * Verify that chain and return it with flags for all issues found.
  1864. *
  1865. * Special cases:
  1866. * - EE == Rj -> return a one-element list containing it
  1867. * - EE, Ci1, ..., Ciq cannot be continued with a trusted root
  1868. * -> return that chain with NOT_TRUSTED set on Ciq
  1869. *
  1870. * Tests for (aspects of) this function should include at least:
  1871. * - trusted EE
  1872. * - EE -> trusted root
  1873. * - EE -> intermediate CA -> trusted root
  1874. * - if relevant: EE untrusted
  1875. * - if relevant: EE -> intermediate, untrusted
  1876. * with the aspect under test checked at each relevant level (EE, int, root).
  1877. * For some aspects longer chains are required, but usually length 2 is
  1878. * enough (but length 1 is not in general).
  1879. *
  1880. * Arguments:
  1881. * - [in] crt: the cert list EE, C1, ..., Cn
  1882. * - [in] trust_ca: the trusted list R1, ..., Rp
  1883. * - [in] ca_crl, profile: as in verify_with_profile()
  1884. * - [out] ver_chain: the built and verified chain
  1885. * Only valid when return value is 0, may contain garbage otherwise!
  1886. * Restart note: need not be the same when calling again to resume.
  1887. * - [in-out] rs_ctx: context for restarting operations
  1888. *
  1889. * Return value:
  1890. * - non-zero if the chain could not be fully built and examined
  1891. * - 0 is the chain was successfully built and examined,
  1892. * even if it was found to be invalid
  1893. */
  1894. static int x509_crt_verify_chain(
  1895. mbedtls_x509_crt *crt,
  1896. mbedtls_x509_crt *trust_ca,
  1897. mbedtls_x509_crl *ca_crl,
  1898. const mbedtls_x509_crt_profile *profile,
  1899. mbedtls_x509_crt_verify_chain *ver_chain,
  1900. mbedtls_x509_crt_restart_ctx *rs_ctx )
  1901. {
  1902. /* Don't initialize any of those variables here, so that the compiler can
  1903. * catch potential issues with jumping ahead when restarting */
  1904. int ret;
  1905. uint32_t *flags;
  1906. mbedtls_x509_crt_verify_chain_item *cur;
  1907. mbedtls_x509_crt *child;
  1908. mbedtls_x509_crt *parent;
  1909. int parent_is_trusted;
  1910. int child_is_trusted;
  1911. int signature_is_good;
  1912. unsigned self_cnt;
  1913. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  1914. /* resume if we had an operation in progress */
  1915. if( rs_ctx != NULL && rs_ctx->in_progress == x509_crt_rs_find_parent )
  1916. {
  1917. /* restore saved state */
  1918. *ver_chain = rs_ctx->ver_chain; /* struct copy */
  1919. self_cnt = rs_ctx->self_cnt;
  1920. /* restore derived state */
  1921. cur = &ver_chain->items[ver_chain->len - 1];
  1922. child = cur->crt;
  1923. flags = &cur->flags;
  1924. goto find_parent;
  1925. }
  1926. #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
  1927. child = crt;
  1928. self_cnt = 0;
  1929. parent_is_trusted = 0;
  1930. child_is_trusted = 0;
  1931. while( 1 ) {
  1932. /* Add certificate to the verification chain */
  1933. cur = &ver_chain->items[ver_chain->len];
  1934. cur->crt = child;
  1935. cur->flags = 0;
  1936. ver_chain->len++;
  1937. flags = &cur->flags;
  1938. /* Check time-validity (all certificates) */
  1939. if( mbedtls_x509_time_is_past( &child->valid_to ) )
  1940. *flags |= MBEDTLS_X509_BADCERT_EXPIRED;
  1941. if( mbedtls_x509_time_is_future( &child->valid_from ) )
  1942. *flags |= MBEDTLS_X509_BADCERT_FUTURE;
  1943. /* Stop here for trusted roots (but not for trusted EE certs) */
  1944. if( child_is_trusted )
  1945. return( 0 );
  1946. /* Check signature algorithm: MD & PK algs */
  1947. if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )
  1948. *flags |= MBEDTLS_X509_BADCERT_BAD_MD;
  1949. if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )
  1950. *flags |= MBEDTLS_X509_BADCERT_BAD_PK;
  1951. /* Special case: EE certs that are locally trusted */
  1952. if( ver_chain->len == 1 &&
  1953. x509_crt_check_ee_locally_trusted( child, trust_ca ) == 0 )
  1954. {
  1955. return( 0 );
  1956. }
  1957. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  1958. find_parent:
  1959. #endif
  1960. /* Look for a parent in trusted CAs or up the chain */
  1961. ret = x509_crt_find_parent( child, trust_ca, &parent,
  1962. &parent_is_trusted, &signature_is_good,
  1963. ver_chain->len - 1, self_cnt, rs_ctx );
  1964. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  1965. if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
  1966. {
  1967. /* save state */
  1968. rs_ctx->in_progress = x509_crt_rs_find_parent;
  1969. rs_ctx->self_cnt = self_cnt;
  1970. rs_ctx->ver_chain = *ver_chain; /* struct copy */
  1971. return( ret );
  1972. }
  1973. #else
  1974. (void) ret;
  1975. #endif
  1976. /* No parent? We're done here */
  1977. if( parent == NULL )
  1978. {
  1979. *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
  1980. return( 0 );
  1981. }
  1982. /* Count intermediate self-issued (not necessarily self-signed) certs.
  1983. * These can occur with some strategies for key rollover, see [SIRO],
  1984. * and should be excluded from max_pathlen checks. */
  1985. if( ver_chain->len != 1 &&
  1986. x509_name_cmp( &child->issuer, &child->subject ) == 0 )
  1987. {
  1988. self_cnt++;
  1989. }
  1990. /* path_cnt is 0 for the first intermediate CA,
  1991. * and if parent is trusted it's not an intermediate CA */
  1992. if( ! parent_is_trusted &&
  1993. ver_chain->len > MBEDTLS_X509_MAX_INTERMEDIATE_CA )
  1994. {
  1995. /* return immediately to avoid overflow the chain array */
  1996. return( MBEDTLS_ERR_X509_FATAL_ERROR );
  1997. }
  1998. /* signature was checked while searching parent */
  1999. if( ! signature_is_good )
  2000. *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
  2001. /* check size of signing key */
  2002. if( x509_profile_check_key( profile, &parent->pk ) != 0 )
  2003. *flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
  2004. #if defined(MBEDTLS_X509_CRL_PARSE_C)
  2005. /* Check trusted CA's CRL for the given crt */
  2006. *flags |= x509_crt_verifycrl( child, parent, ca_crl, profile );
  2007. #else
  2008. (void) ca_crl;
  2009. #endif
  2010. /* prepare for next iteration */
  2011. child = parent;
  2012. parent = NULL;
  2013. child_is_trusted = parent_is_trusted;
  2014. signature_is_good = 0;
  2015. }
  2016. }
  2017. /*
  2018. * Check for CN match
  2019. */
  2020. static int x509_crt_check_cn( const mbedtls_x509_buf *name,
  2021. const char *cn, size_t cn_len )
  2022. {
  2023. /* try exact match */
  2024. if( name->len == cn_len &&
  2025. x509_memcasecmp( cn, name->p, cn_len ) == 0 )
  2026. {
  2027. return( 0 );
  2028. }
  2029. /* try wildcard match */
  2030. if( x509_check_wildcard( cn, name ) == 0 )
  2031. {
  2032. return( 0 );
  2033. }
  2034. return( -1 );
  2035. }
  2036. /*
  2037. * Verify the requested CN - only call this if cn is not NULL!
  2038. */
  2039. static void x509_crt_verify_name( const mbedtls_x509_crt *crt,
  2040. const char *cn,
  2041. uint32_t *flags )
  2042. {
  2043. const mbedtls_x509_name *name;
  2044. const mbedtls_x509_sequence *cur;
  2045. size_t cn_len = strlen( cn );
  2046. if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
  2047. {
  2048. for( cur = &crt->subject_alt_names; cur != NULL; cur = cur->next )
  2049. {
  2050. if( x509_crt_check_cn( &cur->buf, cn, cn_len ) == 0 )
  2051. break;
  2052. }
  2053. if( cur == NULL )
  2054. *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
  2055. }
  2056. else
  2057. {
  2058. for( name = &crt->subject; name != NULL; name = name->next )
  2059. {
  2060. if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 &&
  2061. x509_crt_check_cn( &name->val, cn, cn_len ) == 0 )
  2062. {
  2063. break;
  2064. }
  2065. }
  2066. if( name == NULL )
  2067. *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
  2068. }
  2069. }
  2070. /*
  2071. * Merge the flags for all certs in the chain, after calling callback
  2072. */
  2073. static int x509_crt_merge_flags_with_cb(
  2074. uint32_t *flags,
  2075. const mbedtls_x509_crt_verify_chain *ver_chain,
  2076. int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  2077. void *p_vrfy )
  2078. {
  2079. int ret;
  2080. unsigned i;
  2081. uint32_t cur_flags;
  2082. const mbedtls_x509_crt_verify_chain_item *cur;
  2083. for( i = ver_chain->len; i != 0; --i )
  2084. {
  2085. cur = &ver_chain->items[i-1];
  2086. cur_flags = cur->flags;
  2087. if( NULL != f_vrfy )
  2088. if( ( ret = f_vrfy( p_vrfy, cur->crt, (int) i-1, &cur_flags ) ) != 0 )
  2089. return( ret );
  2090. *flags |= cur_flags;
  2091. }
  2092. return( 0 );
  2093. }
  2094. /*
  2095. * Verify the certificate validity (default profile, not restartable)
  2096. */
  2097. int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
  2098. mbedtls_x509_crt *trust_ca,
  2099. mbedtls_x509_crl *ca_crl,
  2100. const char *cn, uint32_t *flags,
  2101. int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  2102. void *p_vrfy )
  2103. {
  2104. return( mbedtls_x509_crt_verify_restartable( crt, trust_ca, ca_crl,
  2105. &mbedtls_x509_crt_profile_default, cn, flags,
  2106. f_vrfy, p_vrfy, NULL ) );
  2107. }
  2108. /*
  2109. * Verify the certificate validity (user-chosen profile, not restartable)
  2110. */
  2111. int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
  2112. mbedtls_x509_crt *trust_ca,
  2113. mbedtls_x509_crl *ca_crl,
  2114. const mbedtls_x509_crt_profile *profile,
  2115. const char *cn, uint32_t *flags,
  2116. int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  2117. void *p_vrfy )
  2118. {
  2119. return( mbedtls_x509_crt_verify_restartable( crt, trust_ca, ca_crl,
  2120. profile, cn, flags, f_vrfy, p_vrfy, NULL ) );
  2121. }
  2122. /*
  2123. * Verify the certificate validity, with profile, restartable version
  2124. *
  2125. * This function:
  2126. * - checks the requested CN (if any)
  2127. * - checks the type and size of the EE cert's key,
  2128. * as that isn't done as part of chain building/verification currently
  2129. * - builds and verifies the chain
  2130. * - then calls the callback and merges the flags
  2131. */
  2132. int mbedtls_x509_crt_verify_restartable( mbedtls_x509_crt *crt,
  2133. mbedtls_x509_crt *trust_ca,
  2134. mbedtls_x509_crl *ca_crl,
  2135. const mbedtls_x509_crt_profile *profile,
  2136. const char *cn, uint32_t *flags,
  2137. int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  2138. void *p_vrfy,
  2139. mbedtls_x509_crt_restart_ctx *rs_ctx )
  2140. {
  2141. int ret;
  2142. mbedtls_pk_type_t pk_type;
  2143. mbedtls_x509_crt_verify_chain ver_chain;
  2144. uint32_t ee_flags;
  2145. *flags = 0;
  2146. ee_flags = 0;
  2147. x509_crt_verify_chain_reset( &ver_chain );
  2148. if( profile == NULL )
  2149. {
  2150. ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA;
  2151. goto exit;
  2152. }
  2153. /* check name if requested */
  2154. if( cn != NULL )
  2155. x509_crt_verify_name( crt, cn, &ee_flags );
  2156. /* Check the type and size of the key */
  2157. pk_type = mbedtls_pk_get_type( &crt->pk );
  2158. if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )
  2159. ee_flags |= MBEDTLS_X509_BADCERT_BAD_PK;
  2160. if( x509_profile_check_key( profile, &crt->pk ) != 0 )
  2161. ee_flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
  2162. /* Check the chain */
  2163. ret = x509_crt_verify_chain( crt, trust_ca, ca_crl, profile,
  2164. &ver_chain, rs_ctx );
  2165. if( ret != 0 )
  2166. goto exit;
  2167. /* Merge end-entity flags */
  2168. ver_chain.items[0].flags |= ee_flags;
  2169. /* Build final flags, calling callback on the way if any */
  2170. ret = x509_crt_merge_flags_with_cb( flags, &ver_chain, f_vrfy, p_vrfy );
  2171. exit:
  2172. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2173. if( rs_ctx != NULL && ret != MBEDTLS_ERR_ECP_IN_PROGRESS )
  2174. mbedtls_x509_crt_restart_free( rs_ctx );
  2175. #endif
  2176. /* prevent misuse of the vrfy callback - VERIFY_FAILED would be ignored by
  2177. * the SSL module for authmode optional, but non-zero return from the
  2178. * callback means a fatal error so it shouldn't be ignored */
  2179. if( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED )
  2180. ret = MBEDTLS_ERR_X509_FATAL_ERROR;
  2181. if( ret != 0 )
  2182. {
  2183. *flags = (uint32_t) -1;
  2184. return( ret );
  2185. }
  2186. if( *flags != 0 )
  2187. return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
  2188. return( 0 );
  2189. }
  2190. /*
  2191. * Initialize a certificate chain
  2192. */
  2193. void mbedtls_x509_crt_init( mbedtls_x509_crt *crt )
  2194. {
  2195. memset( crt, 0, sizeof(mbedtls_x509_crt) );
  2196. }
  2197. /*
  2198. * Unallocate all certificate data
  2199. */
  2200. void mbedtls_x509_crt_free( mbedtls_x509_crt *crt )
  2201. {
  2202. mbedtls_x509_crt *cert_cur = crt;
  2203. mbedtls_x509_crt *cert_prv;
  2204. mbedtls_x509_name *name_cur;
  2205. mbedtls_x509_name *name_prv;
  2206. mbedtls_x509_sequence *seq_cur;
  2207. mbedtls_x509_sequence *seq_prv;
  2208. if( crt == NULL )
  2209. return;
  2210. do
  2211. {
  2212. mbedtls_pk_free( &cert_cur->pk );
  2213. #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
  2214. mbedtls_free( cert_cur->sig_opts );
  2215. #endif
  2216. name_cur = cert_cur->issuer.next;
  2217. while( name_cur != NULL )
  2218. {
  2219. name_prv = name_cur;
  2220. name_cur = name_cur->next;
  2221. mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
  2222. mbedtls_free( name_prv );
  2223. }
  2224. name_cur = cert_cur->subject.next;
  2225. while( name_cur != NULL )
  2226. {
  2227. name_prv = name_cur;
  2228. name_cur = name_cur->next;
  2229. mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
  2230. mbedtls_free( name_prv );
  2231. }
  2232. seq_cur = cert_cur->ext_key_usage.next;
  2233. while( seq_cur != NULL )
  2234. {
  2235. seq_prv = seq_cur;
  2236. seq_cur = seq_cur->next;
  2237. mbedtls_platform_zeroize( seq_prv,
  2238. sizeof( mbedtls_x509_sequence ) );
  2239. mbedtls_free( seq_prv );
  2240. }
  2241. seq_cur = cert_cur->subject_alt_names.next;
  2242. while( seq_cur != NULL )
  2243. {
  2244. seq_prv = seq_cur;
  2245. seq_cur = seq_cur->next;
  2246. mbedtls_platform_zeroize( seq_prv,
  2247. sizeof( mbedtls_x509_sequence ) );
  2248. mbedtls_free( seq_prv );
  2249. }
  2250. if( cert_cur->raw.p != NULL )
  2251. {
  2252. mbedtls_platform_zeroize( cert_cur->raw.p, cert_cur->raw.len );
  2253. mbedtls_free( cert_cur->raw.p );
  2254. }
  2255. cert_cur = cert_cur->next;
  2256. }
  2257. while( cert_cur != NULL );
  2258. cert_cur = crt;
  2259. do
  2260. {
  2261. cert_prv = cert_cur;
  2262. cert_cur = cert_cur->next;
  2263. mbedtls_platform_zeroize( cert_prv, sizeof( mbedtls_x509_crt ) );
  2264. if( cert_prv != crt )
  2265. mbedtls_free( cert_prv );
  2266. }
  2267. while( cert_cur != NULL );
  2268. }
  2269. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2270. /*
  2271. * Initialize a restart context
  2272. */
  2273. void mbedtls_x509_crt_restart_init( mbedtls_x509_crt_restart_ctx *ctx )
  2274. {
  2275. mbedtls_pk_restart_init( &ctx->pk );
  2276. ctx->parent = NULL;
  2277. ctx->fallback_parent = NULL;
  2278. ctx->fallback_signature_is_good = 0;
  2279. ctx->parent_is_trusted = -1;
  2280. ctx->in_progress = x509_crt_rs_none;
  2281. ctx->self_cnt = 0;
  2282. x509_crt_verify_chain_reset( &ctx->ver_chain );
  2283. }
  2284. /*
  2285. * Free the components of a restart context
  2286. */
  2287. void mbedtls_x509_crt_restart_free( mbedtls_x509_crt_restart_ctx *ctx )
  2288. {
  2289. if( ctx == NULL )
  2290. return;
  2291. mbedtls_pk_restart_free( &ctx->pk );
  2292. mbedtls_x509_crt_restart_init( ctx );
  2293. }
  2294. #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
  2295. #endif /* MBEDTLS_X509_CRT_PARSE_C */