x509_crt.c 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303
  1. /*
  2. * X.509 certificate parsing and verification
  3. *
  4. * Copyright The Mbed TLS Contributors
  5. * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  6. */
  7. /*
  8. * The ITU-T X.509 standard defines a certificate format for PKI.
  9. *
  10. * http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)
  11. * http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)
  12. * http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)
  13. *
  14. * http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf
  15. * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
  16. *
  17. * [SIRO] https://cabforum.org/wp-content/uploads/Chunghwatelecom201503cabforumV4.pdf
  18. */
  19. #include "common.h"
  20. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  21. #include "mbedtls/x509_crt.h"
  22. #include "x509_internal.h"
  23. #include "mbedtls/error.h"
  24. #include "mbedtls/oid.h"
  25. #include "mbedtls/platform_util.h"
  26. #include <string.h>
  27. #if defined(MBEDTLS_PEM_PARSE_C)
  28. #include "mbedtls/pem.h"
  29. #endif
  30. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  31. #include "psa/crypto.h"
  32. #include "psa_util_internal.h"
  33. #include "mbedtls/psa_util.h"
  34. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  35. #include "pk_internal.h"
  36. #include "mbedtls/platform.h"
  37. #if defined(MBEDTLS_THREADING_C)
  38. #include "mbedtls/threading.h"
  39. #endif
  40. #if defined(MBEDTLS_HAVE_TIME)
  41. #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
  42. #ifndef WIN32_LEAN_AND_MEAN
  43. #define WIN32_LEAN_AND_MEAN
  44. #endif
  45. #include <windows.h>
  46. #else
  47. #include <time.h>
  48. #endif
  49. #endif
  50. #if defined(MBEDTLS_FS_IO)
  51. #include <stdio.h>
  52. #if !defined(_WIN32) || defined(EFIX64) || defined(EFI32)
  53. #include <sys/types.h>
  54. #include <sys/stat.h>
  55. #if defined(__MBED__)
  56. #include <platform/mbed_retarget.h>
  57. #else
  58. #include <dirent.h>
  59. #endif /* __MBED__ */
  60. #include <errno.h>
  61. #endif /* !_WIN32 || EFIX64 || EFI32 */
  62. #endif
  63. /*
  64. * Item in a verification chain: cert and flags for it
  65. */
  66. typedef struct {
  67. mbedtls_x509_crt *crt;
  68. uint32_t flags;
  69. } x509_crt_verify_chain_item;
  70. /*
  71. * Max size of verification chain: end-entity + intermediates + trusted root
  72. */
  73. #define X509_MAX_VERIFY_CHAIN_SIZE (MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2)
  74. /* Default profile. Do not remove items unless there are serious security
  75. * concerns. */
  76. const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default =
  77. {
  78. /* Hashes from SHA-256 and above. Note that this selection
  79. * should be aligned with ssl_preset_default_hashes in ssl_tls.c. */
  80. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256) |
  81. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) |
  82. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512),
  83. 0xFFFFFFF, /* Any PK alg */
  84. #if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
  85. /* Curves at or above 128-bit security level. Note that this selection
  86. * should be aligned with ssl_preset_default_curves in ssl_tls.c. */
  87. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_SECP256R1) |
  88. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_SECP384R1) |
  89. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_SECP521R1) |
  90. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_BP256R1) |
  91. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_BP384R1) |
  92. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_BP512R1) |
  93. 0,
  94. #else /* MBEDTLS_PK_HAVE_ECC_KEYS */
  95. 0,
  96. #endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
  97. 2048,
  98. };
  99. /* Next-generation profile. Currently identical to the default, but may
  100. * be tightened at any time. */
  101. const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next =
  102. {
  103. /* Hashes from SHA-256 and above. */
  104. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256) |
  105. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) |
  106. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512),
  107. 0xFFFFFFF, /* Any PK alg */
  108. #if defined(MBEDTLS_ECP_C)
  109. /* Curves at or above 128-bit security level. */
  110. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_SECP256R1) |
  111. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_SECP384R1) |
  112. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_SECP521R1) |
  113. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_BP256R1) |
  114. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_BP384R1) |
  115. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_BP512R1) |
  116. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_SECP256K1),
  117. #else
  118. 0,
  119. #endif
  120. 2048,
  121. };
  122. /*
  123. * NSA Suite B Profile
  124. */
  125. const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb =
  126. {
  127. /* Only SHA-256 and 384 */
  128. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256) |
  129. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384),
  130. /* Only ECDSA */
  131. MBEDTLS_X509_ID_FLAG(MBEDTLS_PK_ECDSA) |
  132. MBEDTLS_X509_ID_FLAG(MBEDTLS_PK_ECKEY),
  133. #if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
  134. /* Only NIST P-256 and P-384 */
  135. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_SECP256R1) |
  136. MBEDTLS_X509_ID_FLAG(MBEDTLS_ECP_DP_SECP384R1),
  137. #else /* MBEDTLS_PK_HAVE_ECC_KEYS */
  138. 0,
  139. #endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
  140. 0,
  141. };
  142. /*
  143. * Empty / all-forbidden profile
  144. */
  145. const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_none =
  146. {
  147. 0,
  148. 0,
  149. 0,
  150. (uint32_t) -1,
  151. };
  152. /*
  153. * Check md_alg against profile
  154. * Return 0 if md_alg is acceptable for this profile, -1 otherwise
  155. */
  156. static int x509_profile_check_md_alg(const mbedtls_x509_crt_profile *profile,
  157. mbedtls_md_type_t md_alg)
  158. {
  159. if (md_alg == MBEDTLS_MD_NONE) {
  160. return -1;
  161. }
  162. if ((profile->allowed_mds & MBEDTLS_X509_ID_FLAG(md_alg)) != 0) {
  163. return 0;
  164. }
  165. return -1;
  166. }
  167. /*
  168. * Check pk_alg against profile
  169. * Return 0 if pk_alg is acceptable for this profile, -1 otherwise
  170. */
  171. static int x509_profile_check_pk_alg(const mbedtls_x509_crt_profile *profile,
  172. mbedtls_pk_type_t pk_alg)
  173. {
  174. if (pk_alg == MBEDTLS_PK_NONE) {
  175. return -1;
  176. }
  177. if ((profile->allowed_pks & MBEDTLS_X509_ID_FLAG(pk_alg)) != 0) {
  178. return 0;
  179. }
  180. return -1;
  181. }
  182. /*
  183. * Check key against profile
  184. * Return 0 if pk is acceptable for this profile, -1 otherwise
  185. */
  186. static int x509_profile_check_key(const mbedtls_x509_crt_profile *profile,
  187. const mbedtls_pk_context *pk)
  188. {
  189. const mbedtls_pk_type_t pk_alg = mbedtls_pk_get_type(pk);
  190. #if defined(MBEDTLS_RSA_C)
  191. if (pk_alg == MBEDTLS_PK_RSA || pk_alg == MBEDTLS_PK_RSASSA_PSS) {
  192. if (mbedtls_pk_get_bitlen(pk) >= profile->rsa_min_bitlen) {
  193. return 0;
  194. }
  195. return -1;
  196. }
  197. #endif /* MBEDTLS_RSA_C */
  198. #if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
  199. if (pk_alg == MBEDTLS_PK_ECDSA ||
  200. pk_alg == MBEDTLS_PK_ECKEY ||
  201. pk_alg == MBEDTLS_PK_ECKEY_DH) {
  202. const mbedtls_ecp_group_id gid = mbedtls_pk_get_ec_group_id(pk);
  203. if (gid == MBEDTLS_ECP_DP_NONE) {
  204. return -1;
  205. }
  206. if ((profile->allowed_curves & MBEDTLS_X509_ID_FLAG(gid)) != 0) {
  207. return 0;
  208. }
  209. return -1;
  210. }
  211. #endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
  212. return -1;
  213. }
  214. /*
  215. * Like memcmp, but case-insensitive and always returns -1 if different
  216. */
  217. static int x509_memcasecmp(const void *s1, const void *s2, size_t len)
  218. {
  219. size_t i;
  220. unsigned char diff;
  221. const unsigned char *n1 = s1, *n2 = s2;
  222. for (i = 0; i < len; i++) {
  223. diff = n1[i] ^ n2[i];
  224. if (diff == 0) {
  225. continue;
  226. }
  227. if (diff == 32 &&
  228. ((n1[i] >= 'a' && n1[i] <= 'z') ||
  229. (n1[i] >= 'A' && n1[i] <= 'Z'))) {
  230. continue;
  231. }
  232. return -1;
  233. }
  234. return 0;
  235. }
  236. /*
  237. * Return 0 if name matches wildcard, -1 otherwise
  238. */
  239. static int x509_check_wildcard(const char *cn, const mbedtls_x509_buf *name)
  240. {
  241. size_t i;
  242. size_t cn_idx = 0, cn_len = strlen(cn);
  243. /* We can't have a match if there is no wildcard to match */
  244. if (name->len < 3 || name->p[0] != '*' || name->p[1] != '.') {
  245. return -1;
  246. }
  247. for (i = 0; i < cn_len; ++i) {
  248. if (cn[i] == '.') {
  249. cn_idx = i;
  250. break;
  251. }
  252. }
  253. if (cn_idx == 0) {
  254. return -1;
  255. }
  256. if (cn_len - cn_idx == name->len - 1 &&
  257. x509_memcasecmp(name->p + 1, cn + cn_idx, name->len - 1) == 0) {
  258. return 0;
  259. }
  260. return -1;
  261. }
  262. /*
  263. * Compare two X.509 strings, case-insensitive, and allowing for some encoding
  264. * variations (but not all).
  265. *
  266. * Return 0 if equal, -1 otherwise.
  267. */
  268. static int x509_string_cmp(const mbedtls_x509_buf *a, const mbedtls_x509_buf *b)
  269. {
  270. if (a->tag == b->tag &&
  271. a->len == b->len &&
  272. memcmp(a->p, b->p, b->len) == 0) {
  273. return 0;
  274. }
  275. if ((a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING) &&
  276. (b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING) &&
  277. a->len == b->len &&
  278. x509_memcasecmp(a->p, b->p, b->len) == 0) {
  279. return 0;
  280. }
  281. return -1;
  282. }
  283. /*
  284. * Compare two X.509 Names (aka rdnSequence).
  285. *
  286. * See RFC 5280 section 7.1, though we don't implement the whole algorithm:
  287. * we sometimes return unequal when the full algorithm would return equal,
  288. * but never the other way. (In particular, we don't do Unicode normalisation
  289. * or space folding.)
  290. *
  291. * Return 0 if equal, -1 otherwise.
  292. */
  293. static int x509_name_cmp(const mbedtls_x509_name *a, const mbedtls_x509_name *b)
  294. {
  295. /* Avoid recursion, it might not be optimised by the compiler */
  296. while (a != NULL || b != NULL) {
  297. if (a == NULL || b == NULL) {
  298. return -1;
  299. }
  300. /* type */
  301. if (a->oid.tag != b->oid.tag ||
  302. a->oid.len != b->oid.len ||
  303. memcmp(a->oid.p, b->oid.p, b->oid.len) != 0) {
  304. return -1;
  305. }
  306. /* value */
  307. if (x509_string_cmp(&a->val, &b->val) != 0) {
  308. return -1;
  309. }
  310. /* structure of the list of sets */
  311. if (a->next_merged != b->next_merged) {
  312. return -1;
  313. }
  314. a = a->next;
  315. b = b->next;
  316. }
  317. /* a == NULL == b */
  318. return 0;
  319. }
  320. /*
  321. * Reset (init or clear) a verify_chain
  322. */
  323. static void x509_crt_verify_chain_reset(
  324. mbedtls_x509_crt_verify_chain *ver_chain)
  325. {
  326. size_t i;
  327. for (i = 0; i < MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE; i++) {
  328. ver_chain->items[i].crt = NULL;
  329. ver_chain->items[i].flags = (uint32_t) -1;
  330. }
  331. ver_chain->len = 0;
  332. #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
  333. ver_chain->trust_ca_cb_result = NULL;
  334. #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
  335. }
  336. /*
  337. * Version ::= INTEGER { v1(0), v2(1), v3(2) }
  338. */
  339. static int x509_get_version(unsigned char **p,
  340. const unsigned char *end,
  341. int *ver)
  342. {
  343. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  344. size_t len;
  345. if ((ret = mbedtls_asn1_get_tag(p, end, &len,
  346. MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
  347. 0)) != 0) {
  348. if (ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
  349. *ver = 0;
  350. return 0;
  351. }
  352. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_FORMAT, ret);
  353. }
  354. end = *p + len;
  355. if ((ret = mbedtls_asn1_get_int(p, end, ver)) != 0) {
  356. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_VERSION, ret);
  357. }
  358. if (*p != end) {
  359. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_VERSION,
  360. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
  361. }
  362. return 0;
  363. }
  364. /*
  365. * Validity ::= SEQUENCE {
  366. * notBefore Time,
  367. * notAfter Time }
  368. */
  369. static int x509_get_dates(unsigned char **p,
  370. const unsigned char *end,
  371. mbedtls_x509_time *from,
  372. mbedtls_x509_time *to)
  373. {
  374. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  375. size_t len;
  376. if ((ret = mbedtls_asn1_get_tag(p, end, &len,
  377. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
  378. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_DATE, ret);
  379. }
  380. end = *p + len;
  381. if ((ret = mbedtls_x509_get_time(p, end, from)) != 0) {
  382. return ret;
  383. }
  384. if ((ret = mbedtls_x509_get_time(p, end, to)) != 0) {
  385. return ret;
  386. }
  387. if (*p != end) {
  388. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_DATE,
  389. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
  390. }
  391. return 0;
  392. }
  393. /*
  394. * X.509 v2/v3 unique identifier (not parsed)
  395. */
  396. static int x509_get_uid(unsigned char **p,
  397. const unsigned char *end,
  398. mbedtls_x509_buf *uid, int n)
  399. {
  400. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  401. if (*p == end) {
  402. return 0;
  403. }
  404. uid->tag = **p;
  405. if ((ret = mbedtls_asn1_get_tag(p, end, &uid->len,
  406. MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
  407. n)) != 0) {
  408. if (ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
  409. return 0;
  410. }
  411. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_FORMAT, ret);
  412. }
  413. uid->p = *p;
  414. *p += uid->len;
  415. return 0;
  416. }
  417. static int x509_get_basic_constraints(unsigned char **p,
  418. const unsigned char *end,
  419. int *ca_istrue,
  420. int *max_pathlen)
  421. {
  422. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  423. size_t len;
  424. /*
  425. * BasicConstraints ::= SEQUENCE {
  426. * cA BOOLEAN DEFAULT FALSE,
  427. * pathLenConstraint INTEGER (0..MAX) OPTIONAL }
  428. */
  429. *ca_istrue = 0; /* DEFAULT FALSE */
  430. *max_pathlen = 0; /* endless */
  431. if ((ret = mbedtls_asn1_get_tag(p, end, &len,
  432. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
  433. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  434. }
  435. if (*p == end) {
  436. return 0;
  437. }
  438. if ((ret = mbedtls_asn1_get_bool(p, end, ca_istrue)) != 0) {
  439. if (ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
  440. ret = mbedtls_asn1_get_int(p, end, ca_istrue);
  441. }
  442. if (ret != 0) {
  443. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  444. }
  445. if (*ca_istrue != 0) {
  446. *ca_istrue = 1;
  447. }
  448. }
  449. if (*p == end) {
  450. return 0;
  451. }
  452. if ((ret = mbedtls_asn1_get_int(p, end, max_pathlen)) != 0) {
  453. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  454. }
  455. if (*p != end) {
  456. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
  457. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
  458. }
  459. /* Do not accept max_pathlen equal to INT_MAX to avoid a signed integer
  460. * overflow, which is an undefined behavior. */
  461. if (*max_pathlen == INT_MAX) {
  462. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
  463. MBEDTLS_ERR_ASN1_INVALID_LENGTH);
  464. }
  465. (*max_pathlen)++;
  466. return 0;
  467. }
  468. /*
  469. * ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
  470. *
  471. * KeyPurposeId ::= OBJECT IDENTIFIER
  472. */
  473. static int x509_get_ext_key_usage(unsigned char **p,
  474. const unsigned char *end,
  475. mbedtls_x509_sequence *ext_key_usage)
  476. {
  477. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  478. if ((ret = mbedtls_asn1_get_sequence_of(p, end, ext_key_usage, MBEDTLS_ASN1_OID)) != 0) {
  479. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  480. }
  481. /* Sequence length must be >= 1 */
  482. if (ext_key_usage->buf.p == NULL) {
  483. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
  484. MBEDTLS_ERR_ASN1_INVALID_LENGTH);
  485. }
  486. return 0;
  487. }
  488. /*
  489. * SubjectKeyIdentifier ::= KeyIdentifier
  490. *
  491. * KeyIdentifier ::= OCTET STRING
  492. */
  493. static int x509_get_subject_key_id(unsigned char **p,
  494. const unsigned char *end,
  495. mbedtls_x509_buf *subject_key_id)
  496. {
  497. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  498. size_t len = 0u;
  499. if ((ret = mbedtls_asn1_get_tag(p, end, &len,
  500. MBEDTLS_ASN1_OCTET_STRING)) != 0) {
  501. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  502. }
  503. subject_key_id->len = len;
  504. subject_key_id->tag = MBEDTLS_ASN1_OCTET_STRING;
  505. subject_key_id->p = *p;
  506. *p += len;
  507. if (*p != end) {
  508. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
  509. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
  510. }
  511. return 0;
  512. }
  513. /*
  514. * AuthorityKeyIdentifier ::= SEQUENCE {
  515. * keyIdentifier [0] KeyIdentifier OPTIONAL,
  516. * authorityCertIssuer [1] GeneralNames OPTIONAL,
  517. * authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL }
  518. *
  519. * KeyIdentifier ::= OCTET STRING
  520. */
  521. static int x509_get_authority_key_id(unsigned char **p,
  522. unsigned char *end,
  523. mbedtls_x509_authority *authority_key_id)
  524. {
  525. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  526. size_t len = 0u;
  527. if ((ret = mbedtls_asn1_get_tag(p, end, &len,
  528. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
  529. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  530. }
  531. if (*p + len != end) {
  532. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
  533. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
  534. }
  535. ret = mbedtls_asn1_get_tag(p, end, &len,
  536. MBEDTLS_ASN1_CONTEXT_SPECIFIC);
  537. /* KeyIdentifier is an OPTIONAL field */
  538. if (ret == 0) {
  539. authority_key_id->keyIdentifier.len = len;
  540. authority_key_id->keyIdentifier.p = *p;
  541. /* Setting tag of the keyIdentfier intentionally to 0x04.
  542. * Although the .keyIdentfier field is CONTEXT_SPECIFIC ([0] OPTIONAL),
  543. * its tag with the content is the payload of on OCTET STRING primitive */
  544. authority_key_id->keyIdentifier.tag = MBEDTLS_ASN1_OCTET_STRING;
  545. *p += len;
  546. } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
  547. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  548. }
  549. if (*p < end) {
  550. /* Getting authorityCertIssuer using the required specific class tag [1] */
  551. if ((ret = mbedtls_asn1_get_tag(p, end, &len,
  552. MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
  553. 1)) != 0) {
  554. /* authorityCertIssuer and authorityCertSerialNumber MUST both
  555. be present or both be absent. At this point we expect to have both. */
  556. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  557. }
  558. /* "end" also includes the CertSerialNumber field so "len" shall be used */
  559. ret = mbedtls_x509_get_subject_alt_name_ext(p,
  560. (*p+len),
  561. &authority_key_id->authorityCertIssuer);
  562. if (ret != 0) {
  563. return ret;
  564. }
  565. /* Getting authorityCertSerialNumber using the required specific class tag [2] */
  566. if ((ret = mbedtls_asn1_get_tag(p, end, &len,
  567. MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2)) != 0) {
  568. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  569. }
  570. authority_key_id->authorityCertSerialNumber.len = len;
  571. authority_key_id->authorityCertSerialNumber.p = *p;
  572. authority_key_id->authorityCertSerialNumber.tag = MBEDTLS_ASN1_INTEGER;
  573. *p += len;
  574. }
  575. if (*p != end) {
  576. return MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  577. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
  578. }
  579. return 0;
  580. }
  581. /*
  582. * id-ce-certificatePolicies OBJECT IDENTIFIER ::= { id-ce 32 }
  583. *
  584. * anyPolicy OBJECT IDENTIFIER ::= { id-ce-certificatePolicies 0 }
  585. *
  586. * certificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation
  587. *
  588. * PolicyInformation ::= SEQUENCE {
  589. * policyIdentifier CertPolicyId,
  590. * policyQualifiers SEQUENCE SIZE (1..MAX) OF
  591. * PolicyQualifierInfo OPTIONAL }
  592. *
  593. * CertPolicyId ::= OBJECT IDENTIFIER
  594. *
  595. * PolicyQualifierInfo ::= SEQUENCE {
  596. * policyQualifierId PolicyQualifierId,
  597. * qualifier ANY DEFINED BY policyQualifierId }
  598. *
  599. * -- policyQualifierIds for Internet policy qualifiers
  600. *
  601. * id-qt OBJECT IDENTIFIER ::= { id-pkix 2 }
  602. * id-qt-cps OBJECT IDENTIFIER ::= { id-qt 1 }
  603. * id-qt-unotice OBJECT IDENTIFIER ::= { id-qt 2 }
  604. *
  605. * PolicyQualifierId ::= OBJECT IDENTIFIER ( id-qt-cps | id-qt-unotice )
  606. *
  607. * Qualifier ::= CHOICE {
  608. * cPSuri CPSuri,
  609. * userNotice UserNotice }
  610. *
  611. * CPSuri ::= IA5String
  612. *
  613. * UserNotice ::= SEQUENCE {
  614. * noticeRef NoticeReference OPTIONAL,
  615. * explicitText DisplayText OPTIONAL }
  616. *
  617. * NoticeReference ::= SEQUENCE {
  618. * organization DisplayText,
  619. * noticeNumbers SEQUENCE OF INTEGER }
  620. *
  621. * DisplayText ::= CHOICE {
  622. * ia5String IA5String (SIZE (1..200)),
  623. * visibleString VisibleString (SIZE (1..200)),
  624. * bmpString BMPString (SIZE (1..200)),
  625. * utf8String UTF8String (SIZE (1..200)) }
  626. *
  627. * NOTE: we only parse and use anyPolicy without qualifiers at this point
  628. * as defined in RFC 5280.
  629. */
  630. static int x509_get_certificate_policies(unsigned char **p,
  631. const unsigned char *end,
  632. mbedtls_x509_sequence *certificate_policies)
  633. {
  634. int ret, parse_ret = 0;
  635. size_t len;
  636. mbedtls_asn1_buf *buf;
  637. mbedtls_asn1_sequence *cur = certificate_policies;
  638. /* Get main sequence tag */
  639. ret = mbedtls_asn1_get_tag(p, end, &len,
  640. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
  641. if (ret != 0) {
  642. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  643. }
  644. if (*p + len != end) {
  645. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
  646. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
  647. }
  648. /*
  649. * Cannot be an empty sequence.
  650. */
  651. if (len == 0) {
  652. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
  653. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
  654. }
  655. while (*p < end) {
  656. mbedtls_x509_buf policy_oid;
  657. const unsigned char *policy_end;
  658. /*
  659. * Get the policy sequence
  660. */
  661. if ((ret = mbedtls_asn1_get_tag(p, end, &len,
  662. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
  663. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  664. }
  665. policy_end = *p + len;
  666. if ((ret = mbedtls_asn1_get_tag(p, policy_end, &len,
  667. MBEDTLS_ASN1_OID)) != 0) {
  668. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  669. }
  670. policy_oid.tag = MBEDTLS_ASN1_OID;
  671. policy_oid.len = len;
  672. policy_oid.p = *p;
  673. /*
  674. * Only AnyPolicy is currently supported when enforcing policy.
  675. */
  676. if (MBEDTLS_OID_CMP(MBEDTLS_OID_ANY_POLICY, &policy_oid) != 0) {
  677. /*
  678. * Set the parsing return code but continue parsing, in case this
  679. * extension is critical.
  680. */
  681. parse_ret = MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE;
  682. }
  683. /* Allocate and assign next pointer */
  684. if (cur->buf.p != NULL) {
  685. if (cur->next != NULL) {
  686. return MBEDTLS_ERR_X509_INVALID_EXTENSIONS;
  687. }
  688. cur->next = mbedtls_calloc(1, sizeof(mbedtls_asn1_sequence));
  689. if (cur->next == NULL) {
  690. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
  691. MBEDTLS_ERR_ASN1_ALLOC_FAILED);
  692. }
  693. cur = cur->next;
  694. }
  695. buf = &(cur->buf);
  696. buf->tag = policy_oid.tag;
  697. buf->p = policy_oid.p;
  698. buf->len = policy_oid.len;
  699. *p += len;
  700. /*
  701. * If there is an optional qualifier, then *p < policy_end
  702. * Check the Qualifier len to verify it doesn't exceed policy_end.
  703. */
  704. if (*p < policy_end) {
  705. if ((ret = mbedtls_asn1_get_tag(p, policy_end, &len,
  706. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) !=
  707. 0) {
  708. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  709. }
  710. /*
  711. * Skip the optional policy qualifiers.
  712. */
  713. *p += len;
  714. }
  715. if (*p != policy_end) {
  716. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
  717. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
  718. }
  719. }
  720. /* Set final sequence entry's next pointer to NULL */
  721. cur->next = NULL;
  722. if (*p != end) {
  723. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
  724. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
  725. }
  726. return parse_ret;
  727. }
  728. /*
  729. * X.509 v3 extensions
  730. *
  731. */
  732. static int x509_get_crt_ext(unsigned char **p,
  733. const unsigned char *end,
  734. mbedtls_x509_crt *crt,
  735. mbedtls_x509_crt_ext_cb_t cb,
  736. void *p_ctx)
  737. {
  738. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  739. size_t len;
  740. unsigned char *end_ext_data, *start_ext_octet, *end_ext_octet;
  741. if (*p == end) {
  742. return 0;
  743. }
  744. if ((ret = mbedtls_x509_get_ext(p, end, &crt->v3_ext, 3)) != 0) {
  745. return ret;
  746. }
  747. end = crt->v3_ext.p + crt->v3_ext.len;
  748. while (*p < end) {
  749. /*
  750. * Extension ::= SEQUENCE {
  751. * extnID OBJECT IDENTIFIER,
  752. * critical BOOLEAN DEFAULT FALSE,
  753. * extnValue OCTET STRING }
  754. */
  755. mbedtls_x509_buf extn_oid = { 0, 0, NULL };
  756. int is_critical = 0; /* DEFAULT FALSE */
  757. int ext_type = 0;
  758. if ((ret = mbedtls_asn1_get_tag(p, end, &len,
  759. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
  760. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  761. }
  762. end_ext_data = *p + len;
  763. /* Get extension ID */
  764. if ((ret = mbedtls_asn1_get_tag(p, end_ext_data, &extn_oid.len,
  765. MBEDTLS_ASN1_OID)) != 0) {
  766. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  767. }
  768. extn_oid.tag = MBEDTLS_ASN1_OID;
  769. extn_oid.p = *p;
  770. *p += extn_oid.len;
  771. /* Get optional critical */
  772. if ((ret = mbedtls_asn1_get_bool(p, end_ext_data, &is_critical)) != 0 &&
  773. (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG)) {
  774. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  775. }
  776. /* Data should be octet string type */
  777. if ((ret = mbedtls_asn1_get_tag(p, end_ext_data, &len,
  778. MBEDTLS_ASN1_OCTET_STRING)) != 0) {
  779. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
  780. }
  781. start_ext_octet = *p;
  782. end_ext_octet = *p + len;
  783. if (end_ext_octet != end_ext_data) {
  784. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
  785. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
  786. }
  787. /*
  788. * Detect supported extensions
  789. */
  790. ret = mbedtls_oid_get_x509_ext_type(&extn_oid, &ext_type);
  791. if (ret != 0) {
  792. /* Give the callback (if any) a chance to handle the extension */
  793. if (cb != NULL) {
  794. ret = cb(p_ctx, crt, &extn_oid, is_critical, *p, end_ext_octet);
  795. if (ret != 0 && is_critical) {
  796. return ret;
  797. }
  798. *p = end_ext_octet;
  799. continue;
  800. }
  801. /* No parser found, skip extension */
  802. *p = end_ext_octet;
  803. if (is_critical) {
  804. /* Data is marked as critical: fail */
  805. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
  806. MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
  807. }
  808. continue;
  809. }
  810. /* Forbid repeated extensions */
  811. if ((crt->ext_types & ext_type) != 0) {
  812. return MBEDTLS_ERR_X509_INVALID_EXTENSIONS;
  813. }
  814. crt->ext_types |= ext_type;
  815. switch (ext_type) {
  816. case MBEDTLS_X509_EXT_BASIC_CONSTRAINTS:
  817. /* Parse basic constraints */
  818. if ((ret = x509_get_basic_constraints(p, end_ext_octet,
  819. &crt->ca_istrue, &crt->max_pathlen)) != 0) {
  820. return ret;
  821. }
  822. break;
  823. case MBEDTLS_X509_EXT_KEY_USAGE:
  824. /* Parse key usage */
  825. if ((ret = mbedtls_x509_get_key_usage(p, end_ext_octet,
  826. &crt->key_usage)) != 0) {
  827. return ret;
  828. }
  829. break;
  830. case MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE:
  831. /* Parse extended key usage */
  832. if ((ret = x509_get_ext_key_usage(p, end_ext_octet,
  833. &crt->ext_key_usage)) != 0) {
  834. return ret;
  835. }
  836. break;
  837. case MBEDTLS_X509_EXT_SUBJECT_KEY_IDENTIFIER:
  838. /* Parse subject key identifier */
  839. if ((ret = x509_get_subject_key_id(p, end_ext_data,
  840. &crt->subject_key_id)) != 0) {
  841. return ret;
  842. }
  843. break;
  844. case MBEDTLS_X509_EXT_AUTHORITY_KEY_IDENTIFIER:
  845. /* Parse authority key identifier */
  846. if ((ret = x509_get_authority_key_id(p, end_ext_octet,
  847. &crt->authority_key_id)) != 0) {
  848. return ret;
  849. }
  850. break;
  851. case MBEDTLS_X509_EXT_SUBJECT_ALT_NAME:
  852. /* Parse subject alt name
  853. * SubjectAltName ::= GeneralNames
  854. */
  855. if ((ret = mbedtls_x509_get_subject_alt_name(p, end_ext_octet,
  856. &crt->subject_alt_names)) != 0) {
  857. return ret;
  858. }
  859. break;
  860. case MBEDTLS_X509_EXT_NS_CERT_TYPE:
  861. /* Parse netscape certificate type */
  862. if ((ret = mbedtls_x509_get_ns_cert_type(p, end_ext_octet,
  863. &crt->ns_cert_type)) != 0) {
  864. return ret;
  865. }
  866. break;
  867. case MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES:
  868. /* Parse certificate policies type */
  869. if ((ret = x509_get_certificate_policies(p, end_ext_octet,
  870. &crt->certificate_policies)) != 0) {
  871. /* Give the callback (if any) a chance to handle the extension
  872. * if it contains unsupported policies */
  873. if (ret == MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE && cb != NULL &&
  874. cb(p_ctx, crt, &extn_oid, is_critical,
  875. start_ext_octet, end_ext_octet) == 0) {
  876. break;
  877. }
  878. if (is_critical) {
  879. return ret;
  880. } else
  881. /*
  882. * If MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE is returned, then we
  883. * cannot interpret or enforce the policy. However, it is up to
  884. * the user to choose how to enforce the policies,
  885. * unless the extension is critical.
  886. */
  887. if (ret != MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE) {
  888. return ret;
  889. }
  890. }
  891. break;
  892. default:
  893. /*
  894. * If this is a non-critical extension, which the oid layer
  895. * supports, but there isn't an x509 parser for it,
  896. * skip the extension.
  897. */
  898. if (is_critical) {
  899. return MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE;
  900. } else {
  901. *p = end_ext_octet;
  902. }
  903. }
  904. }
  905. if (*p != end) {
  906. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
  907. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
  908. }
  909. return 0;
  910. }
  911. /*
  912. * Parse and fill a single X.509 certificate in DER format
  913. */
  914. static int x509_crt_parse_der_core(mbedtls_x509_crt *crt,
  915. const unsigned char *buf,
  916. size_t buflen,
  917. int make_copy,
  918. mbedtls_x509_crt_ext_cb_t cb,
  919. void *p_ctx)
  920. {
  921. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  922. size_t len;
  923. unsigned char *p, *end, *crt_end;
  924. mbedtls_x509_buf sig_params1, sig_params2, sig_oid2;
  925. memset(&sig_params1, 0, sizeof(mbedtls_x509_buf));
  926. memset(&sig_params2, 0, sizeof(mbedtls_x509_buf));
  927. memset(&sig_oid2, 0, sizeof(mbedtls_x509_buf));
  928. /*
  929. * Check for valid input
  930. */
  931. if (crt == NULL || buf == NULL) {
  932. return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
  933. }
  934. /* Use the original buffer until we figure out actual length. */
  935. p = (unsigned char *) buf;
  936. len = buflen;
  937. end = p + len;
  938. /*
  939. * Certificate ::= SEQUENCE {
  940. * tbsCertificate TBSCertificate,
  941. * signatureAlgorithm AlgorithmIdentifier,
  942. * signatureValue BIT STRING }
  943. */
  944. if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
  945. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
  946. mbedtls_x509_crt_free(crt);
  947. return MBEDTLS_ERR_X509_INVALID_FORMAT;
  948. }
  949. end = crt_end = p + len;
  950. crt->raw.len = (size_t) (crt_end - buf);
  951. if (make_copy != 0) {
  952. /* Create and populate a new buffer for the raw field. */
  953. crt->raw.p = p = mbedtls_calloc(1, crt->raw.len);
  954. if (crt->raw.p == NULL) {
  955. return MBEDTLS_ERR_X509_ALLOC_FAILED;
  956. }
  957. memcpy(crt->raw.p, buf, crt->raw.len);
  958. crt->own_buffer = 1;
  959. p += crt->raw.len - len;
  960. end = crt_end = p + len;
  961. } else {
  962. crt->raw.p = (unsigned char *) buf;
  963. crt->own_buffer = 0;
  964. }
  965. /*
  966. * TBSCertificate ::= SEQUENCE {
  967. */
  968. crt->tbs.p = p;
  969. if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
  970. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
  971. mbedtls_x509_crt_free(crt);
  972. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_FORMAT, ret);
  973. }
  974. end = p + len;
  975. crt->tbs.len = (size_t) (end - crt->tbs.p);
  976. /*
  977. * Version ::= INTEGER { v1(0), v2(1), v3(2) }
  978. *
  979. * CertificateSerialNumber ::= INTEGER
  980. *
  981. * signature AlgorithmIdentifier
  982. */
  983. if ((ret = x509_get_version(&p, end, &crt->version)) != 0 ||
  984. (ret = mbedtls_x509_get_serial(&p, end, &crt->serial)) != 0 ||
  985. (ret = mbedtls_x509_get_alg(&p, end, &crt->sig_oid,
  986. &sig_params1)) != 0) {
  987. mbedtls_x509_crt_free(crt);
  988. return ret;
  989. }
  990. if (crt->version < 0 || crt->version > 2) {
  991. mbedtls_x509_crt_free(crt);
  992. return MBEDTLS_ERR_X509_UNKNOWN_VERSION;
  993. }
  994. crt->version++;
  995. if ((ret = mbedtls_x509_get_sig_alg(&crt->sig_oid, &sig_params1,
  996. &crt->sig_md, &crt->sig_pk,
  997. &crt->sig_opts)) != 0) {
  998. mbedtls_x509_crt_free(crt);
  999. return ret;
  1000. }
  1001. /*
  1002. * issuer Name
  1003. */
  1004. crt->issuer_raw.p = p;
  1005. if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
  1006. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
  1007. mbedtls_x509_crt_free(crt);
  1008. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_FORMAT, ret);
  1009. }
  1010. if ((ret = mbedtls_x509_get_name(&p, p + len, &crt->issuer)) != 0) {
  1011. mbedtls_x509_crt_free(crt);
  1012. return ret;
  1013. }
  1014. crt->issuer_raw.len = (size_t) (p - crt->issuer_raw.p);
  1015. /*
  1016. * Validity ::= SEQUENCE {
  1017. * notBefore Time,
  1018. * notAfter Time }
  1019. *
  1020. */
  1021. if ((ret = x509_get_dates(&p, end, &crt->valid_from,
  1022. &crt->valid_to)) != 0) {
  1023. mbedtls_x509_crt_free(crt);
  1024. return ret;
  1025. }
  1026. /*
  1027. * subject Name
  1028. */
  1029. crt->subject_raw.p = p;
  1030. if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
  1031. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
  1032. mbedtls_x509_crt_free(crt);
  1033. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_FORMAT, ret);
  1034. }
  1035. if (len && (ret = mbedtls_x509_get_name(&p, p + len, &crt->subject)) != 0) {
  1036. mbedtls_x509_crt_free(crt);
  1037. return ret;
  1038. }
  1039. crt->subject_raw.len = (size_t) (p - crt->subject_raw.p);
  1040. /*
  1041. * SubjectPublicKeyInfo
  1042. */
  1043. crt->pk_raw.p = p;
  1044. if ((ret = mbedtls_pk_parse_subpubkey(&p, end, &crt->pk)) != 0) {
  1045. mbedtls_x509_crt_free(crt);
  1046. return ret;
  1047. }
  1048. crt->pk_raw.len = (size_t) (p - crt->pk_raw.p);
  1049. /*
  1050. * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
  1051. * -- If present, version shall be v2 or v3
  1052. * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
  1053. * -- If present, version shall be v2 or v3
  1054. * extensions [3] EXPLICIT Extensions OPTIONAL
  1055. * -- If present, version shall be v3
  1056. */
  1057. if (crt->version == 2 || crt->version == 3) {
  1058. ret = x509_get_uid(&p, end, &crt->issuer_id, 1);
  1059. if (ret != 0) {
  1060. mbedtls_x509_crt_free(crt);
  1061. return ret;
  1062. }
  1063. }
  1064. if (crt->version == 2 || crt->version == 3) {
  1065. ret = x509_get_uid(&p, end, &crt->subject_id, 2);
  1066. if (ret != 0) {
  1067. mbedtls_x509_crt_free(crt);
  1068. return ret;
  1069. }
  1070. }
  1071. if (crt->version == 3) {
  1072. ret = x509_get_crt_ext(&p, end, crt, cb, p_ctx);
  1073. if (ret != 0) {
  1074. mbedtls_x509_crt_free(crt);
  1075. return ret;
  1076. }
  1077. }
  1078. if (p != end) {
  1079. mbedtls_x509_crt_free(crt);
  1080. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_FORMAT,
  1081. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
  1082. }
  1083. end = crt_end;
  1084. /*
  1085. * }
  1086. * -- end of TBSCertificate
  1087. *
  1088. * signatureAlgorithm AlgorithmIdentifier,
  1089. * signatureValue BIT STRING
  1090. */
  1091. if ((ret = mbedtls_x509_get_alg(&p, end, &sig_oid2, &sig_params2)) != 0) {
  1092. mbedtls_x509_crt_free(crt);
  1093. return ret;
  1094. }
  1095. if (crt->sig_oid.len != sig_oid2.len ||
  1096. memcmp(crt->sig_oid.p, sig_oid2.p, crt->sig_oid.len) != 0 ||
  1097. sig_params1.tag != sig_params2.tag ||
  1098. sig_params1.len != sig_params2.len ||
  1099. (sig_params1.len != 0 &&
  1100. memcmp(sig_params1.p, sig_params2.p, sig_params1.len) != 0)) {
  1101. mbedtls_x509_crt_free(crt);
  1102. return MBEDTLS_ERR_X509_SIG_MISMATCH;
  1103. }
  1104. if ((ret = mbedtls_x509_get_sig(&p, end, &crt->sig)) != 0) {
  1105. mbedtls_x509_crt_free(crt);
  1106. return ret;
  1107. }
  1108. if (p != end) {
  1109. mbedtls_x509_crt_free(crt);
  1110. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_FORMAT,
  1111. MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
  1112. }
  1113. return 0;
  1114. }
  1115. /*
  1116. * Parse one X.509 certificate in DER format from a buffer and add them to a
  1117. * chained list
  1118. */
  1119. static int mbedtls_x509_crt_parse_der_internal(mbedtls_x509_crt *chain,
  1120. const unsigned char *buf,
  1121. size_t buflen,
  1122. int make_copy,
  1123. mbedtls_x509_crt_ext_cb_t cb,
  1124. void *p_ctx)
  1125. {
  1126. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1127. mbedtls_x509_crt *crt = chain, *prev = NULL;
  1128. /*
  1129. * Check for valid input
  1130. */
  1131. if (crt == NULL || buf == NULL) {
  1132. return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
  1133. }
  1134. while (crt->version != 0 && crt->next != NULL) {
  1135. prev = crt;
  1136. crt = crt->next;
  1137. }
  1138. /*
  1139. * Add new certificate on the end of the chain if needed.
  1140. */
  1141. if (crt->version != 0 && crt->next == NULL) {
  1142. crt->next = mbedtls_calloc(1, sizeof(mbedtls_x509_crt));
  1143. if (crt->next == NULL) {
  1144. return MBEDTLS_ERR_X509_ALLOC_FAILED;
  1145. }
  1146. prev = crt;
  1147. mbedtls_x509_crt_init(crt->next);
  1148. crt = crt->next;
  1149. }
  1150. ret = x509_crt_parse_der_core(crt, buf, buflen, make_copy, cb, p_ctx);
  1151. if (ret != 0) {
  1152. if (prev) {
  1153. prev->next = NULL;
  1154. }
  1155. if (crt != chain) {
  1156. mbedtls_free(crt);
  1157. }
  1158. return ret;
  1159. }
  1160. return 0;
  1161. }
  1162. int mbedtls_x509_crt_parse_der_nocopy(mbedtls_x509_crt *chain,
  1163. const unsigned char *buf,
  1164. size_t buflen)
  1165. {
  1166. return mbedtls_x509_crt_parse_der_internal(chain, buf, buflen, 0, NULL, NULL);
  1167. }
  1168. int mbedtls_x509_crt_parse_der_with_ext_cb(mbedtls_x509_crt *chain,
  1169. const unsigned char *buf,
  1170. size_t buflen,
  1171. int make_copy,
  1172. mbedtls_x509_crt_ext_cb_t cb,
  1173. void *p_ctx)
  1174. {
  1175. return mbedtls_x509_crt_parse_der_internal(chain, buf, buflen, make_copy, cb, p_ctx);
  1176. }
  1177. int mbedtls_x509_crt_parse_der(mbedtls_x509_crt *chain,
  1178. const unsigned char *buf,
  1179. size_t buflen)
  1180. {
  1181. return mbedtls_x509_crt_parse_der_internal(chain, buf, buflen, 1, NULL, NULL);
  1182. }
  1183. /*
  1184. * Parse one or more PEM certificates from a buffer and add them to the chained
  1185. * list
  1186. */
  1187. int mbedtls_x509_crt_parse(mbedtls_x509_crt *chain,
  1188. const unsigned char *buf,
  1189. size_t buflen)
  1190. {
  1191. #if defined(MBEDTLS_PEM_PARSE_C)
  1192. int success = 0, first_error = 0, total_failed = 0;
  1193. int buf_format = MBEDTLS_X509_FORMAT_DER;
  1194. #endif
  1195. /*
  1196. * Check for valid input
  1197. */
  1198. if (chain == NULL || buf == NULL) {
  1199. return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
  1200. }
  1201. /*
  1202. * Determine buffer content. Buffer contains either one DER certificate or
  1203. * one or more PEM certificates.
  1204. */
  1205. #if defined(MBEDTLS_PEM_PARSE_C)
  1206. if (buflen != 0 && buf[buflen - 1] == '\0' &&
  1207. strstr((const char *) buf, "-----BEGIN CERTIFICATE-----") != NULL) {
  1208. buf_format = MBEDTLS_X509_FORMAT_PEM;
  1209. }
  1210. if (buf_format == MBEDTLS_X509_FORMAT_DER) {
  1211. return mbedtls_x509_crt_parse_der(chain, buf, buflen);
  1212. }
  1213. #else
  1214. return mbedtls_x509_crt_parse_der(chain, buf, buflen);
  1215. #endif
  1216. #if defined(MBEDTLS_PEM_PARSE_C)
  1217. if (buf_format == MBEDTLS_X509_FORMAT_PEM) {
  1218. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1219. mbedtls_pem_context pem;
  1220. /* 1 rather than 0 since the terminating NULL byte is counted in */
  1221. while (buflen > 1) {
  1222. size_t use_len;
  1223. mbedtls_pem_init(&pem);
  1224. /* If we get there, we know the string is null-terminated */
  1225. ret = mbedtls_pem_read_buffer(&pem,
  1226. "-----BEGIN CERTIFICATE-----",
  1227. "-----END CERTIFICATE-----",
  1228. buf, NULL, 0, &use_len);
  1229. if (ret == 0) {
  1230. /*
  1231. * Was PEM encoded
  1232. */
  1233. buflen -= use_len;
  1234. buf += use_len;
  1235. } else if (ret == MBEDTLS_ERR_PEM_BAD_INPUT_DATA) {
  1236. return ret;
  1237. } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
  1238. mbedtls_pem_free(&pem);
  1239. /*
  1240. * PEM header and footer were found
  1241. */
  1242. buflen -= use_len;
  1243. buf += use_len;
  1244. if (first_error == 0) {
  1245. first_error = ret;
  1246. }
  1247. total_failed++;
  1248. continue;
  1249. } else {
  1250. break;
  1251. }
  1252. ret = mbedtls_x509_crt_parse_der(chain, pem.buf, pem.buflen);
  1253. mbedtls_pem_free(&pem);
  1254. if (ret != 0) {
  1255. /*
  1256. * Quit parsing on a memory error
  1257. */
  1258. if (ret == MBEDTLS_ERR_X509_ALLOC_FAILED) {
  1259. return ret;
  1260. }
  1261. if (first_error == 0) {
  1262. first_error = ret;
  1263. }
  1264. total_failed++;
  1265. continue;
  1266. }
  1267. success = 1;
  1268. }
  1269. }
  1270. if (success) {
  1271. return total_failed;
  1272. } else if (first_error) {
  1273. return first_error;
  1274. } else {
  1275. return MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT;
  1276. }
  1277. #endif /* MBEDTLS_PEM_PARSE_C */
  1278. }
  1279. #if defined(MBEDTLS_FS_IO)
  1280. /*
  1281. * Load one or more certificates and add them to the chained list
  1282. */
  1283. int mbedtls_x509_crt_parse_file(mbedtls_x509_crt *chain, const char *path)
  1284. {
  1285. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1286. size_t n;
  1287. unsigned char *buf;
  1288. if ((ret = mbedtls_pk_load_file(path, &buf, &n)) != 0) {
  1289. return ret;
  1290. }
  1291. ret = mbedtls_x509_crt_parse(chain, buf, n);
  1292. mbedtls_zeroize_and_free(buf, n);
  1293. return ret;
  1294. }
  1295. int mbedtls_x509_crt_parse_path(mbedtls_x509_crt *chain, const char *path)
  1296. {
  1297. int ret = 0;
  1298. #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
  1299. int w_ret;
  1300. WCHAR szDir[MAX_PATH];
  1301. char filename[MAX_PATH];
  1302. char *p;
  1303. size_t len = strlen(path);
  1304. WIN32_FIND_DATAW file_data;
  1305. HANDLE hFind;
  1306. if (len > MAX_PATH - 3) {
  1307. return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
  1308. }
  1309. memset(szDir, 0, sizeof(szDir));
  1310. memset(filename, 0, MAX_PATH);
  1311. memcpy(filename, path, len);
  1312. filename[len++] = '\\';
  1313. p = filename + len;
  1314. filename[len++] = '*';
  1315. /*
  1316. * Note this function uses the code page CP_ACP which is the system default
  1317. * ANSI codepage. The input string is always described in BYTES and the
  1318. * output length is described in WCHARs.
  1319. */
  1320. w_ret = MultiByteToWideChar(CP_ACP, 0, filename, (int) len, szDir,
  1321. MAX_PATH - 3);
  1322. if (w_ret == 0) {
  1323. return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
  1324. }
  1325. hFind = FindFirstFileW(szDir, &file_data);
  1326. if (hFind == INVALID_HANDLE_VALUE) {
  1327. return MBEDTLS_ERR_X509_FILE_IO_ERROR;
  1328. }
  1329. len = MAX_PATH - len;
  1330. do {
  1331. memset(p, 0, len);
  1332. if (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  1333. continue;
  1334. }
  1335. w_ret = WideCharToMultiByte(CP_ACP, 0, file_data.cFileName,
  1336. -1, p, (int) len, NULL, NULL);
  1337. if (w_ret == 0) {
  1338. ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
  1339. goto cleanup;
  1340. }
  1341. w_ret = mbedtls_x509_crt_parse_file(chain, filename);
  1342. if (w_ret < 0) {
  1343. ret++;
  1344. } else {
  1345. ret += w_ret;
  1346. }
  1347. } while (FindNextFileW(hFind, &file_data) != 0);
  1348. if (GetLastError() != ERROR_NO_MORE_FILES) {
  1349. ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
  1350. }
  1351. cleanup:
  1352. FindClose(hFind);
  1353. #else /* _WIN32 */
  1354. int t_ret;
  1355. int snp_ret;
  1356. struct stat sb;
  1357. struct dirent *entry;
  1358. char entry_name[MBEDTLS_X509_MAX_FILE_PATH_LEN];
  1359. DIR *dir = opendir(path);
  1360. if (dir == NULL) {
  1361. return MBEDTLS_ERR_X509_FILE_IO_ERROR;
  1362. }
  1363. #if defined(MBEDTLS_THREADING_C)
  1364. if ((ret = mbedtls_mutex_lock(&mbedtls_threading_readdir_mutex)) != 0) {
  1365. closedir(dir);
  1366. return ret;
  1367. }
  1368. #endif /* MBEDTLS_THREADING_C */
  1369. memset(&sb, 0, sizeof(sb));
  1370. while ((entry = readdir(dir)) != NULL) {
  1371. snp_ret = mbedtls_snprintf(entry_name, sizeof(entry_name),
  1372. "%s/%s", path, entry->d_name);
  1373. if (snp_ret < 0 || (size_t) snp_ret >= sizeof(entry_name)) {
  1374. ret = MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
  1375. goto cleanup;
  1376. } else if (stat(entry_name, &sb) == -1) {
  1377. if (errno == ENOENT) {
  1378. /* Broken symbolic link - ignore this entry.
  1379. stat(2) will return this error for either (a) a dangling
  1380. symlink or (b) a missing file.
  1381. Given that we have just obtained the filename from readdir,
  1382. assume that it does exist and therefore treat this as a
  1383. dangling symlink. */
  1384. continue;
  1385. } else {
  1386. /* Some other file error; report the error. */
  1387. ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
  1388. goto cleanup;
  1389. }
  1390. }
  1391. if (!S_ISREG(sb.st_mode)) {
  1392. continue;
  1393. }
  1394. // Ignore parse errors
  1395. //
  1396. t_ret = mbedtls_x509_crt_parse_file(chain, entry_name);
  1397. if (t_ret < 0) {
  1398. ret++;
  1399. } else {
  1400. ret += t_ret;
  1401. }
  1402. }
  1403. cleanup:
  1404. closedir(dir);
  1405. #if defined(MBEDTLS_THREADING_C)
  1406. if (mbedtls_mutex_unlock(&mbedtls_threading_readdir_mutex) != 0) {
  1407. ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR;
  1408. }
  1409. #endif /* MBEDTLS_THREADING_C */
  1410. #endif /* _WIN32 */
  1411. return ret;
  1412. }
  1413. #endif /* MBEDTLS_FS_IO */
  1414. #if !defined(MBEDTLS_X509_REMOVE_INFO)
  1415. #define PRINT_ITEM(i) \
  1416. do { \
  1417. ret = mbedtls_snprintf(p, n, "%s" i, sep); \
  1418. MBEDTLS_X509_SAFE_SNPRINTF; \
  1419. sep = ", "; \
  1420. } while (0)
  1421. #define CERT_TYPE(type, name) \
  1422. do { \
  1423. if (ns_cert_type & (type)) { \
  1424. PRINT_ITEM(name); \
  1425. } \
  1426. } while (0)
  1427. #define KEY_USAGE(code, name) \
  1428. do { \
  1429. if (key_usage & (code)) { \
  1430. PRINT_ITEM(name); \
  1431. } \
  1432. } while (0)
  1433. static int x509_info_ext_key_usage(char **buf, size_t *size,
  1434. const mbedtls_x509_sequence *extended_key_usage)
  1435. {
  1436. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1437. const char *desc;
  1438. size_t n = *size;
  1439. char *p = *buf;
  1440. const mbedtls_x509_sequence *cur = extended_key_usage;
  1441. const char *sep = "";
  1442. while (cur != NULL) {
  1443. if (mbedtls_oid_get_extended_key_usage(&cur->buf, &desc) != 0) {
  1444. desc = "???";
  1445. }
  1446. ret = mbedtls_snprintf(p, n, "%s%s", sep, desc);
  1447. MBEDTLS_X509_SAFE_SNPRINTF;
  1448. sep = ", ";
  1449. cur = cur->next;
  1450. }
  1451. *size = n;
  1452. *buf = p;
  1453. return 0;
  1454. }
  1455. static int x509_info_cert_policies(char **buf, size_t *size,
  1456. const mbedtls_x509_sequence *certificate_policies)
  1457. {
  1458. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1459. const char *desc;
  1460. size_t n = *size;
  1461. char *p = *buf;
  1462. const mbedtls_x509_sequence *cur = certificate_policies;
  1463. const char *sep = "";
  1464. while (cur != NULL) {
  1465. if (mbedtls_oid_get_certificate_policies(&cur->buf, &desc) != 0) {
  1466. desc = "???";
  1467. }
  1468. ret = mbedtls_snprintf(p, n, "%s%s", sep, desc);
  1469. MBEDTLS_X509_SAFE_SNPRINTF;
  1470. sep = ", ";
  1471. cur = cur->next;
  1472. }
  1473. *size = n;
  1474. *buf = p;
  1475. return 0;
  1476. }
  1477. /*
  1478. * Return an informational string about the certificate.
  1479. */
  1480. #define BEFORE_COLON 18
  1481. #define BC "18"
  1482. int mbedtls_x509_crt_info(char *buf, size_t size, const char *prefix,
  1483. const mbedtls_x509_crt *crt)
  1484. {
  1485. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1486. size_t n;
  1487. char *p;
  1488. char key_size_str[BEFORE_COLON];
  1489. p = buf;
  1490. n = size;
  1491. if (NULL == crt) {
  1492. ret = mbedtls_snprintf(p, n, "\nCertificate is uninitialised!\n");
  1493. MBEDTLS_X509_SAFE_SNPRINTF;
  1494. return (int) (size - n);
  1495. }
  1496. ret = mbedtls_snprintf(p, n, "%scert. version : %d\n",
  1497. prefix, crt->version);
  1498. MBEDTLS_X509_SAFE_SNPRINTF;
  1499. ret = mbedtls_snprintf(p, n, "%sserial number : ",
  1500. prefix);
  1501. MBEDTLS_X509_SAFE_SNPRINTF;
  1502. ret = mbedtls_x509_serial_gets(p, n, &crt->serial);
  1503. MBEDTLS_X509_SAFE_SNPRINTF;
  1504. ret = mbedtls_snprintf(p, n, "\n%sissuer name : ", prefix);
  1505. MBEDTLS_X509_SAFE_SNPRINTF;
  1506. ret = mbedtls_x509_dn_gets(p, n, &crt->issuer);
  1507. MBEDTLS_X509_SAFE_SNPRINTF;
  1508. ret = mbedtls_snprintf(p, n, "\n%ssubject name : ", prefix);
  1509. MBEDTLS_X509_SAFE_SNPRINTF;
  1510. ret = mbedtls_x509_dn_gets(p, n, &crt->subject);
  1511. MBEDTLS_X509_SAFE_SNPRINTF;
  1512. ret = mbedtls_snprintf(p, n, "\n%sissued on : " \
  1513. "%04d-%02d-%02d %02d:%02d:%02d", prefix,
  1514. crt->valid_from.year, crt->valid_from.mon,
  1515. crt->valid_from.day, crt->valid_from.hour,
  1516. crt->valid_from.min, crt->valid_from.sec);
  1517. MBEDTLS_X509_SAFE_SNPRINTF;
  1518. ret = mbedtls_snprintf(p, n, "\n%sexpires on : " \
  1519. "%04d-%02d-%02d %02d:%02d:%02d", prefix,
  1520. crt->valid_to.year, crt->valid_to.mon,
  1521. crt->valid_to.day, crt->valid_to.hour,
  1522. crt->valid_to.min, crt->valid_to.sec);
  1523. MBEDTLS_X509_SAFE_SNPRINTF;
  1524. ret = mbedtls_snprintf(p, n, "\n%ssigned using : ", prefix);
  1525. MBEDTLS_X509_SAFE_SNPRINTF;
  1526. ret = mbedtls_x509_sig_alg_gets(p, n, &crt->sig_oid, crt->sig_pk,
  1527. crt->sig_md, crt->sig_opts);
  1528. MBEDTLS_X509_SAFE_SNPRINTF;
  1529. /* Key size */
  1530. if ((ret = mbedtls_x509_key_size_helper(key_size_str, BEFORE_COLON,
  1531. mbedtls_pk_get_name(&crt->pk))) != 0) {
  1532. return ret;
  1533. }
  1534. ret = mbedtls_snprintf(p, n, "\n%s%-" BC "s: %d bits", prefix, key_size_str,
  1535. (int) mbedtls_pk_get_bitlen(&crt->pk));
  1536. MBEDTLS_X509_SAFE_SNPRINTF;
  1537. /*
  1538. * Optional extensions
  1539. */
  1540. if (crt->ext_types & MBEDTLS_X509_EXT_BASIC_CONSTRAINTS) {
  1541. ret = mbedtls_snprintf(p, n, "\n%sbasic constraints : CA=%s", prefix,
  1542. crt->ca_istrue ? "true" : "false");
  1543. MBEDTLS_X509_SAFE_SNPRINTF;
  1544. if (crt->max_pathlen > 0) {
  1545. ret = mbedtls_snprintf(p, n, ", max_pathlen=%d", crt->max_pathlen - 1);
  1546. MBEDTLS_X509_SAFE_SNPRINTF;
  1547. }
  1548. }
  1549. if (crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME) {
  1550. ret = mbedtls_snprintf(p, n, "\n%ssubject alt name :", prefix);
  1551. MBEDTLS_X509_SAFE_SNPRINTF;
  1552. if ((ret = mbedtls_x509_info_subject_alt_name(&p, &n,
  1553. &crt->subject_alt_names,
  1554. prefix)) != 0) {
  1555. return ret;
  1556. }
  1557. }
  1558. if (crt->ext_types & MBEDTLS_X509_EXT_NS_CERT_TYPE) {
  1559. ret = mbedtls_snprintf(p, n, "\n%scert. type : ", prefix);
  1560. MBEDTLS_X509_SAFE_SNPRINTF;
  1561. if ((ret = mbedtls_x509_info_cert_type(&p, &n, crt->ns_cert_type)) != 0) {
  1562. return ret;
  1563. }
  1564. }
  1565. if (crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE) {
  1566. ret = mbedtls_snprintf(p, n, "\n%skey usage : ", prefix);
  1567. MBEDTLS_X509_SAFE_SNPRINTF;
  1568. if ((ret = mbedtls_x509_info_key_usage(&p, &n, crt->key_usage)) != 0) {
  1569. return ret;
  1570. }
  1571. }
  1572. if (crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE) {
  1573. ret = mbedtls_snprintf(p, n, "\n%sext key usage : ", prefix);
  1574. MBEDTLS_X509_SAFE_SNPRINTF;
  1575. if ((ret = x509_info_ext_key_usage(&p, &n,
  1576. &crt->ext_key_usage)) != 0) {
  1577. return ret;
  1578. }
  1579. }
  1580. if (crt->ext_types & MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES) {
  1581. ret = mbedtls_snprintf(p, n, "\n%scertificate policies : ", prefix);
  1582. MBEDTLS_X509_SAFE_SNPRINTF;
  1583. if ((ret = x509_info_cert_policies(&p, &n,
  1584. &crt->certificate_policies)) != 0) {
  1585. return ret;
  1586. }
  1587. }
  1588. ret = mbedtls_snprintf(p, n, "\n");
  1589. MBEDTLS_X509_SAFE_SNPRINTF;
  1590. return (int) (size - n);
  1591. }
  1592. struct x509_crt_verify_string {
  1593. int code;
  1594. const char *string;
  1595. };
  1596. #define X509_CRT_ERROR_INFO(err, err_str, info) { err, info },
  1597. static const struct x509_crt_verify_string x509_crt_verify_strings[] = {
  1598. MBEDTLS_X509_CRT_ERROR_INFO_LIST
  1599. { 0, NULL }
  1600. };
  1601. #undef X509_CRT_ERROR_INFO
  1602. int mbedtls_x509_crt_verify_info(char *buf, size_t size, const char *prefix,
  1603. uint32_t flags)
  1604. {
  1605. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1606. const struct x509_crt_verify_string *cur;
  1607. char *p = buf;
  1608. size_t n = size;
  1609. for (cur = x509_crt_verify_strings; cur->string != NULL; cur++) {
  1610. if ((flags & cur->code) == 0) {
  1611. continue;
  1612. }
  1613. ret = mbedtls_snprintf(p, n, "%s%s\n", prefix, cur->string);
  1614. MBEDTLS_X509_SAFE_SNPRINTF;
  1615. flags ^= cur->code;
  1616. }
  1617. if (flags != 0) {
  1618. ret = mbedtls_snprintf(p, n, "%sUnknown reason "
  1619. "(this should not happen)\n", prefix);
  1620. MBEDTLS_X509_SAFE_SNPRINTF;
  1621. }
  1622. return (int) (size - n);
  1623. }
  1624. #endif /* MBEDTLS_X509_REMOVE_INFO */
  1625. int mbedtls_x509_crt_check_key_usage(const mbedtls_x509_crt *crt,
  1626. unsigned int usage)
  1627. {
  1628. unsigned int usage_must, usage_may;
  1629. unsigned int may_mask = MBEDTLS_X509_KU_ENCIPHER_ONLY
  1630. | MBEDTLS_X509_KU_DECIPHER_ONLY;
  1631. if ((crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE) == 0) {
  1632. return 0;
  1633. }
  1634. usage_must = usage & ~may_mask;
  1635. if (((crt->key_usage & ~may_mask) & usage_must) != usage_must) {
  1636. return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
  1637. }
  1638. usage_may = usage & may_mask;
  1639. if (((crt->key_usage & may_mask) | usage_may) != usage_may) {
  1640. return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
  1641. }
  1642. return 0;
  1643. }
  1644. int mbedtls_x509_crt_check_extended_key_usage(const mbedtls_x509_crt *crt,
  1645. const char *usage_oid,
  1646. size_t usage_len)
  1647. {
  1648. const mbedtls_x509_sequence *cur;
  1649. /* Extension is not mandatory, absent means no restriction */
  1650. if ((crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE) == 0) {
  1651. return 0;
  1652. }
  1653. /*
  1654. * Look for the requested usage (or wildcard ANY) in our list
  1655. */
  1656. for (cur = &crt->ext_key_usage; cur != NULL; cur = cur->next) {
  1657. const mbedtls_x509_buf *cur_oid = &cur->buf;
  1658. if (cur_oid->len == usage_len &&
  1659. memcmp(cur_oid->p, usage_oid, usage_len) == 0) {
  1660. return 0;
  1661. }
  1662. if (MBEDTLS_OID_CMP(MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE, cur_oid) == 0) {
  1663. return 0;
  1664. }
  1665. }
  1666. return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
  1667. }
  1668. #if defined(MBEDTLS_X509_CRL_PARSE_C)
  1669. /*
  1670. * Return 1 if the certificate is revoked, or 0 otherwise.
  1671. */
  1672. int mbedtls_x509_crt_is_revoked(const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl)
  1673. {
  1674. const mbedtls_x509_crl_entry *cur = &crl->entry;
  1675. while (cur != NULL && cur->serial.len != 0) {
  1676. if (crt->serial.len == cur->serial.len &&
  1677. memcmp(crt->serial.p, cur->serial.p, crt->serial.len) == 0) {
  1678. return 1;
  1679. }
  1680. cur = cur->next;
  1681. }
  1682. return 0;
  1683. }
  1684. /*
  1685. * Check that the given certificate is not revoked according to the CRL.
  1686. * Skip validation if no CRL for the given CA is present.
  1687. */
  1688. static int x509_crt_verifycrl(mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
  1689. mbedtls_x509_crl *crl_list,
  1690. const mbedtls_x509_crt_profile *profile,
  1691. const mbedtls_x509_time *now)
  1692. {
  1693. int flags = 0;
  1694. unsigned char hash[MBEDTLS_MD_MAX_SIZE];
  1695. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1696. psa_algorithm_t psa_algorithm;
  1697. #else
  1698. const mbedtls_md_info_t *md_info;
  1699. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1700. size_t hash_length;
  1701. if (ca == NULL) {
  1702. return flags;
  1703. }
  1704. while (crl_list != NULL) {
  1705. if (crl_list->version == 0 ||
  1706. x509_name_cmp(&crl_list->issuer, &ca->subject) != 0) {
  1707. crl_list = crl_list->next;
  1708. continue;
  1709. }
  1710. /*
  1711. * Check if the CA is configured to sign CRLs
  1712. */
  1713. if (mbedtls_x509_crt_check_key_usage(ca,
  1714. MBEDTLS_X509_KU_CRL_SIGN) != 0) {
  1715. flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
  1716. break;
  1717. }
  1718. /*
  1719. * Check if CRL is correctly signed by the trusted CA
  1720. */
  1721. if (x509_profile_check_md_alg(profile, crl_list->sig_md) != 0) {
  1722. flags |= MBEDTLS_X509_BADCRL_BAD_MD;
  1723. }
  1724. if (x509_profile_check_pk_alg(profile, crl_list->sig_pk) != 0) {
  1725. flags |= MBEDTLS_X509_BADCRL_BAD_PK;
  1726. }
  1727. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  1728. psa_algorithm = mbedtls_md_psa_alg_from_type(crl_list->sig_md);
  1729. if (psa_hash_compute(psa_algorithm,
  1730. crl_list->tbs.p,
  1731. crl_list->tbs.len,
  1732. hash,
  1733. sizeof(hash),
  1734. &hash_length) != PSA_SUCCESS) {
  1735. /* Note: this can't happen except after an internal error */
  1736. flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
  1737. break;
  1738. }
  1739. #else
  1740. md_info = mbedtls_md_info_from_type(crl_list->sig_md);
  1741. hash_length = mbedtls_md_get_size(md_info);
  1742. if (mbedtls_md(md_info,
  1743. crl_list->tbs.p,
  1744. crl_list->tbs.len,
  1745. hash) != 0) {
  1746. /* Note: this can't happen except after an internal error */
  1747. flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
  1748. break;
  1749. }
  1750. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1751. if (x509_profile_check_key(profile, &ca->pk) != 0) {
  1752. flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
  1753. }
  1754. if (mbedtls_pk_verify_ext(crl_list->sig_pk, crl_list->sig_opts, &ca->pk,
  1755. crl_list->sig_md, hash, hash_length,
  1756. crl_list->sig.p, crl_list->sig.len) != 0) {
  1757. flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
  1758. break;
  1759. }
  1760. #if defined(MBEDTLS_HAVE_TIME_DATE)
  1761. /*
  1762. * Check for validity of CRL (Do not drop out)
  1763. */
  1764. if (mbedtls_x509_time_cmp(&crl_list->next_update, now) < 0) {
  1765. flags |= MBEDTLS_X509_BADCRL_EXPIRED;
  1766. }
  1767. if (mbedtls_x509_time_cmp(&crl_list->this_update, now) > 0) {
  1768. flags |= MBEDTLS_X509_BADCRL_FUTURE;
  1769. }
  1770. #else
  1771. ((void) now);
  1772. #endif
  1773. /*
  1774. * Check if certificate is revoked
  1775. */
  1776. if (mbedtls_x509_crt_is_revoked(crt, crl_list)) {
  1777. flags |= MBEDTLS_X509_BADCERT_REVOKED;
  1778. break;
  1779. }
  1780. crl_list = crl_list->next;
  1781. }
  1782. return flags;
  1783. }
  1784. #endif /* MBEDTLS_X509_CRL_PARSE_C */
  1785. /*
  1786. * Check the signature of a certificate by its parent
  1787. */
  1788. static int x509_crt_check_signature(const mbedtls_x509_crt *child,
  1789. mbedtls_x509_crt *parent,
  1790. mbedtls_x509_crt_restart_ctx *rs_ctx)
  1791. {
  1792. size_t hash_len;
  1793. unsigned char hash[MBEDTLS_MD_MAX_SIZE];
  1794. #if !defined(MBEDTLS_USE_PSA_CRYPTO)
  1795. const mbedtls_md_info_t *md_info;
  1796. md_info = mbedtls_md_info_from_type(child->sig_md);
  1797. hash_len = mbedtls_md_get_size(md_info);
  1798. /* Note: hash errors can happen only after an internal error */
  1799. if (mbedtls_md(md_info, child->tbs.p, child->tbs.len, hash) != 0) {
  1800. return -1;
  1801. }
  1802. #else
  1803. psa_algorithm_t hash_alg = mbedtls_md_psa_alg_from_type(child->sig_md);
  1804. psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
  1805. status = psa_hash_compute(hash_alg,
  1806. child->tbs.p,
  1807. child->tbs.len,
  1808. hash,
  1809. sizeof(hash),
  1810. &hash_len);
  1811. if (status != PSA_SUCCESS) {
  1812. return MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
  1813. }
  1814. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  1815. /* Skip expensive computation on obvious mismatch */
  1816. if (!mbedtls_pk_can_do(&parent->pk, child->sig_pk)) {
  1817. return -1;
  1818. }
  1819. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  1820. if (rs_ctx != NULL && child->sig_pk == MBEDTLS_PK_ECDSA) {
  1821. return mbedtls_pk_verify_restartable(&parent->pk,
  1822. child->sig_md, hash, hash_len,
  1823. child->sig.p, child->sig.len, &rs_ctx->pk);
  1824. }
  1825. #else
  1826. (void) rs_ctx;
  1827. #endif
  1828. return mbedtls_pk_verify_ext(child->sig_pk, child->sig_opts, &parent->pk,
  1829. child->sig_md, hash, hash_len,
  1830. child->sig.p, child->sig.len);
  1831. }
  1832. /*
  1833. * Check if 'parent' is a suitable parent (signing CA) for 'child'.
  1834. * Return 0 if yes, -1 if not.
  1835. *
  1836. * top means parent is a locally-trusted certificate
  1837. */
  1838. static int x509_crt_check_parent(const mbedtls_x509_crt *child,
  1839. const mbedtls_x509_crt *parent,
  1840. int top)
  1841. {
  1842. int need_ca_bit;
  1843. /* Parent must be the issuer */
  1844. if (x509_name_cmp(&child->issuer, &parent->subject) != 0) {
  1845. return -1;
  1846. }
  1847. /* Parent must have the basicConstraints CA bit set as a general rule */
  1848. need_ca_bit = 1;
  1849. /* Exception: v1/v2 certificates that are locally trusted. */
  1850. if (top && parent->version < 3) {
  1851. need_ca_bit = 0;
  1852. }
  1853. if (need_ca_bit && !parent->ca_istrue) {
  1854. return -1;
  1855. }
  1856. if (need_ca_bit &&
  1857. mbedtls_x509_crt_check_key_usage(parent, MBEDTLS_X509_KU_KEY_CERT_SIGN) != 0) {
  1858. return -1;
  1859. }
  1860. return 0;
  1861. }
  1862. /*
  1863. * Find a suitable parent for child in candidates, or return NULL.
  1864. *
  1865. * Here suitable is defined as:
  1866. * 1. subject name matches child's issuer
  1867. * 2. if necessary, the CA bit is set and key usage allows signing certs
  1868. * 3. for trusted roots, the signature is correct
  1869. * (for intermediates, the signature is checked and the result reported)
  1870. * 4. pathlen constraints are satisfied
  1871. *
  1872. * If there's a suitable candidate which is also time-valid, return the first
  1873. * such. Otherwise, return the first suitable candidate (or NULL if there is
  1874. * none).
  1875. *
  1876. * The rationale for this rule is that someone could have a list of trusted
  1877. * roots with two versions on the same root with different validity periods.
  1878. * (At least one user reported having such a list and wanted it to just work.)
  1879. * The reason we don't just require time-validity is that generally there is
  1880. * only one version, and if it's expired we want the flags to state that
  1881. * rather than NOT_TRUSTED, as would be the case if we required it here.
  1882. *
  1883. * The rationale for rule 3 (signature for trusted roots) is that users might
  1884. * have two versions of the same CA with different keys in their list, and the
  1885. * way we select the correct one is by checking the signature (as we don't
  1886. * rely on key identifier extensions). (This is one way users might choose to
  1887. * handle key rollover, another relies on self-issued certs, see [SIRO].)
  1888. *
  1889. * Arguments:
  1890. * - [in] child: certificate for which we're looking for a parent
  1891. * - [in] candidates: chained list of potential parents
  1892. * - [out] r_parent: parent found (or NULL)
  1893. * - [out] r_signature_is_good: 1 if child signature by parent is valid, or 0
  1894. * - [in] top: 1 if candidates consists of trusted roots, ie we're at the top
  1895. * of the chain, 0 otherwise
  1896. * - [in] path_cnt: number of intermediates seen so far
  1897. * - [in] self_cnt: number of self-signed intermediates seen so far
  1898. * (will never be greater than path_cnt)
  1899. * - [in-out] rs_ctx: context for restarting operations
  1900. *
  1901. * Return value:
  1902. * - 0 on success
  1903. * - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise
  1904. */
  1905. static int x509_crt_find_parent_in(
  1906. mbedtls_x509_crt *child,
  1907. mbedtls_x509_crt *candidates,
  1908. mbedtls_x509_crt **r_parent,
  1909. int *r_signature_is_good,
  1910. int top,
  1911. unsigned path_cnt,
  1912. unsigned self_cnt,
  1913. mbedtls_x509_crt_restart_ctx *rs_ctx,
  1914. const mbedtls_x509_time *now)
  1915. {
  1916. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1917. mbedtls_x509_crt *parent, *fallback_parent;
  1918. int signature_is_good = 0, fallback_signature_is_good;
  1919. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  1920. /* did we have something in progress? */
  1921. if (rs_ctx != NULL && rs_ctx->parent != NULL) {
  1922. /* restore saved state */
  1923. parent = rs_ctx->parent;
  1924. fallback_parent = rs_ctx->fallback_parent;
  1925. fallback_signature_is_good = rs_ctx->fallback_signature_is_good;
  1926. /* clear saved state */
  1927. rs_ctx->parent = NULL;
  1928. rs_ctx->fallback_parent = NULL;
  1929. rs_ctx->fallback_signature_is_good = 0;
  1930. /* resume where we left */
  1931. goto check_signature;
  1932. }
  1933. #endif
  1934. fallback_parent = NULL;
  1935. fallback_signature_is_good = 0;
  1936. for (parent = candidates; parent != NULL; parent = parent->next) {
  1937. /* basic parenting skills (name, CA bit, key usage) */
  1938. if (x509_crt_check_parent(child, parent, top) != 0) {
  1939. continue;
  1940. }
  1941. /* +1 because stored max_pathlen is 1 higher that the actual value */
  1942. if (parent->max_pathlen > 0 &&
  1943. (size_t) parent->max_pathlen < 1 + path_cnt - self_cnt) {
  1944. continue;
  1945. }
  1946. /* Signature */
  1947. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  1948. check_signature:
  1949. #endif
  1950. ret = x509_crt_check_signature(child, parent, rs_ctx);
  1951. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  1952. if (rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
  1953. /* save state */
  1954. rs_ctx->parent = parent;
  1955. rs_ctx->fallback_parent = fallback_parent;
  1956. rs_ctx->fallback_signature_is_good = fallback_signature_is_good;
  1957. return ret;
  1958. }
  1959. #else
  1960. (void) ret;
  1961. #endif
  1962. signature_is_good = ret == 0;
  1963. if (top && !signature_is_good) {
  1964. continue;
  1965. }
  1966. #if defined(MBEDTLS_HAVE_TIME_DATE)
  1967. /* optional time check */
  1968. if (mbedtls_x509_time_cmp(&parent->valid_to, now) < 0 || /* past */
  1969. mbedtls_x509_time_cmp(&parent->valid_from, now) > 0) { /* future */
  1970. if (fallback_parent == NULL) {
  1971. fallback_parent = parent;
  1972. fallback_signature_is_good = signature_is_good;
  1973. }
  1974. continue;
  1975. }
  1976. #else
  1977. ((void) now);
  1978. #endif
  1979. *r_parent = parent;
  1980. *r_signature_is_good = signature_is_good;
  1981. break;
  1982. }
  1983. if (parent == NULL) {
  1984. *r_parent = fallback_parent;
  1985. *r_signature_is_good = fallback_signature_is_good;
  1986. }
  1987. return 0;
  1988. }
  1989. /*
  1990. * Find a parent in trusted CAs or the provided chain, or return NULL.
  1991. *
  1992. * Searches in trusted CAs first, and return the first suitable parent found
  1993. * (see find_parent_in() for definition of suitable).
  1994. *
  1995. * Arguments:
  1996. * - [in] child: certificate for which we're looking for a parent, followed
  1997. * by a chain of possible intermediates
  1998. * - [in] trust_ca: list of locally trusted certificates
  1999. * - [out] parent: parent found (or NULL)
  2000. * - [out] parent_is_trusted: 1 if returned `parent` is trusted, or 0
  2001. * - [out] signature_is_good: 1 if child signature by parent is valid, or 0
  2002. * - [in] path_cnt: number of links in the chain so far (EE -> ... -> child)
  2003. * - [in] self_cnt: number of self-signed certs in the chain so far
  2004. * (will always be no greater than path_cnt)
  2005. * - [in-out] rs_ctx: context for restarting operations
  2006. *
  2007. * Return value:
  2008. * - 0 on success
  2009. * - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise
  2010. */
  2011. static int x509_crt_find_parent(
  2012. mbedtls_x509_crt *child,
  2013. mbedtls_x509_crt *trust_ca,
  2014. mbedtls_x509_crt **parent,
  2015. int *parent_is_trusted,
  2016. int *signature_is_good,
  2017. unsigned path_cnt,
  2018. unsigned self_cnt,
  2019. mbedtls_x509_crt_restart_ctx *rs_ctx,
  2020. const mbedtls_x509_time *now)
  2021. {
  2022. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2023. mbedtls_x509_crt *search_list;
  2024. *parent_is_trusted = 1;
  2025. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2026. /* restore then clear saved state if we have some stored */
  2027. if (rs_ctx != NULL && rs_ctx->parent_is_trusted != -1) {
  2028. *parent_is_trusted = rs_ctx->parent_is_trusted;
  2029. rs_ctx->parent_is_trusted = -1;
  2030. }
  2031. #endif
  2032. while (1) {
  2033. search_list = *parent_is_trusted ? trust_ca : child->next;
  2034. ret = x509_crt_find_parent_in(child, search_list,
  2035. parent, signature_is_good,
  2036. *parent_is_trusted,
  2037. path_cnt, self_cnt, rs_ctx, now);
  2038. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2039. if (rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
  2040. /* save state */
  2041. rs_ctx->parent_is_trusted = *parent_is_trusted;
  2042. return ret;
  2043. }
  2044. #else
  2045. (void) ret;
  2046. #endif
  2047. /* stop here if found or already in second iteration */
  2048. if (*parent != NULL || *parent_is_trusted == 0) {
  2049. break;
  2050. }
  2051. /* prepare second iteration */
  2052. *parent_is_trusted = 0;
  2053. }
  2054. /* extra precaution against mistakes in the caller */
  2055. if (*parent == NULL) {
  2056. *parent_is_trusted = 0;
  2057. *signature_is_good = 0;
  2058. }
  2059. return 0;
  2060. }
  2061. /*
  2062. * Check if an end-entity certificate is locally trusted
  2063. *
  2064. * Currently we require such certificates to be self-signed (actually only
  2065. * check for self-issued as self-signatures are not checked)
  2066. */
  2067. static int x509_crt_check_ee_locally_trusted(
  2068. mbedtls_x509_crt *crt,
  2069. mbedtls_x509_crt *trust_ca)
  2070. {
  2071. mbedtls_x509_crt *cur;
  2072. /* must be self-issued */
  2073. if (x509_name_cmp(&crt->issuer, &crt->subject) != 0) {
  2074. return -1;
  2075. }
  2076. /* look for an exact match with trusted cert */
  2077. for (cur = trust_ca; cur != NULL; cur = cur->next) {
  2078. if (crt->raw.len == cur->raw.len &&
  2079. memcmp(crt->raw.p, cur->raw.p, crt->raw.len) == 0) {
  2080. return 0;
  2081. }
  2082. }
  2083. /* too bad */
  2084. return -1;
  2085. }
  2086. /*
  2087. * Build and verify a certificate chain
  2088. *
  2089. * Given a peer-provided list of certificates EE, C1, ..., Cn and
  2090. * a list of trusted certs R1, ... Rp, try to build and verify a chain
  2091. * EE, Ci1, ... Ciq [, Rj]
  2092. * such that every cert in the chain is a child of the next one,
  2093. * jumping to a trusted root as early as possible.
  2094. *
  2095. * Verify that chain and return it with flags for all issues found.
  2096. *
  2097. * Special cases:
  2098. * - EE == Rj -> return a one-element list containing it
  2099. * - EE, Ci1, ..., Ciq cannot be continued with a trusted root
  2100. * -> return that chain with NOT_TRUSTED set on Ciq
  2101. *
  2102. * Tests for (aspects of) this function should include at least:
  2103. * - trusted EE
  2104. * - EE -> trusted root
  2105. * - EE -> intermediate CA -> trusted root
  2106. * - if relevant: EE untrusted
  2107. * - if relevant: EE -> intermediate, untrusted
  2108. * with the aspect under test checked at each relevant level (EE, int, root).
  2109. * For some aspects longer chains are required, but usually length 2 is
  2110. * enough (but length 1 is not in general).
  2111. *
  2112. * Arguments:
  2113. * - [in] crt: the cert list EE, C1, ..., Cn
  2114. * - [in] trust_ca: the trusted list R1, ..., Rp
  2115. * - [in] ca_crl, profile: as in verify_with_profile()
  2116. * - [out] ver_chain: the built and verified chain
  2117. * Only valid when return value is 0, may contain garbage otherwise!
  2118. * Restart note: need not be the same when calling again to resume.
  2119. * - [in-out] rs_ctx: context for restarting operations
  2120. *
  2121. * Return value:
  2122. * - non-zero if the chain could not be fully built and examined
  2123. * - 0 is the chain was successfully built and examined,
  2124. * even if it was found to be invalid
  2125. */
  2126. static int x509_crt_verify_chain(
  2127. mbedtls_x509_crt *crt,
  2128. mbedtls_x509_crt *trust_ca,
  2129. mbedtls_x509_crl *ca_crl,
  2130. mbedtls_x509_crt_ca_cb_t f_ca_cb,
  2131. void *p_ca_cb,
  2132. const mbedtls_x509_crt_profile *profile,
  2133. mbedtls_x509_crt_verify_chain *ver_chain,
  2134. mbedtls_x509_crt_restart_ctx *rs_ctx)
  2135. {
  2136. /* Don't initialize any of those variables here, so that the compiler can
  2137. * catch potential issues with jumping ahead when restarting */
  2138. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2139. uint32_t *flags;
  2140. mbedtls_x509_crt_verify_chain_item *cur;
  2141. mbedtls_x509_crt *child;
  2142. mbedtls_x509_crt *parent;
  2143. int parent_is_trusted;
  2144. int child_is_trusted;
  2145. int signature_is_good;
  2146. unsigned self_cnt;
  2147. mbedtls_x509_crt *cur_trust_ca = NULL;
  2148. mbedtls_x509_time now;
  2149. #if defined(MBEDTLS_HAVE_TIME_DATE)
  2150. if (mbedtls_x509_time_gmtime(mbedtls_time(NULL), &now) != 0) {
  2151. return MBEDTLS_ERR_X509_FATAL_ERROR;
  2152. }
  2153. #endif
  2154. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2155. /* resume if we had an operation in progress */
  2156. if (rs_ctx != NULL && rs_ctx->in_progress == x509_crt_rs_find_parent) {
  2157. /* restore saved state */
  2158. *ver_chain = rs_ctx->ver_chain; /* struct copy */
  2159. self_cnt = rs_ctx->self_cnt;
  2160. /* restore derived state */
  2161. cur = &ver_chain->items[ver_chain->len - 1];
  2162. child = cur->crt;
  2163. flags = &cur->flags;
  2164. goto find_parent;
  2165. }
  2166. #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
  2167. child = crt;
  2168. self_cnt = 0;
  2169. parent_is_trusted = 0;
  2170. child_is_trusted = 0;
  2171. while (1) {
  2172. /* Add certificate to the verification chain */
  2173. cur = &ver_chain->items[ver_chain->len];
  2174. cur->crt = child;
  2175. cur->flags = 0;
  2176. ver_chain->len++;
  2177. flags = &cur->flags;
  2178. #if defined(MBEDTLS_HAVE_TIME_DATE)
  2179. /* Check time-validity (all certificates) */
  2180. if (mbedtls_x509_time_cmp(&child->valid_to, &now) < 0) {
  2181. *flags |= MBEDTLS_X509_BADCERT_EXPIRED;
  2182. }
  2183. if (mbedtls_x509_time_cmp(&child->valid_from, &now) > 0) {
  2184. *flags |= MBEDTLS_X509_BADCERT_FUTURE;
  2185. }
  2186. #endif
  2187. /* Stop here for trusted roots (but not for trusted EE certs) */
  2188. if (child_is_trusted) {
  2189. return 0;
  2190. }
  2191. /* Check signature algorithm: MD & PK algs */
  2192. if (x509_profile_check_md_alg(profile, child->sig_md) != 0) {
  2193. *flags |= MBEDTLS_X509_BADCERT_BAD_MD;
  2194. }
  2195. if (x509_profile_check_pk_alg(profile, child->sig_pk) != 0) {
  2196. *flags |= MBEDTLS_X509_BADCERT_BAD_PK;
  2197. }
  2198. /* Special case: EE certs that are locally trusted */
  2199. if (ver_chain->len == 1 &&
  2200. x509_crt_check_ee_locally_trusted(child, trust_ca) == 0) {
  2201. return 0;
  2202. }
  2203. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2204. find_parent:
  2205. #endif
  2206. /* Obtain list of potential trusted signers from CA callback,
  2207. * or use statically provided list. */
  2208. #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
  2209. if (f_ca_cb != NULL) {
  2210. mbedtls_x509_crt_free(ver_chain->trust_ca_cb_result);
  2211. mbedtls_free(ver_chain->trust_ca_cb_result);
  2212. ver_chain->trust_ca_cb_result = NULL;
  2213. ret = f_ca_cb(p_ca_cb, child, &ver_chain->trust_ca_cb_result);
  2214. if (ret != 0) {
  2215. return MBEDTLS_ERR_X509_FATAL_ERROR;
  2216. }
  2217. cur_trust_ca = ver_chain->trust_ca_cb_result;
  2218. } else
  2219. #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
  2220. {
  2221. ((void) f_ca_cb);
  2222. ((void) p_ca_cb);
  2223. cur_trust_ca = trust_ca;
  2224. }
  2225. /* Look for a parent in trusted CAs or up the chain */
  2226. ret = x509_crt_find_parent(child, cur_trust_ca, &parent,
  2227. &parent_is_trusted, &signature_is_good,
  2228. ver_chain->len - 1, self_cnt, rs_ctx,
  2229. &now);
  2230. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2231. if (rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
  2232. /* save state */
  2233. rs_ctx->in_progress = x509_crt_rs_find_parent;
  2234. rs_ctx->self_cnt = self_cnt;
  2235. rs_ctx->ver_chain = *ver_chain; /* struct copy */
  2236. return ret;
  2237. }
  2238. #else
  2239. (void) ret;
  2240. #endif
  2241. /* No parent? We're done here */
  2242. if (parent == NULL) {
  2243. *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
  2244. return 0;
  2245. }
  2246. /* Count intermediate self-issued (not necessarily self-signed) certs.
  2247. * These can occur with some strategies for key rollover, see [SIRO],
  2248. * and should be excluded from max_pathlen checks. */
  2249. if (ver_chain->len != 1 &&
  2250. x509_name_cmp(&child->issuer, &child->subject) == 0) {
  2251. self_cnt++;
  2252. }
  2253. /* path_cnt is 0 for the first intermediate CA,
  2254. * and if parent is trusted it's not an intermediate CA */
  2255. if (!parent_is_trusted &&
  2256. ver_chain->len > MBEDTLS_X509_MAX_INTERMEDIATE_CA) {
  2257. /* return immediately to avoid overflow the chain array */
  2258. return MBEDTLS_ERR_X509_FATAL_ERROR;
  2259. }
  2260. /* signature was checked while searching parent */
  2261. if (!signature_is_good) {
  2262. *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
  2263. }
  2264. /* check size of signing key */
  2265. if (x509_profile_check_key(profile, &parent->pk) != 0) {
  2266. *flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
  2267. }
  2268. #if defined(MBEDTLS_X509_CRL_PARSE_C)
  2269. /* Check trusted CA's CRL for the given crt */
  2270. *flags |= x509_crt_verifycrl(child, parent, ca_crl, profile, &now);
  2271. #else
  2272. (void) ca_crl;
  2273. #endif
  2274. /* prepare for next iteration */
  2275. child = parent;
  2276. parent = NULL;
  2277. child_is_trusted = parent_is_trusted;
  2278. signature_is_good = 0;
  2279. }
  2280. }
  2281. #ifdef _WIN32
  2282. #ifdef _MSC_VER
  2283. #pragma comment(lib, "ws2_32.lib")
  2284. #include <winsock2.h>
  2285. #include <ws2tcpip.h>
  2286. #elif (defined(__MINGW32__) || defined(__MINGW64__)) && _WIN32_WINNT >= 0x0600
  2287. #include <winsock2.h>
  2288. #include <ws2tcpip.h>
  2289. #else
  2290. /* inet_pton() is not supported, fallback to software version */
  2291. #define MBEDTLS_TEST_SW_INET_PTON
  2292. #endif
  2293. #elif defined(__sun)
  2294. /* Solaris requires -lsocket -lnsl for inet_pton() */
  2295. #elif defined(__has_include)
  2296. #if __has_include(<sys/socket.h>)
  2297. #include <sys/socket.h>
  2298. #endif
  2299. #if __has_include(<arpa/inet.h>)
  2300. #include <arpa/inet.h>
  2301. #endif
  2302. #endif
  2303. /* Use whether or not AF_INET6 is defined to indicate whether or not to use
  2304. * the platform inet_pton() or a local implementation (below). The local
  2305. * implementation may be used even in cases where the platform provides
  2306. * inet_pton(), e.g. when there are different includes required and/or the
  2307. * platform implementation requires dependencies on additional libraries.
  2308. * Specifically, Windows requires custom includes and additional link
  2309. * dependencies, and Solaris requires additional link dependencies.
  2310. * Also, as a coarse heuristic, use the local implementation if the compiler
  2311. * does not support __has_include(), or if the definition of AF_INET6 is not
  2312. * provided by headers included (or not) via __has_include() above.
  2313. * MBEDTLS_TEST_SW_INET_PTON is a bypass define to force testing of this code //no-check-names
  2314. * despite having a platform that has inet_pton. */
  2315. #if !defined(AF_INET6) || defined(MBEDTLS_TEST_SW_INET_PTON) //no-check-names
  2316. /* Definition located further below to possibly reduce compiler inlining */
  2317. static int x509_inet_pton_ipv4(const char *src, void *dst);
  2318. #define li_cton(c, n) \
  2319. (((n) = (c) - '0') <= 9 || (((n) = ((c)&0xdf) - 'A') <= 5 ? ((n) += 10) : 0))
  2320. static int x509_inet_pton_ipv6(const char *src, void *dst)
  2321. {
  2322. const unsigned char *p = (const unsigned char *) src;
  2323. int nonzero_groups = 0, num_digits, zero_group_start = -1;
  2324. uint16_t addr[8];
  2325. do {
  2326. /* note: allows excess leading 0's, e.g. 1:0002:3:... */
  2327. uint16_t group = num_digits = 0;
  2328. for (uint8_t digit; num_digits < 4; num_digits++) {
  2329. if (li_cton(*p, digit) == 0) {
  2330. break;
  2331. }
  2332. group = (group << 4) | digit;
  2333. p++;
  2334. }
  2335. if (num_digits != 0) {
  2336. MBEDTLS_PUT_UINT16_BE(group, addr, nonzero_groups);
  2337. nonzero_groups++;
  2338. if (*p == '\0') {
  2339. break;
  2340. } else if (*p == '.') {
  2341. /* Don't accept IPv4 too early or late */
  2342. if ((nonzero_groups == 0 && zero_group_start == -1) ||
  2343. nonzero_groups >= 7) {
  2344. break;
  2345. }
  2346. /* Walk back to prior ':', then parse as IPv4-mapped */
  2347. int steps = 4;
  2348. do {
  2349. p--;
  2350. steps--;
  2351. } while (*p != ':' && steps > 0);
  2352. if (*p != ':') {
  2353. break;
  2354. }
  2355. p++;
  2356. nonzero_groups--;
  2357. if (x509_inet_pton_ipv4((const char *) p,
  2358. addr + nonzero_groups) != 0) {
  2359. break;
  2360. }
  2361. nonzero_groups += 2;
  2362. p = (const unsigned char *) "";
  2363. break;
  2364. } else if (*p != ':') {
  2365. return -1;
  2366. }
  2367. } else {
  2368. /* Don't accept a second zero group or an invalid delimiter */
  2369. if (zero_group_start != -1 || *p != ':') {
  2370. return -1;
  2371. }
  2372. zero_group_start = nonzero_groups;
  2373. /* Accept a zero group at start, but it has to be a double colon */
  2374. if (zero_group_start == 0 && *++p != ':') {
  2375. return -1;
  2376. }
  2377. if (p[1] == '\0') {
  2378. ++p;
  2379. break;
  2380. }
  2381. }
  2382. ++p;
  2383. } while (nonzero_groups < 8);
  2384. if (*p != '\0') {
  2385. return -1;
  2386. }
  2387. if (zero_group_start != -1) {
  2388. if (nonzero_groups > 6) {
  2389. return -1;
  2390. }
  2391. int zero_groups = 8 - nonzero_groups;
  2392. int groups_after_zero = nonzero_groups - zero_group_start;
  2393. /* Move the non-zero part to after the zeroes */
  2394. if (groups_after_zero) {
  2395. memmove(addr + zero_group_start + zero_groups,
  2396. addr + zero_group_start,
  2397. groups_after_zero * sizeof(*addr));
  2398. }
  2399. memset(addr + zero_group_start, 0, zero_groups * sizeof(*addr));
  2400. } else {
  2401. if (nonzero_groups != 8) {
  2402. return -1;
  2403. }
  2404. }
  2405. memcpy(dst, addr, sizeof(addr));
  2406. return 0;
  2407. }
  2408. static int x509_inet_pton_ipv4(const char *src, void *dst)
  2409. {
  2410. const unsigned char *p = (const unsigned char *) src;
  2411. uint8_t *res = (uint8_t *) dst;
  2412. uint8_t digit, num_digits = 0;
  2413. uint8_t num_octets = 0;
  2414. uint16_t octet;
  2415. do {
  2416. octet = num_digits = 0;
  2417. do {
  2418. digit = *p - '0';
  2419. if (digit > 9) {
  2420. break;
  2421. }
  2422. /* Don't allow leading zeroes. These might mean octal format,
  2423. * which this implementation does not support. */
  2424. if (octet == 0 && num_digits > 0) {
  2425. return -1;
  2426. }
  2427. octet = octet * 10 + digit;
  2428. num_digits++;
  2429. p++;
  2430. } while (num_digits < 3);
  2431. if (octet >= 256 || num_digits > 3 || num_digits == 0) {
  2432. return -1;
  2433. }
  2434. *res++ = (uint8_t) octet;
  2435. num_octets++;
  2436. } while (num_octets < 4 && *p++ == '.');
  2437. return num_octets == 4 && *p == '\0' ? 0 : -1;
  2438. }
  2439. #else
  2440. static int x509_inet_pton_ipv6(const char *src, void *dst)
  2441. {
  2442. return inet_pton(AF_INET6, src, dst) == 1 ? 0 : -1;
  2443. }
  2444. static int x509_inet_pton_ipv4(const char *src, void *dst)
  2445. {
  2446. return inet_pton(AF_INET, src, dst) == 1 ? 0 : -1;
  2447. }
  2448. #endif /* !AF_INET6 || MBEDTLS_TEST_SW_INET_PTON */ //no-check-names
  2449. size_t mbedtls_x509_crt_parse_cn_inet_pton(const char *cn, void *dst)
  2450. {
  2451. return strchr(cn, ':') == NULL
  2452. ? x509_inet_pton_ipv4(cn, dst) == 0 ? 4 : 0
  2453. : x509_inet_pton_ipv6(cn, dst) == 0 ? 16 : 0;
  2454. }
  2455. /*
  2456. * Check for CN match
  2457. */
  2458. static int x509_crt_check_cn(const mbedtls_x509_buf *name,
  2459. const char *cn, size_t cn_len)
  2460. {
  2461. /* try exact match */
  2462. if (name->len == cn_len &&
  2463. x509_memcasecmp(cn, name->p, cn_len) == 0) {
  2464. return 0;
  2465. }
  2466. /* try wildcard match */
  2467. if (x509_check_wildcard(cn, name) == 0) {
  2468. return 0;
  2469. }
  2470. return -1;
  2471. }
  2472. static int x509_crt_check_san_ip(const mbedtls_x509_sequence *san,
  2473. const char *cn, size_t cn_len)
  2474. {
  2475. uint32_t ip[4];
  2476. cn_len = mbedtls_x509_crt_parse_cn_inet_pton(cn, ip);
  2477. if (cn_len == 0) {
  2478. return -1;
  2479. }
  2480. for (const mbedtls_x509_sequence *cur = san; cur != NULL; cur = cur->next) {
  2481. const unsigned char san_type = (unsigned char) cur->buf.tag &
  2482. MBEDTLS_ASN1_TAG_VALUE_MASK;
  2483. if (san_type == MBEDTLS_X509_SAN_IP_ADDRESS &&
  2484. cur->buf.len == cn_len && memcmp(cur->buf.p, ip, cn_len) == 0) {
  2485. return 0;
  2486. }
  2487. }
  2488. return -1;
  2489. }
  2490. static int x509_crt_check_san_uri(const mbedtls_x509_sequence *san,
  2491. const char *cn, size_t cn_len)
  2492. {
  2493. for (const mbedtls_x509_sequence *cur = san; cur != NULL; cur = cur->next) {
  2494. const unsigned char san_type = (unsigned char) cur->buf.tag &
  2495. MBEDTLS_ASN1_TAG_VALUE_MASK;
  2496. if (san_type == MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER &&
  2497. cur->buf.len == cn_len && memcmp(cur->buf.p, cn, cn_len) == 0) {
  2498. return 0;
  2499. }
  2500. }
  2501. return -1;
  2502. }
  2503. /*
  2504. * Check for SAN match, see RFC 5280 Section 4.2.1.6
  2505. */
  2506. static int x509_crt_check_san(const mbedtls_x509_sequence *san,
  2507. const char *cn, size_t cn_len)
  2508. {
  2509. int san_ip = 0;
  2510. int san_uri = 0;
  2511. /* Prioritize DNS name over other subtypes due to popularity */
  2512. for (const mbedtls_x509_sequence *cur = san; cur != NULL; cur = cur->next) {
  2513. switch ((unsigned char) cur->buf.tag & MBEDTLS_ASN1_TAG_VALUE_MASK) {
  2514. case MBEDTLS_X509_SAN_DNS_NAME:
  2515. if (x509_crt_check_cn(&cur->buf, cn, cn_len) == 0) {
  2516. return 0;
  2517. }
  2518. break;
  2519. case MBEDTLS_X509_SAN_IP_ADDRESS:
  2520. san_ip = 1;
  2521. break;
  2522. case MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER:
  2523. san_uri = 1;
  2524. break;
  2525. /* (We may handle other types here later.) */
  2526. default: /* Unrecognized type */
  2527. break;
  2528. }
  2529. }
  2530. if (san_ip) {
  2531. if (x509_crt_check_san_ip(san, cn, cn_len) == 0) {
  2532. return 0;
  2533. }
  2534. }
  2535. if (san_uri) {
  2536. if (x509_crt_check_san_uri(san, cn, cn_len) == 0) {
  2537. return 0;
  2538. }
  2539. }
  2540. return -1;
  2541. }
  2542. /*
  2543. * Verify the requested CN - only call this if cn is not NULL!
  2544. */
  2545. static void x509_crt_verify_name(const mbedtls_x509_crt *crt,
  2546. const char *cn,
  2547. uint32_t *flags)
  2548. {
  2549. const mbedtls_x509_name *name;
  2550. size_t cn_len = strlen(cn);
  2551. if (crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME) {
  2552. if (x509_crt_check_san(&crt->subject_alt_names, cn, cn_len) == 0) {
  2553. return;
  2554. }
  2555. } else {
  2556. for (name = &crt->subject; name != NULL; name = name->next) {
  2557. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0 &&
  2558. x509_crt_check_cn(&name->val, cn, cn_len) == 0) {
  2559. return;
  2560. }
  2561. }
  2562. }
  2563. *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
  2564. }
  2565. /*
  2566. * Merge the flags for all certs in the chain, after calling callback
  2567. */
  2568. static int x509_crt_merge_flags_with_cb(
  2569. uint32_t *flags,
  2570. const mbedtls_x509_crt_verify_chain *ver_chain,
  2571. int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  2572. void *p_vrfy)
  2573. {
  2574. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2575. unsigned i;
  2576. uint32_t cur_flags;
  2577. const mbedtls_x509_crt_verify_chain_item *cur;
  2578. for (i = ver_chain->len; i != 0; --i) {
  2579. cur = &ver_chain->items[i-1];
  2580. cur_flags = cur->flags;
  2581. if (NULL != f_vrfy) {
  2582. if ((ret = f_vrfy(p_vrfy, cur->crt, (int) i-1, &cur_flags)) != 0) {
  2583. return ret;
  2584. }
  2585. }
  2586. *flags |= cur_flags;
  2587. }
  2588. return 0;
  2589. }
  2590. /*
  2591. * Verify the certificate validity, with profile, restartable version
  2592. *
  2593. * This function:
  2594. * - checks the requested CN (if any)
  2595. * - checks the type and size of the EE cert's key,
  2596. * as that isn't done as part of chain building/verification currently
  2597. * - builds and verifies the chain
  2598. * - then calls the callback and merges the flags
  2599. *
  2600. * The parameters pairs `trust_ca`, `ca_crl` and `f_ca_cb`, `p_ca_cb`
  2601. * are mutually exclusive: If `f_ca_cb != NULL`, it will be used by the
  2602. * verification routine to search for trusted signers, and CRLs will
  2603. * be disabled. Otherwise, `trust_ca` will be used as the static list
  2604. * of trusted signers, and `ca_crl` will be use as the static list
  2605. * of CRLs.
  2606. */
  2607. static int x509_crt_verify_restartable_ca_cb(mbedtls_x509_crt *crt,
  2608. mbedtls_x509_crt *trust_ca,
  2609. mbedtls_x509_crl *ca_crl,
  2610. mbedtls_x509_crt_ca_cb_t f_ca_cb,
  2611. void *p_ca_cb,
  2612. const mbedtls_x509_crt_profile *profile,
  2613. const char *cn, uint32_t *flags,
  2614. int (*f_vrfy)(void *,
  2615. mbedtls_x509_crt *,
  2616. int,
  2617. uint32_t *),
  2618. void *p_vrfy,
  2619. mbedtls_x509_crt_restart_ctx *rs_ctx)
  2620. {
  2621. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2622. mbedtls_pk_type_t pk_type;
  2623. mbedtls_x509_crt_verify_chain ver_chain;
  2624. uint32_t ee_flags;
  2625. *flags = 0;
  2626. ee_flags = 0;
  2627. x509_crt_verify_chain_reset(&ver_chain);
  2628. if (profile == NULL) {
  2629. ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA;
  2630. goto exit;
  2631. }
  2632. /* check name if requested */
  2633. if (cn != NULL) {
  2634. x509_crt_verify_name(crt, cn, &ee_flags);
  2635. }
  2636. /* Check the type and size of the key */
  2637. pk_type = mbedtls_pk_get_type(&crt->pk);
  2638. if (x509_profile_check_pk_alg(profile, pk_type) != 0) {
  2639. ee_flags |= MBEDTLS_X509_BADCERT_BAD_PK;
  2640. }
  2641. if (x509_profile_check_key(profile, &crt->pk) != 0) {
  2642. ee_flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
  2643. }
  2644. /* Check the chain */
  2645. ret = x509_crt_verify_chain(crt, trust_ca, ca_crl,
  2646. f_ca_cb, p_ca_cb, profile,
  2647. &ver_chain, rs_ctx);
  2648. if (ret != 0) {
  2649. goto exit;
  2650. }
  2651. /* Merge end-entity flags */
  2652. ver_chain.items[0].flags |= ee_flags;
  2653. /* Build final flags, calling callback on the way if any */
  2654. ret = x509_crt_merge_flags_with_cb(flags, &ver_chain, f_vrfy, p_vrfy);
  2655. exit:
  2656. #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
  2657. mbedtls_x509_crt_free(ver_chain.trust_ca_cb_result);
  2658. mbedtls_free(ver_chain.trust_ca_cb_result);
  2659. ver_chain.trust_ca_cb_result = NULL;
  2660. #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
  2661. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2662. if (rs_ctx != NULL && ret != MBEDTLS_ERR_ECP_IN_PROGRESS) {
  2663. mbedtls_x509_crt_restart_free(rs_ctx);
  2664. }
  2665. #endif
  2666. /* prevent misuse of the vrfy callback - VERIFY_FAILED would be ignored by
  2667. * the SSL module for authmode optional, but non-zero return from the
  2668. * callback means a fatal error so it shouldn't be ignored */
  2669. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  2670. ret = MBEDTLS_ERR_X509_FATAL_ERROR;
  2671. }
  2672. if (ret != 0) {
  2673. *flags = (uint32_t) -1;
  2674. return ret;
  2675. }
  2676. if (*flags != 0) {
  2677. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  2678. }
  2679. return 0;
  2680. }
  2681. /*
  2682. * Verify the certificate validity (default profile, not restartable)
  2683. */
  2684. int mbedtls_x509_crt_verify(mbedtls_x509_crt *crt,
  2685. mbedtls_x509_crt *trust_ca,
  2686. mbedtls_x509_crl *ca_crl,
  2687. const char *cn, uint32_t *flags,
  2688. int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  2689. void *p_vrfy)
  2690. {
  2691. return x509_crt_verify_restartable_ca_cb(crt, trust_ca, ca_crl,
  2692. NULL, NULL,
  2693. &mbedtls_x509_crt_profile_default,
  2694. cn, flags,
  2695. f_vrfy, p_vrfy, NULL);
  2696. }
  2697. /*
  2698. * Verify the certificate validity (user-chosen profile, not restartable)
  2699. */
  2700. int mbedtls_x509_crt_verify_with_profile(mbedtls_x509_crt *crt,
  2701. mbedtls_x509_crt *trust_ca,
  2702. mbedtls_x509_crl *ca_crl,
  2703. const mbedtls_x509_crt_profile *profile,
  2704. const char *cn, uint32_t *flags,
  2705. int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  2706. void *p_vrfy)
  2707. {
  2708. return x509_crt_verify_restartable_ca_cb(crt, trust_ca, ca_crl,
  2709. NULL, NULL,
  2710. profile, cn, flags,
  2711. f_vrfy, p_vrfy, NULL);
  2712. }
  2713. #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
  2714. /*
  2715. * Verify the certificate validity (user-chosen profile, CA callback,
  2716. * not restartable).
  2717. */
  2718. int mbedtls_x509_crt_verify_with_ca_cb(mbedtls_x509_crt *crt,
  2719. mbedtls_x509_crt_ca_cb_t f_ca_cb,
  2720. void *p_ca_cb,
  2721. const mbedtls_x509_crt_profile *profile,
  2722. const char *cn, uint32_t *flags,
  2723. int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  2724. void *p_vrfy)
  2725. {
  2726. return x509_crt_verify_restartable_ca_cb(crt, NULL, NULL,
  2727. f_ca_cb, p_ca_cb,
  2728. profile, cn, flags,
  2729. f_vrfy, p_vrfy, NULL);
  2730. }
  2731. #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
  2732. int mbedtls_x509_crt_verify_restartable(mbedtls_x509_crt *crt,
  2733. mbedtls_x509_crt *trust_ca,
  2734. mbedtls_x509_crl *ca_crl,
  2735. const mbedtls_x509_crt_profile *profile,
  2736. const char *cn, uint32_t *flags,
  2737. int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  2738. void *p_vrfy,
  2739. mbedtls_x509_crt_restart_ctx *rs_ctx)
  2740. {
  2741. return x509_crt_verify_restartable_ca_cb(crt, trust_ca, ca_crl,
  2742. NULL, NULL,
  2743. profile, cn, flags,
  2744. f_vrfy, p_vrfy, rs_ctx);
  2745. }
  2746. /*
  2747. * Initialize a certificate chain
  2748. */
  2749. void mbedtls_x509_crt_init(mbedtls_x509_crt *crt)
  2750. {
  2751. memset(crt, 0, sizeof(mbedtls_x509_crt));
  2752. }
  2753. /*
  2754. * Unallocate all certificate data
  2755. */
  2756. void mbedtls_x509_crt_free(mbedtls_x509_crt *crt)
  2757. {
  2758. mbedtls_x509_crt *cert_cur = crt;
  2759. mbedtls_x509_crt *cert_prv;
  2760. while (cert_cur != NULL) {
  2761. mbedtls_pk_free(&cert_cur->pk);
  2762. #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
  2763. mbedtls_free(cert_cur->sig_opts);
  2764. #endif
  2765. mbedtls_asn1_free_named_data_list_shallow(cert_cur->issuer.next);
  2766. mbedtls_asn1_free_named_data_list_shallow(cert_cur->subject.next);
  2767. mbedtls_asn1_sequence_free(cert_cur->ext_key_usage.next);
  2768. mbedtls_asn1_sequence_free(cert_cur->subject_alt_names.next);
  2769. mbedtls_asn1_sequence_free(cert_cur->certificate_policies.next);
  2770. mbedtls_asn1_sequence_free(cert_cur->authority_key_id.authorityCertIssuer.next);
  2771. if (cert_cur->raw.p != NULL && cert_cur->own_buffer) {
  2772. mbedtls_zeroize_and_free(cert_cur->raw.p, cert_cur->raw.len);
  2773. }
  2774. cert_prv = cert_cur;
  2775. cert_cur = cert_cur->next;
  2776. mbedtls_platform_zeroize(cert_prv, sizeof(mbedtls_x509_crt));
  2777. if (cert_prv != crt) {
  2778. mbedtls_free(cert_prv);
  2779. }
  2780. }
  2781. }
  2782. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2783. /*
  2784. * Initialize a restart context
  2785. */
  2786. void mbedtls_x509_crt_restart_init(mbedtls_x509_crt_restart_ctx *ctx)
  2787. {
  2788. mbedtls_pk_restart_init(&ctx->pk);
  2789. ctx->parent = NULL;
  2790. ctx->fallback_parent = NULL;
  2791. ctx->fallback_signature_is_good = 0;
  2792. ctx->parent_is_trusted = -1;
  2793. ctx->in_progress = x509_crt_rs_none;
  2794. ctx->self_cnt = 0;
  2795. x509_crt_verify_chain_reset(&ctx->ver_chain);
  2796. }
  2797. /*
  2798. * Free the components of a restart context
  2799. */
  2800. void mbedtls_x509_crt_restart_free(mbedtls_x509_crt_restart_ctx *ctx)
  2801. {
  2802. if (ctx == NULL) {
  2803. return;
  2804. }
  2805. mbedtls_pk_restart_free(&ctx->pk);
  2806. mbedtls_x509_crt_restart_init(ctx);
  2807. }
  2808. #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
  2809. int mbedtls_x509_crt_get_ca_istrue(const mbedtls_x509_crt *crt)
  2810. {
  2811. if ((crt->ext_types & MBEDTLS_X509_EXT_BASIC_CONSTRAINTS) != 0) {
  2812. return crt->MBEDTLS_PRIVATE(ca_istrue);
  2813. }
  2814. return MBEDTLS_ERR_X509_INVALID_EXTENSIONS;
  2815. }
  2816. #endif /* MBEDTLS_X509_CRT_PARSE_C */