2
0

x509_crt.c 82 KB

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