2
0

x509_crt.c 82 KB

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