x509_crt.c 80 KB

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