2
0

x509_crt.c 80 KB

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