x509asn1.c 34 KB

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