x509asn1.c 34 KB

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