x509asn1.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "curl_setup.h"
  23. #if defined(USE_GSKIT) || defined(USE_NSS) || defined(USE_GNUTLS) || \
  24. defined(USE_CYASSL) || defined(USE_SCHANNEL)
  25. #include <curl/curl.h>
  26. #include "urldata.h"
  27. #include "strcase.h"
  28. #include "hostcheck.h"
  29. #include "vtls/vtls.h"
  30. #include "sendf.h"
  31. #include "inet_pton.h"
  32. #include "curl_base64.h"
  33. #include "x509asn1.h"
  34. /* The last 3 #include files should be in this order */
  35. #include "curl_printf.h"
  36. #include "curl_memory.h"
  37. #include "memdebug.h"
  38. /* For overflow checks. */
  39. #define CURL_SIZE_T_MAX ((size_t)-1)
  40. /* ASN.1 OIDs. */
  41. static const char cnOID[] = "2.5.4.3"; /* Common name. */
  42. static const char sanOID[] = "2.5.29.17"; /* Subject alternative name. */
  43. static const curl_OID OIDtable[] = {
  44. { "1.2.840.10040.4.1", "dsa" },
  45. { "1.2.840.10040.4.3", "dsa-with-sha1" },
  46. { "1.2.840.10045.2.1", "ecPublicKey" },
  47. { "1.2.840.10045.3.0.1", "c2pnb163v1" },
  48. { "1.2.840.10045.4.1", "ecdsa-with-SHA1" },
  49. { "1.2.840.10046.2.1", "dhpublicnumber" },
  50. { "1.2.840.113549.1.1.1", "rsaEncryption" },
  51. { "1.2.840.113549.1.1.2", "md2WithRSAEncryption" },
  52. { "1.2.840.113549.1.1.4", "md5WithRSAEncryption" },
  53. { "1.2.840.113549.1.1.5", "sha1WithRSAEncryption" },
  54. { "1.2.840.113549.1.1.10", "RSASSA-PSS" },
  55. { "1.2.840.113549.1.1.14", "sha224WithRSAEncryption" },
  56. { "1.2.840.113549.1.1.11", "sha256WithRSAEncryption" },
  57. { "1.2.840.113549.1.1.12", "sha384WithRSAEncryption" },
  58. { "1.2.840.113549.1.1.13", "sha512WithRSAEncryption" },
  59. { "1.2.840.113549.2.2", "md2" },
  60. { "1.2.840.113549.2.5", "md5" },
  61. { "1.3.14.3.2.26", "sha1" },
  62. { cnOID, "CN" },
  63. { "2.5.4.4", "SN" },
  64. { "2.5.4.5", "serialNumber" },
  65. { "2.5.4.6", "C" },
  66. { "2.5.4.7", "L" },
  67. { "2.5.4.8", "ST" },
  68. { "2.5.4.9", "streetAddress" },
  69. { "2.5.4.10", "O" },
  70. { "2.5.4.11", "OU" },
  71. { "2.5.4.12", "title" },
  72. { "2.5.4.13", "description" },
  73. { "2.5.4.17", "postalCode" },
  74. { "2.5.4.41", "name" },
  75. { "2.5.4.42", "givenName" },
  76. { "2.5.4.43", "initials" },
  77. { "2.5.4.44", "generationQualifier" },
  78. { "2.5.4.45", "X500UniqueIdentifier" },
  79. { "2.5.4.46", "dnQualifier" },
  80. { "2.5.4.65", "pseudonym" },
  81. { "1.2.840.113549.1.9.1", "emailAddress" },
  82. { "2.5.4.72", "role" },
  83. { sanOID, "subjectAltName" },
  84. { "2.5.29.18", "issuerAltName" },
  85. { "2.5.29.19", "basicConstraints" },
  86. { "2.16.840.1.101.3.4.2.4", "sha224" },
  87. { "2.16.840.1.101.3.4.2.1", "sha256" },
  88. { "2.16.840.1.101.3.4.2.2", "sha384" },
  89. { "2.16.840.1.101.3.4.2.3", "sha512" },
  90. { (const char *) NULL, (const char *) NULL }
  91. };
  92. /*
  93. * Lightweight ASN.1 parser.
  94. * In particular, it does not check for syntactic/lexical errors.
  95. * It is intended to support certificate information gathering for SSL backends
  96. * that offer a mean to get certificates as a whole, but do not supply
  97. * entry points to get particular certificate sub-fields.
  98. * Please note there is no pretention here to rewrite a full SSL library.
  99. */
  100. const char *Curl_getASN1Element(curl_asn1Element *elem,
  101. const char *beg, const char *end)
  102. {
  103. unsigned char b;
  104. unsigned long len;
  105. curl_asn1Element lelem;
  106. /* Get a single ASN.1 element into `elem', parse ASN.1 string at `beg'
  107. ending at `end'.
  108. Returns a pointer in source string after the parsed element, or NULL
  109. if an error occurs. */
  110. if(!beg || !end || beg >= end || !*beg ||
  111. (size_t)(end - beg) > CURL_ASN1_MAX)
  112. return (const char *) NULL;
  113. /* Process header byte. */
  114. elem->header = beg;
  115. b = (unsigned char) *beg++;
  116. elem->constructed = (b & 0x20) != 0;
  117. elem->class = (b >> 6) & 3;
  118. b &= 0x1F;
  119. if(b == 0x1F)
  120. return (const char *) NULL; /* Long tag values not supported here. */
  121. elem->tag = b;
  122. /* Process length. */
  123. if(beg >= end)
  124. return (const char *) NULL;
  125. b = (unsigned char) *beg++;
  126. if(!(b & 0x80))
  127. len = b;
  128. else if(!(b &= 0x7F)) {
  129. /* Unspecified length. Since we have all the data, we can determine the
  130. effective length by skipping element until an end element is found. */
  131. if(!elem->constructed)
  132. return (const char *) NULL;
  133. elem->beg = beg;
  134. while(beg < end && *beg) {
  135. beg = Curl_getASN1Element(&lelem, beg, end);
  136. if(!beg)
  137. return (const char *) NULL;
  138. }
  139. if(beg >= end)
  140. return (const char *) NULL;
  141. elem->end = beg;
  142. return beg + 1;
  143. }
  144. else if((unsigned)b > (size_t)(end - beg))
  145. return (const char *) NULL; /* Does not fit in source. */
  146. else {
  147. /* Get long length. */
  148. len = 0;
  149. do {
  150. if(len & 0xFF000000L)
  151. return (const char *) NULL; /* Lengths > 32 bits are not supported. */
  152. len = (len << 8) | (unsigned char) *beg++;
  153. } while(--b);
  154. }
  155. if(len > (size_t)(end - beg))
  156. return (const char *) NULL; /* Element data does not fit in source. */
  157. elem->beg = beg;
  158. elem->end = beg + len;
  159. return elem->end;
  160. }
  161. static const curl_OID * searchOID(const char *oid)
  162. {
  163. const curl_OID *op;
  164. /* Search the null terminated OID or OID identifier in local table.
  165. Return the table entry pointer or NULL if not found. */
  166. for(op = OIDtable; op->numoid; op++)
  167. if(!strcmp(op->numoid, oid) || strcasecompare(op->textoid, oid))
  168. return op;
  169. return (const curl_OID *) NULL;
  170. }
  171. static const char *bool2str(const char *beg, const char *end)
  172. {
  173. /* Convert an ASN.1 Boolean value into its string representation.
  174. Return the dynamically allocated string, or NULL if source is not an
  175. ASN.1 Boolean value. */
  176. if(end - beg != 1)
  177. return (const char *) NULL;
  178. return strdup(*beg? "TRUE": "FALSE");
  179. }
  180. static const char *octet2str(const char *beg, const char *end)
  181. {
  182. size_t n = end - beg;
  183. char *buf = NULL;
  184. /* Convert an ASN.1 octet string to a printable string.
  185. Return the dynamically allocated string, or NULL if an error occurs. */
  186. if(n <= (CURL_SIZE_T_MAX - 1) / 3) {
  187. buf = malloc(3 * n + 1);
  188. if(buf)
  189. for(n = 0; beg < end; n += 3)
  190. snprintf(buf + n, 4, "%02x:", *(const unsigned char *) beg++);
  191. }
  192. return buf;
  193. }
  194. static const char *bit2str(const char *beg, const char *end)
  195. {
  196. /* Convert an ASN.1 bit string to a printable string.
  197. Return the dynamically allocated string, or NULL if an error occurs. */
  198. if(++beg > end)
  199. return (const char *) NULL;
  200. return octet2str(beg, end);
  201. }
  202. static const char *int2str(const char *beg, const char *end)
  203. {
  204. long val = 0;
  205. size_t n = end - beg;
  206. /* Convert an ASN.1 integer value into its string representation.
  207. Return the dynamically allocated string, or NULL if source is not an
  208. ASN.1 integer value. */
  209. if(!n)
  210. return (const char *) NULL;
  211. if(n > 4)
  212. return octet2str(beg, end);
  213. /* Represent integers <= 32-bit as a single value. */
  214. if(*beg & 0x80)
  215. val = ~val;
  216. do
  217. val = (val << 8) | *(const unsigned char *) beg++;
  218. while(beg < end);
  219. return curl_maprintf("%s%lx", (val < 0 || val >= 10)? "0x": "", val);
  220. }
  221. static ssize_t
  222. utf8asn1str(char **to, int type, const char *from, const char *end)
  223. {
  224. size_t inlength = end - from;
  225. int size = 1;
  226. size_t outlength;
  227. int charsize;
  228. unsigned int wc;
  229. char *buf;
  230. /* Perform a lazy conversion from an ASN.1 typed string to UTF8. Allocate the
  231. destination buffer dynamically. The allocation size will normally be too
  232. large: this is to avoid buffer overflows.
  233. Terminate the string with a nul byte and return the converted
  234. string length. */
  235. *to = (char *) NULL;
  236. switch(type) {
  237. case CURL_ASN1_BMP_STRING:
  238. size = 2;
  239. break;
  240. case CURL_ASN1_UNIVERSAL_STRING:
  241. size = 4;
  242. break;
  243. case CURL_ASN1_NUMERIC_STRING:
  244. case CURL_ASN1_PRINTABLE_STRING:
  245. case CURL_ASN1_TELETEX_STRING:
  246. case CURL_ASN1_IA5_STRING:
  247. case CURL_ASN1_VISIBLE_STRING:
  248. case CURL_ASN1_UTF8_STRING:
  249. break;
  250. default:
  251. return -1; /* Conversion not supported. */
  252. }
  253. if(inlength % size)
  254. return -1; /* Length inconsistent with character size. */
  255. if(inlength / size > (CURL_SIZE_T_MAX - 1) / 4)
  256. return -1; /* Too big. */
  257. buf = malloc(4 * (inlength / size) + 1);
  258. if(!buf)
  259. return -1; /* Not enough memory. */
  260. if(type == CURL_ASN1_UTF8_STRING) {
  261. /* Just copy. */
  262. outlength = inlength;
  263. if(outlength)
  264. memcpy(buf, from, outlength);
  265. }
  266. else {
  267. for(outlength = 0; from < end;) {
  268. wc = 0;
  269. switch(size) {
  270. case 4:
  271. wc = (wc << 8) | *(const unsigned char *) from++;
  272. wc = (wc << 8) | *(const unsigned char *) from++;
  273. /* fallthrough */
  274. case 2:
  275. wc = (wc << 8) | *(const unsigned char *) from++;
  276. /* fallthrough */
  277. default: /* case 1: */
  278. wc = (wc << 8) | *(const unsigned char *) from++;
  279. }
  280. charsize = 1;
  281. if(wc >= 0x00000080) {
  282. if(wc >= 0x00000800) {
  283. if(wc >= 0x00010000) {
  284. if(wc >= 0x00200000) {
  285. free(buf);
  286. return -1; /* Invalid char. size for target encoding. */
  287. }
  288. buf[outlength + 3] = (char) (0x80 | (wc & 0x3F));
  289. wc = (wc >> 6) | 0x00010000;
  290. charsize++;
  291. }
  292. buf[outlength + 2] = (char) (0x80 | (wc & 0x3F));
  293. wc = (wc >> 6) | 0x00000800;
  294. charsize++;
  295. }
  296. buf[outlength + 1] = (char) (0x80 | (wc & 0x3F));
  297. wc = (wc >> 6) | 0x000000C0;
  298. charsize++;
  299. }
  300. buf[outlength] = (char) wc;
  301. outlength += charsize;
  302. }
  303. }
  304. buf[outlength] = '\0';
  305. *to = buf;
  306. return outlength;
  307. }
  308. static const char *string2str(int type, const char *beg, const char *end)
  309. {
  310. char *buf;
  311. /* Convert an ASN.1 String into its UTF-8 string representation.
  312. Return the dynamically allocated string, or NULL if an error occurs. */
  313. if(utf8asn1str(&buf, type, beg, end) < 0)
  314. return (const char *) NULL;
  315. return buf;
  316. }
  317. static int encodeUint(char *buf, int n, unsigned int x)
  318. {
  319. int i = 0;
  320. unsigned int y = x / 10;
  321. /* Decimal ASCII encode unsigned integer `x' in the `n'-byte buffer at `buf'.
  322. Return the total number of encoded digits, even if larger than `n'. */
  323. if(y) {
  324. i += encodeUint(buf, n, y);
  325. x -= y * 10;
  326. }
  327. if(i < n)
  328. buf[i] = (char) ('0' + x);
  329. i++;
  330. if(i < n)
  331. buf[i] = '\0'; /* Store a terminator if possible. */
  332. return i;
  333. }
  334. static int encodeOID(char *buf, int n, const char *beg, const char *end)
  335. {
  336. int i = 0;
  337. unsigned int x;
  338. unsigned int y;
  339. /* Convert an ASN.1 OID into its dotted string representation.
  340. Store the result in th `n'-byte buffer at `buf'.
  341. Return the converted string length, or -1 if an error occurs. */
  342. /* Process the first two numbers. */
  343. y = *(const unsigned char *) beg++;
  344. x = y / 40;
  345. y -= x * 40;
  346. i += encodeUint(buf + i, n - i, x);
  347. if(i < n)
  348. buf[i] = '.';
  349. i++;
  350. i += encodeUint(buf + i, n - i, y);
  351. /* Process the trailing numbers. */
  352. while(beg < end) {
  353. if(i < n)
  354. buf[i] = '.';
  355. i++;
  356. x = 0;
  357. do {
  358. if(x & 0xFF000000)
  359. return -1;
  360. y = *(const unsigned char *) beg++;
  361. x = (x << 7) | (y & 0x7F);
  362. } while(y & 0x80);
  363. i += encodeUint(buf + i, n - i, x);
  364. }
  365. if(i < n)
  366. buf[i] = '\0';
  367. return i;
  368. }
  369. static const char *OID2str(const char *beg, const char *end, bool symbolic)
  370. {
  371. char *buf = (char *) NULL;
  372. const curl_OID * op;
  373. int n;
  374. /* Convert an ASN.1 OID into its dotted or symbolic string representation.
  375. Return the dynamically allocated string, or NULL if an error occurs. */
  376. if(beg < end) {
  377. n = encodeOID((char *) NULL, -1, beg, end);
  378. if(n >= 0) {
  379. buf = malloc(n + 1);
  380. if(buf) {
  381. encodeOID(buf, n, beg, end);
  382. buf[n] = '\0';
  383. if(symbolic) {
  384. op = searchOID(buf);
  385. if(op) {
  386. free(buf);
  387. buf = strdup(op->textoid);
  388. }
  389. }
  390. }
  391. }
  392. }
  393. return buf;
  394. }
  395. static const char *GTime2str(const char *beg, const char *end)
  396. {
  397. const char *tzp;
  398. const char *fracp;
  399. char sec1, sec2;
  400. size_t fracl;
  401. size_t tzl;
  402. const char *sep = "";
  403. /* Convert an ASN.1 Generalized time to a printable string.
  404. Return the dynamically allocated string, or NULL if an error occurs. */
  405. for(fracp = beg; fracp < end && *fracp >= '0' && *fracp <= '9'; fracp++)
  406. ;
  407. /* Get seconds digits. */
  408. sec1 = '0';
  409. switch(fracp - beg - 12) {
  410. case 0:
  411. sec2 = '0';
  412. break;
  413. case 2:
  414. sec1 = fracp[-2];
  415. /* FALLTHROUGH */
  416. case 1:
  417. sec2 = fracp[-1];
  418. break;
  419. default:
  420. return (const char *) NULL;
  421. }
  422. /* Scan for timezone, measure fractional seconds. */
  423. tzp = fracp;
  424. fracl = 0;
  425. if(fracp < end && (*fracp == '.' || *fracp == ',')) {
  426. fracp++;
  427. do
  428. tzp++;
  429. while(tzp < end && *tzp >= '0' && *tzp <= '9');
  430. /* Strip leading zeroes in fractional seconds. */
  431. for(fracl = tzp - fracp - 1; fracl && fracp[fracl - 1] == '0'; fracl--)
  432. ;
  433. }
  434. /* Process timezone. */
  435. if(tzp >= end)
  436. ; /* Nothing to do. */
  437. else if(*tzp == 'Z') {
  438. tzp = " GMT";
  439. end = tzp + 4;
  440. }
  441. else {
  442. sep = " ";
  443. tzp++;
  444. }
  445. tzl = end - tzp;
  446. return curl_maprintf("%.4s-%.2s-%.2s %.2s:%.2s:%c%c%s%.*s%s%.*s",
  447. beg, beg + 4, beg + 6,
  448. beg + 8, beg + 10, sec1, sec2,
  449. fracl? ".": "", fracl, fracp,
  450. sep, tzl, tzp);
  451. }
  452. static const char *UTime2str(const char *beg, const char *end)
  453. {
  454. const char *tzp;
  455. size_t tzl;
  456. const char *sec;
  457. /* Convert an ASN.1 UTC time to a printable string.
  458. Return the dynamically allocated string, or NULL if an error occurs. */
  459. for(tzp = beg; tzp < end && *tzp >= '0' && *tzp <= '9'; tzp++)
  460. ;
  461. /* Get the seconds. */
  462. sec = beg + 10;
  463. switch(tzp - sec) {
  464. case 0:
  465. sec = "00";
  466. case 2:
  467. break;
  468. default:
  469. return (const char *) NULL;
  470. }
  471. /* Process timezone. */
  472. if(tzp >= end)
  473. return (const char *) NULL;
  474. if(*tzp == 'Z') {
  475. tzp = "GMT";
  476. end = tzp + 3;
  477. }
  478. else
  479. tzp++;
  480. tzl = end - tzp;
  481. return curl_maprintf("%u%.2s-%.2s-%.2s %.2s:%.2s:%.2s %.*s",
  482. 20 - (*beg >= '5'), beg, beg + 2, beg + 4,
  483. beg + 6, beg + 8, sec,
  484. tzl, tzp);
  485. }
  486. const char *Curl_ASN1tostr(curl_asn1Element *elem, int type)
  487. {
  488. /* Convert an ASN.1 element to a printable string.
  489. Return the dynamically allocated string, or NULL if an error occurs. */
  490. if(elem->constructed)
  491. return (const char *) NULL; /* No conversion of structured elements. */
  492. if(!type)
  493. type = elem->tag; /* Type not forced: use element tag as type. */
  494. switch(type) {
  495. case CURL_ASN1_BOOLEAN:
  496. return bool2str(elem->beg, elem->end);
  497. case CURL_ASN1_INTEGER:
  498. case CURL_ASN1_ENUMERATED:
  499. return int2str(elem->beg, elem->end);
  500. case CURL_ASN1_BIT_STRING:
  501. return bit2str(elem->beg, elem->end);
  502. case CURL_ASN1_OCTET_STRING:
  503. return octet2str(elem->beg, elem->end);
  504. case CURL_ASN1_NULL:
  505. return strdup("");
  506. case CURL_ASN1_OBJECT_IDENTIFIER:
  507. return OID2str(elem->beg, elem->end, TRUE);
  508. case CURL_ASN1_UTC_TIME:
  509. return UTime2str(elem->beg, elem->end);
  510. case CURL_ASN1_GENERALIZED_TIME:
  511. return GTime2str(elem->beg, elem->end);
  512. case CURL_ASN1_UTF8_STRING:
  513. case CURL_ASN1_NUMERIC_STRING:
  514. case CURL_ASN1_PRINTABLE_STRING:
  515. case CURL_ASN1_TELETEX_STRING:
  516. case CURL_ASN1_IA5_STRING:
  517. case CURL_ASN1_VISIBLE_STRING:
  518. case CURL_ASN1_UNIVERSAL_STRING:
  519. case CURL_ASN1_BMP_STRING:
  520. return string2str(type, elem->beg, elem->end);
  521. }
  522. return (const char *) NULL; /* Unsupported. */
  523. }
  524. static ssize_t encodeDN(char *buf, size_t n, curl_asn1Element *dn)
  525. {
  526. curl_asn1Element rdn;
  527. curl_asn1Element atv;
  528. curl_asn1Element oid;
  529. curl_asn1Element value;
  530. size_t l = 0;
  531. const char *p1;
  532. const char *p2;
  533. const char *p3;
  534. const char *str;
  535. /* ASCII encode distinguished name at `dn' into the `n'-byte buffer at `buf'.
  536. Return the total string length, even if larger than `n'. */
  537. for(p1 = dn->beg; p1 < dn->end;) {
  538. p1 = Curl_getASN1Element(&rdn, p1, dn->end);
  539. for(p2 = rdn.beg; p2 < rdn.end;) {
  540. p2 = Curl_getASN1Element(&atv, p2, rdn.end);
  541. p3 = Curl_getASN1Element(&oid, atv.beg, atv.end);
  542. Curl_getASN1Element(&value, p3, atv.end);
  543. str = Curl_ASN1tostr(&oid, 0);
  544. if(!str)
  545. return -1;
  546. /* Encode delimiter.
  547. If attribute has a short uppercase name, delimiter is ", ". */
  548. if(l) {
  549. for(p3 = str; isupper(*p3); p3++)
  550. ;
  551. for(p3 = (*p3 || p3 - str > 2)? "/": ", "; *p3; p3++) {
  552. if(l < n)
  553. buf[l] = *p3;
  554. l++;
  555. }
  556. }
  557. /* Encode attribute name. */
  558. for(p3 = str; *p3; p3++) {
  559. if(l < n)
  560. buf[l] = *p3;
  561. l++;
  562. }
  563. free((char *) str);
  564. /* Generate equal sign. */
  565. if(l < n)
  566. buf[l] = '=';
  567. l++;
  568. /* Generate value. */
  569. str = Curl_ASN1tostr(&value, 0);
  570. if(!str)
  571. return -1;
  572. for(p3 = str; *p3; p3++) {
  573. if(l < n)
  574. buf[l] = *p3;
  575. l++;
  576. }
  577. free((char *) str);
  578. }
  579. }
  580. return l;
  581. }
  582. const char *Curl_DNtostr(curl_asn1Element *dn)
  583. {
  584. char *buf = (char *) NULL;
  585. ssize_t n = encodeDN(buf, 0, dn);
  586. /* Convert an ASN.1 distinguished name into a printable string.
  587. Return the dynamically allocated string, or NULL if an error occurs. */
  588. if(n >= 0) {
  589. buf = malloc(n + 1);
  590. if(buf) {
  591. encodeDN(buf, n + 1, dn);
  592. buf[n] = '\0';
  593. }
  594. }
  595. return (const char *) buf;
  596. }
  597. /*
  598. * X509 parser.
  599. */
  600. int Curl_parseX509(curl_X509certificate *cert,
  601. const char *beg, const char *end)
  602. {
  603. curl_asn1Element elem;
  604. curl_asn1Element tbsCertificate;
  605. const char *ccp;
  606. static const char defaultVersion = 0; /* v1. */
  607. /* ASN.1 parse an X509 certificate into structure subfields.
  608. Syntax is assumed to have already been checked by the SSL backend.
  609. See RFC 5280. */
  610. cert->certificate.header = NULL;
  611. cert->certificate.beg = beg;
  612. cert->certificate.end = end;
  613. /* Get the sequence content. */
  614. if(!Curl_getASN1Element(&elem, beg, end))
  615. return -1; /* Invalid bounds/size. */
  616. beg = elem.beg;
  617. end = elem.end;
  618. /* Get tbsCertificate. */
  619. beg = Curl_getASN1Element(&tbsCertificate, beg, end);
  620. /* Skip the signatureAlgorithm. */
  621. beg = Curl_getASN1Element(&cert->signatureAlgorithm, beg, end);
  622. /* Get the signatureValue. */
  623. Curl_getASN1Element(&cert->signature, beg, end);
  624. /* Parse TBSCertificate. */
  625. beg = tbsCertificate.beg;
  626. end = tbsCertificate.end;
  627. /* Get optional version, get serialNumber. */
  628. cert->version.header = NULL;
  629. cert->version.beg = &defaultVersion;
  630. cert->version.end = &defaultVersion + sizeof defaultVersion;;
  631. beg = Curl_getASN1Element(&elem, beg, end);
  632. if(elem.tag == 0) {
  633. Curl_getASN1Element(&cert->version, elem.beg, elem.end);
  634. beg = Curl_getASN1Element(&elem, beg, end);
  635. }
  636. cert->serialNumber = elem;
  637. /* Get signature algorithm. */
  638. beg = Curl_getASN1Element(&cert->signatureAlgorithm, beg, end);
  639. /* Get issuer. */
  640. beg = Curl_getASN1Element(&cert->issuer, beg, end);
  641. /* Get notBefore and notAfter. */
  642. beg = Curl_getASN1Element(&elem, beg, end);
  643. ccp = Curl_getASN1Element(&cert->notBefore, elem.beg, elem.end);
  644. Curl_getASN1Element(&cert->notAfter, ccp, elem.end);
  645. /* Get subject. */
  646. beg = Curl_getASN1Element(&cert->subject, beg, end);
  647. /* Get subjectPublicKeyAlgorithm and subjectPublicKey. */
  648. beg = Curl_getASN1Element(&cert->subjectPublicKeyInfo, beg, end);
  649. ccp = Curl_getASN1Element(&cert->subjectPublicKeyAlgorithm,
  650. cert->subjectPublicKeyInfo.beg,
  651. cert->subjectPublicKeyInfo.end);
  652. Curl_getASN1Element(&cert->subjectPublicKey, ccp,
  653. cert->subjectPublicKeyInfo.end);
  654. /* Get optional issuerUiqueID, subjectUniqueID and extensions. */
  655. cert->issuerUniqueID.tag = cert->subjectUniqueID.tag = 0;
  656. cert->extensions.tag = elem.tag = 0;
  657. cert->issuerUniqueID.header = cert->subjectUniqueID.header = NULL;
  658. cert->issuerUniqueID.beg = cert->issuerUniqueID.end = "";
  659. cert->subjectUniqueID.beg = cert->subjectUniqueID.end = "";
  660. cert->extensions.header = NULL;
  661. cert->extensions.beg = cert->extensions.end = "";
  662. if(beg < end)
  663. beg = Curl_getASN1Element(&elem, beg, end);
  664. if(elem.tag == 1) {
  665. cert->issuerUniqueID = elem;
  666. if(beg < end)
  667. beg = Curl_getASN1Element(&elem, beg, end);
  668. }
  669. if(elem.tag == 2) {
  670. cert->subjectUniqueID = elem;
  671. if(beg < end)
  672. beg = Curl_getASN1Element(&elem, beg, end);
  673. }
  674. if(elem.tag == 3)
  675. Curl_getASN1Element(&cert->extensions, elem.beg, elem.end);
  676. return 0;
  677. }
  678. static size_t copySubstring(char *to, const char *from)
  679. {
  680. size_t i;
  681. /* Copy at most 64-characters, terminate with a newline and returns the
  682. effective number of stored characters. */
  683. for(i = 0; i < 64; i++) {
  684. to[i] = *from;
  685. if(!*from++)
  686. break;
  687. }
  688. to[i++] = '\n';
  689. return i;
  690. }
  691. static const char *dumpAlgo(curl_asn1Element *param,
  692. const char *beg, const char *end)
  693. {
  694. curl_asn1Element oid;
  695. /* Get algorithm parameters and return algorithm name. */
  696. beg = Curl_getASN1Element(&oid, beg, end);
  697. param->header = NULL;
  698. param->tag = 0;
  699. param->beg = param->end = end;
  700. if(beg < end)
  701. Curl_getASN1Element(param, beg, end);
  702. return OID2str(oid.beg, oid.end, TRUE);
  703. }
  704. static void do_pubkey_field(struct Curl_easy *data, int certnum,
  705. const char *label, curl_asn1Element *elem)
  706. {
  707. const char *output;
  708. /* Generate a certificate information record for the public key. */
  709. output = Curl_ASN1tostr(elem, 0);
  710. if(output) {
  711. if(data->set.ssl.certinfo)
  712. Curl_ssl_push_certinfo(data, certnum, label, output);
  713. if(!certnum)
  714. infof(data, " %s: %s\n", label, output);
  715. free((char *) output);
  716. }
  717. }
  718. static void do_pubkey(struct Curl_easy *data, int certnum,
  719. const char *algo, curl_asn1Element *param,
  720. curl_asn1Element *pubkey)
  721. {
  722. curl_asn1Element elem;
  723. curl_asn1Element pk;
  724. const char *p;
  725. const char *q;
  726. unsigned long len;
  727. unsigned int i;
  728. /* Generate all information records for the public key. */
  729. /* Get the public key (single element). */
  730. Curl_getASN1Element(&pk, pubkey->beg + 1, pubkey->end);
  731. if(strcasecompare(algo, "rsaEncryption")) {
  732. p = Curl_getASN1Element(&elem, pk.beg, pk.end);
  733. /* Compute key length. */
  734. for(q = elem.beg; !*q && q < elem.end; q++)
  735. ;
  736. len = (unsigned long)((elem.end - q) * 8);
  737. if(len)
  738. for(i = *(unsigned char *) q; !(i & 0x80); i <<= 1)
  739. len--;
  740. if(len > 32)
  741. elem.beg = q; /* Strip leading zero bytes. */
  742. if(!certnum)
  743. infof(data, " RSA Public Key (%lu bits)\n", len);
  744. if(data->set.ssl.certinfo) {
  745. q = curl_maprintf("%lu", len);
  746. if(q) {
  747. Curl_ssl_push_certinfo(data, certnum, "RSA Public Key", q);
  748. free((char *) q);
  749. }
  750. }
  751. /* Generate coefficients. */
  752. do_pubkey_field(data, certnum, "rsa(n)", &elem);
  753. Curl_getASN1Element(&elem, p, pk.end);
  754. do_pubkey_field(data, certnum, "rsa(e)", &elem);
  755. }
  756. else if(strcasecompare(algo, "dsa")) {
  757. p = Curl_getASN1Element(&elem, param->beg, param->end);
  758. do_pubkey_field(data, certnum, "dsa(p)", &elem);
  759. p = Curl_getASN1Element(&elem, p, param->end);
  760. do_pubkey_field(data, certnum, "dsa(q)", &elem);
  761. Curl_getASN1Element(&elem, p, param->end);
  762. do_pubkey_field(data, certnum, "dsa(g)", &elem);
  763. do_pubkey_field(data, certnum, "dsa(pub_key)", &pk);
  764. }
  765. else if(strcasecompare(algo, "dhpublicnumber")) {
  766. p = Curl_getASN1Element(&elem, param->beg, param->end);
  767. do_pubkey_field(data, certnum, "dh(p)", &elem);
  768. Curl_getASN1Element(&elem, param->beg, param->end);
  769. do_pubkey_field(data, certnum, "dh(g)", &elem);
  770. do_pubkey_field(data, certnum, "dh(pub_key)", &pk);
  771. }
  772. #if 0 /* Patent-encumbered. */
  773. else if(strcasecompare(algo, "ecPublicKey")) {
  774. /* Left TODO. */
  775. }
  776. #endif
  777. }
  778. CURLcode Curl_extract_certinfo(struct connectdata *conn,
  779. int certnum,
  780. const char *beg,
  781. const char *end)
  782. {
  783. curl_X509certificate cert;
  784. struct Curl_easy *data = conn->data;
  785. curl_asn1Element param;
  786. const char *ccp;
  787. char *cp1;
  788. size_t cl1;
  789. char *cp2;
  790. CURLcode result;
  791. unsigned long version;
  792. size_t i;
  793. size_t j;
  794. if(!data->set.ssl.certinfo)
  795. if(certnum)
  796. return CURLE_OK;
  797. /* Prepare the certificate information for curl_easy_getinfo(). */
  798. /* Extract the certificate ASN.1 elements. */
  799. if(Curl_parseX509(&cert, beg, end))
  800. return CURLE_OUT_OF_MEMORY;
  801. /* Subject. */
  802. ccp = Curl_DNtostr(&cert.subject);
  803. if(!ccp)
  804. return CURLE_OUT_OF_MEMORY;
  805. if(data->set.ssl.certinfo)
  806. Curl_ssl_push_certinfo(data, certnum, "Subject", ccp);
  807. if(!certnum)
  808. infof(data, "%2d Subject: %s\n", certnum, ccp);
  809. free((char *) ccp);
  810. /* Issuer. */
  811. ccp = Curl_DNtostr(&cert.issuer);
  812. if(!ccp)
  813. return CURLE_OUT_OF_MEMORY;
  814. if(data->set.ssl.certinfo)
  815. Curl_ssl_push_certinfo(data, certnum, "Issuer", ccp);
  816. if(!certnum)
  817. infof(data, " Issuer: %s\n", ccp);
  818. free((char *) ccp);
  819. /* Version (always fits in less than 32 bits). */
  820. version = 0;
  821. for(ccp = cert.version.beg; ccp < cert.version.end; ccp++)
  822. version = (version << 8) | *(const unsigned char *) ccp;
  823. if(data->set.ssl.certinfo) {
  824. ccp = curl_maprintf("%lx", version);
  825. if(!ccp)
  826. return CURLE_OUT_OF_MEMORY;
  827. Curl_ssl_push_certinfo(data, certnum, "Version", ccp);
  828. free((char *) ccp);
  829. }
  830. if(!certnum)
  831. infof(data, " Version: %lu (0x%lx)\n", version + 1, version);
  832. /* Serial number. */
  833. ccp = Curl_ASN1tostr(&cert.serialNumber, 0);
  834. if(!ccp)
  835. return CURLE_OUT_OF_MEMORY;
  836. if(data->set.ssl.certinfo)
  837. Curl_ssl_push_certinfo(data, certnum, "Serial Number", ccp);
  838. if(!certnum)
  839. infof(data, " Serial Number: %s\n", ccp);
  840. free((char *) ccp);
  841. /* Signature algorithm .*/
  842. ccp = dumpAlgo(&param, cert.signatureAlgorithm.beg,
  843. cert.signatureAlgorithm.end);
  844. if(!ccp)
  845. return CURLE_OUT_OF_MEMORY;
  846. if(data->set.ssl.certinfo)
  847. Curl_ssl_push_certinfo(data, certnum, "Signature Algorithm", ccp);
  848. if(!certnum)
  849. infof(data, " Signature Algorithm: %s\n", ccp);
  850. free((char *) ccp);
  851. /* Start Date. */
  852. ccp = Curl_ASN1tostr(&cert.notBefore, 0);
  853. if(!ccp)
  854. return CURLE_OUT_OF_MEMORY;
  855. if(data->set.ssl.certinfo)
  856. Curl_ssl_push_certinfo(data, certnum, "Start Date", ccp);
  857. if(!certnum)
  858. infof(data, " Start Date: %s\n", ccp);
  859. free((char *) ccp);
  860. /* Expire Date. */
  861. ccp = Curl_ASN1tostr(&cert.notAfter, 0);
  862. if(!ccp)
  863. return CURLE_OUT_OF_MEMORY;
  864. if(data->set.ssl.certinfo)
  865. Curl_ssl_push_certinfo(data, certnum, "Expire Date", ccp);
  866. if(!certnum)
  867. infof(data, " Expire Date: %s\n", ccp);
  868. free((char *) ccp);
  869. /* Public Key Algorithm. */
  870. ccp = dumpAlgo(&param, cert.subjectPublicKeyAlgorithm.beg,
  871. cert.subjectPublicKeyAlgorithm.end);
  872. if(!ccp)
  873. return CURLE_OUT_OF_MEMORY;
  874. if(data->set.ssl.certinfo)
  875. Curl_ssl_push_certinfo(data, certnum, "Public Key Algorithm", ccp);
  876. if(!certnum)
  877. infof(data, " Public Key Algorithm: %s\n", ccp);
  878. do_pubkey(data, certnum, ccp, &param, &cert.subjectPublicKey);
  879. free((char *) ccp);
  880. /* TODO: extensions. */
  881. /* Signature. */
  882. ccp = Curl_ASN1tostr(&cert.signature, 0);
  883. if(!ccp)
  884. return CURLE_OUT_OF_MEMORY;
  885. if(data->set.ssl.certinfo)
  886. Curl_ssl_push_certinfo(data, certnum, "Signature", ccp);
  887. if(!certnum)
  888. infof(data, " Signature: %s\n", ccp);
  889. free((char *) ccp);
  890. /* Generate PEM certificate. */
  891. result = Curl_base64_encode(data, cert.certificate.beg,
  892. cert.certificate.end - cert.certificate.beg,
  893. &cp1, &cl1);
  894. if(result)
  895. return result;
  896. /* Compute the number of characters in final certificate string. Format is:
  897. -----BEGIN CERTIFICATE-----\n
  898. <max 64 base64 characters>\n
  899. .
  900. .
  901. .
  902. -----END CERTIFICATE-----\n
  903. */
  904. i = 28 + cl1 + (cl1 + 64 - 1) / 64 + 26;
  905. cp2 = malloc(i + 1);
  906. if(!cp2) {
  907. free(cp1);
  908. return CURLE_OUT_OF_MEMORY;
  909. }
  910. /* Build the certificate string. */
  911. i = copySubstring(cp2, "-----BEGIN CERTIFICATE-----");
  912. for(j = 0; j < cl1; j += 64)
  913. i += copySubstring(cp2 + i, cp1 + j);
  914. i += copySubstring(cp2 + i, "-----END CERTIFICATE-----");
  915. cp2[i] = '\0';
  916. free(cp1);
  917. if(data->set.ssl.certinfo)
  918. Curl_ssl_push_certinfo(data, certnum, "Cert", cp2);
  919. if(!certnum)
  920. infof(data, "%s\n", cp2);
  921. free(cp2);
  922. return CURLE_OK;
  923. }
  924. #endif /* USE_GSKIT or USE_NSS or USE_GNUTLS or USE_CYASSL or USE_SCHANNEL */
  925. #if defined(USE_GSKIT)
  926. static const char *checkOID(const char *beg, const char *end,
  927. const char *oid)
  928. {
  929. curl_asn1Element e;
  930. const char *ccp;
  931. const char *p;
  932. bool matched;
  933. /* Check if first ASN.1 element at `beg' is the given OID.
  934. Return a pointer in the source after the OID if found, else NULL. */
  935. ccp = Curl_getASN1Element(&e, beg, end);
  936. if(!ccp || e.tag != CURL_ASN1_OBJECT_IDENTIFIER)
  937. return (const char *) NULL;
  938. p = OID2str(e.beg, e.end, FALSE);
  939. if(!p)
  940. return (const char *) NULL;
  941. matched = !strcmp(p, oid);
  942. free((char *) p);
  943. return matched? ccp: (const char *) NULL;
  944. }
  945. CURLcode Curl_verifyhost(struct connectdata *conn,
  946. const char *beg, const char *end)
  947. {
  948. struct Curl_easy *data = conn->data;
  949. curl_X509certificate cert;
  950. curl_asn1Element dn;
  951. curl_asn1Element elem;
  952. curl_asn1Element ext;
  953. curl_asn1Element name;
  954. const char *p;
  955. const char *q;
  956. char *dnsname;
  957. int matched = -1;
  958. size_t addrlen = (size_t) -1;
  959. ssize_t len;
  960. const char * const hostname = SSL_IS_PROXY()? conn->http_proxy.host.name:
  961. conn->host.name;
  962. const char * const dispname = SSL_IS_PROXY()?
  963. conn->http_proxy.host.dispname:
  964. conn->host.dispname;
  965. #ifdef ENABLE_IPV6
  966. struct in6_addr addr;
  967. #else
  968. struct in_addr addr;
  969. #endif
  970. /* Verify that connection server matches info in X509 certificate at
  971. `beg'..`end'. */
  972. if(!SSL_CONN_CONFIG(verifyhost))
  973. return CURLE_OK;
  974. if(Curl_parseX509(&cert, beg, end))
  975. return CURLE_PEER_FAILED_VERIFICATION;
  976. /* Get the server IP address. */
  977. #ifdef ENABLE_IPV6
  978. if(conn->bits.ipv6_ip && Curl_inet_pton(AF_INET6, hostname, &addr))
  979. addrlen = sizeof(struct in6_addr);
  980. else
  981. #endif
  982. if(Curl_inet_pton(AF_INET, hostname, &addr))
  983. addrlen = sizeof(struct in_addr);
  984. /* Process extensions. */
  985. for(p = cert.extensions.beg; p < cert.extensions.end && matched != 1;) {
  986. p = Curl_getASN1Element(&ext, p, cert.extensions.end);
  987. /* Check if extension is a subjectAlternativeName. */
  988. ext.beg = checkOID(ext.beg, ext.end, sanOID);
  989. if(ext.beg) {
  990. ext.beg = Curl_getASN1Element(&elem, ext.beg, ext.end);
  991. /* Skip critical if present. */
  992. if(elem.tag == CURL_ASN1_BOOLEAN)
  993. ext.beg = Curl_getASN1Element(&elem, ext.beg, ext.end);
  994. /* Parse the octet string contents: is a single sequence. */
  995. Curl_getASN1Element(&elem, elem.beg, elem.end);
  996. /* Check all GeneralNames. */
  997. for(q = elem.beg; matched != 1 && q < elem.end;) {
  998. q = Curl_getASN1Element(&name, q, elem.end);
  999. switch(name.tag) {
  1000. case 2: /* DNS name. */
  1001. len = utf8asn1str(&dnsname, CURL_ASN1_IA5_STRING,
  1002. name.beg, name.end);
  1003. if(len > 0 && (size_t)len == strlen(dnsname))
  1004. matched = Curl_cert_hostcheck(dnsname, hostname);
  1005. else
  1006. matched = 0;
  1007. free(dnsname);
  1008. break;
  1009. case 7: /* IP address. */
  1010. matched = (size_t) (name.end - q) == addrlen &&
  1011. !memcmp(&addr, q, addrlen);
  1012. break;
  1013. }
  1014. }
  1015. }
  1016. }
  1017. switch(matched) {
  1018. case 1:
  1019. /* an alternative name matched the server hostname */
  1020. infof(data, "\t subjectAltName: %s matched\n", dispname);
  1021. return CURLE_OK;
  1022. case 0:
  1023. /* an alternative name field existed, but didn't match and then
  1024. we MUST fail */
  1025. infof(data, "\t subjectAltName does not match %s\n", dispname);
  1026. return CURLE_PEER_FAILED_VERIFICATION;
  1027. }
  1028. /* Process subject. */
  1029. name.header = NULL;
  1030. name.beg = name.end = "";
  1031. q = cert.subject.beg;
  1032. /* we have to look to the last occurrence of a commonName in the
  1033. distinguished one to get the most significant one. */
  1034. while(q < cert.subject.end) {
  1035. q = Curl_getASN1Element(&dn, q, cert.subject.end);
  1036. for(p = dn.beg; p < dn.end;) {
  1037. p = Curl_getASN1Element(&elem, p, dn.end);
  1038. /* We have a DN's AttributeTypeAndValue: check it in case it's a CN. */
  1039. elem.beg = checkOID(elem.beg, elem.end, cnOID);
  1040. if(elem.beg)
  1041. name = elem; /* Latch CN. */
  1042. }
  1043. }
  1044. /* Check the CN if found. */
  1045. if(!Curl_getASN1Element(&elem, name.beg, name.end))
  1046. failf(data, "SSL: unable to obtain common name from peer certificate");
  1047. else {
  1048. len = utf8asn1str(&dnsname, elem.tag, elem.beg, elem.end);
  1049. if(len < 0) {
  1050. free(dnsname);
  1051. return CURLE_OUT_OF_MEMORY;
  1052. }
  1053. if(strlen(dnsname) != (size_t) len) /* Nul byte in string ? */
  1054. failf(data, "SSL: illegal cert name field");
  1055. else if(Curl_cert_hostcheck((const char *) dnsname, hostname)) {
  1056. infof(data, "\t common name: %s (matched)\n", dnsname);
  1057. free(dnsname);
  1058. return CURLE_OK;
  1059. }
  1060. else
  1061. failf(data, "SSL: certificate subject name '%s' does not match "
  1062. "target host name '%s'", dnsname, dispname);
  1063. free(dnsname);
  1064. }
  1065. return CURLE_PEER_FAILED_VERIFICATION;
  1066. }
  1067. #endif /* USE_GSKIT */