2
0

x509asn1.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  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_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. 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) || curl_strequal(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. case 2:
  267. wc = (wc << 8) | *(const unsigned char *) from++;
  268. default: /* case 1: */
  269. wc = (wc << 8) | *(const unsigned char *) from++;
  270. }
  271. charsize = 1;
  272. if(wc >= 0x00000080) {
  273. if(wc >= 0x00000800) {
  274. if(wc >= 0x00010000) {
  275. if(wc >= 0x00200000) {
  276. free(buf);
  277. return -1; /* Invalid char. size for target encoding. */
  278. }
  279. buf[outlength + 3] = (char) (0x80 | (wc & 0x3F));
  280. wc = (wc >> 6) | 0x00010000;
  281. charsize++;
  282. }
  283. buf[outlength + 2] = (char) (0x80 | (wc & 0x3F));
  284. wc = (wc >> 6) | 0x00000800;
  285. charsize++;
  286. }
  287. buf[outlength + 1] = (char) (0x80 | (wc & 0x3F));
  288. wc = (wc >> 6) | 0x000000C0;
  289. charsize++;
  290. }
  291. buf[outlength] = (char) wc;
  292. outlength += charsize;
  293. }
  294. }
  295. buf[outlength] = '\0';
  296. *to = buf;
  297. return outlength;
  298. }
  299. static const char * string2str(int type, const char * beg, const char * end)
  300. {
  301. char * buf;
  302. /* Convert an ASN.1 String into its UTF-8 string representation.
  303. Return the dynamically allocated string, or NULL if an error occurs. */
  304. if(utf8asn1str(&buf, type, beg, end) < 0)
  305. return (const char *) NULL;
  306. return buf;
  307. }
  308. static int encodeUint(char * buf, int n, unsigned int x)
  309. {
  310. int i = 0;
  311. unsigned int y = x / 10;
  312. /* Decimal ASCII encode unsigned integer `x' in the `n'-byte buffer at `buf'.
  313. Return the total number of encoded digits, even if larger than `n'. */
  314. if(y) {
  315. i += encodeUint(buf, n, y);
  316. x -= y * 10;
  317. }
  318. if(i < n)
  319. buf[i] = (char) ('0' + x);
  320. i++;
  321. if(i < n)
  322. buf[i] = '\0'; /* Store a terminator if possible. */
  323. return i;
  324. }
  325. static int encodeOID(char * buf, int n, const char * beg, const char * end)
  326. {
  327. int i = 0;
  328. unsigned int x;
  329. unsigned int y;
  330. /* Convert an ASN.1 OID into its dotted string representation.
  331. Store the result in th `n'-byte buffer at `buf'.
  332. Return the converted string length, or -1 if an error occurs. */
  333. /* Process the first two numbers. */
  334. y = *(const unsigned char *) beg++;
  335. x = y / 40;
  336. y -= x * 40;
  337. i += encodeUint(buf + i, n - i, x);
  338. if(i < n)
  339. buf[i] = '.';
  340. i++;
  341. i += encodeUint(buf + i, n - i, y);
  342. /* Process the trailing numbers. */
  343. while(beg < end) {
  344. if(i < n)
  345. buf[i] = '.';
  346. i++;
  347. x = 0;
  348. do {
  349. if(x & 0xFF000000)
  350. return -1;
  351. y = *(const unsigned char *) beg++;
  352. x = (x << 7) | (y & 0x7F);
  353. } while(y & 0x80);
  354. i += encodeUint(buf + i, n - i, x);
  355. }
  356. if(i < n)
  357. buf[i] = '\0';
  358. return i;
  359. }
  360. static const char * OID2str(const char * beg, const char * end, bool symbolic)
  361. {
  362. char * buf = (char *) NULL;
  363. const curl_OID * op;
  364. int n;
  365. /* Convert an ASN.1 OID into its dotted or symbolic string representation.
  366. Return the dynamically allocated string, or NULL if an error occurs. */
  367. if(beg < end) {
  368. n = encodeOID((char *) NULL, -1, beg, end);
  369. if(n >= 0) {
  370. buf = malloc(n + 1);
  371. if(buf) {
  372. encodeOID(buf, n, beg, end);
  373. buf[n] = '\0';
  374. if(symbolic) {
  375. op = searchOID(buf);
  376. if(op) {
  377. free(buf);
  378. buf = strdup(op->textoid);
  379. }
  380. }
  381. }
  382. }
  383. }
  384. return buf;
  385. }
  386. static const char * GTime2str(const char * beg, const char * end)
  387. {
  388. const char * tzp;
  389. const char * fracp;
  390. char sec1, sec2;
  391. size_t fracl;
  392. size_t tzl;
  393. const char * sep = "";
  394. /* Convert an ASN.1 Generalized time to a printable string.
  395. Return the dynamically allocated string, or NULL if an error occurs. */
  396. for(fracp = beg; fracp < end && *fracp >= '0' && *fracp <= '9'; fracp++)
  397. ;
  398. /* Get seconds digits. */
  399. sec1 = '0';
  400. switch (fracp - beg - 12) {
  401. case 0:
  402. sec2 = '0';
  403. break;
  404. case 2:
  405. sec1 = fracp[-2];
  406. case 1:
  407. sec2 = fracp[-1];
  408. break;
  409. default:
  410. return (const char *) NULL;
  411. }
  412. /* Scan for timezone, measure fractional seconds. */
  413. tzp = fracp;
  414. fracl = 0;
  415. if(fracp < end && (*fracp == '.' || *fracp == ',')) {
  416. fracp++;
  417. do
  418. tzp++;
  419. while(tzp < end && *tzp >= '0' && *tzp <= '9');
  420. /* Strip leading zeroes in fractional seconds. */
  421. for(fracl = tzp - fracp - 1; fracl && fracp[fracl - 1] == '0'; fracl--)
  422. ;
  423. }
  424. /* Process timezone. */
  425. if(tzp >= end)
  426. ; /* Nothing to do. */
  427. else if(*tzp == 'Z') {
  428. tzp = " GMT";
  429. end = tzp + 4;
  430. }
  431. else {
  432. sep = " ";
  433. tzp++;
  434. }
  435. tzl = end - tzp;
  436. return curl_maprintf("%.4s-%.2s-%.2s %.2s:%.2s:%c%c%s%.*s%s%.*s",
  437. beg, beg + 4, beg + 6,
  438. beg + 8, beg + 10, sec1, sec2,
  439. fracl? ".": "", fracl, fracp,
  440. sep, tzl, tzp);
  441. }
  442. static const char * UTime2str(const char * beg, const char * end)
  443. {
  444. const char * tzp;
  445. size_t tzl;
  446. const char * sec;
  447. /* Convert an ASN.1 UTC time to a printable string.
  448. Return the dynamically allocated string, or NULL if an error occurs. */
  449. for(tzp = beg; tzp < end && *tzp >= '0' && *tzp <= '9'; tzp++)
  450. ;
  451. /* Get the seconds. */
  452. sec = beg + 10;
  453. switch (tzp - sec) {
  454. case 0:
  455. sec = "00";
  456. case 2:
  457. break;
  458. default:
  459. return (const char *) NULL;
  460. }
  461. /* Process timezone. */
  462. if(tzp >= end)
  463. return (const char *) NULL;
  464. if(*tzp == 'Z') {
  465. tzp = "GMT";
  466. end = tzp + 3;
  467. }
  468. else
  469. tzp++;
  470. tzl = end - tzp;
  471. return curl_maprintf("%u%.2s-%.2s-%.2s %.2s:%.2s:%.2s %.*s",
  472. 20 - (*beg >= '5'), beg, beg + 2, beg + 4,
  473. beg + 6, beg + 8, sec,
  474. tzl, tzp);
  475. }
  476. const char * Curl_ASN1tostr(curl_asn1Element * elem, int type)
  477. {
  478. static const char zero = '\0';
  479. /* Convert an ASN.1 element to a printable string.
  480. Return the dynamically allocated string, or NULL if an error occurs. */
  481. if(elem->constructed)
  482. return (const char *) NULL; /* No conversion of structured elements. */
  483. if(!type)
  484. type = elem->tag; /* Type not forced: use element tag as type. */
  485. switch (type) {
  486. case CURL_ASN1_BOOLEAN:
  487. return bool2str(elem->beg, elem->end);
  488. case CURL_ASN1_INTEGER:
  489. case CURL_ASN1_ENUMERATED:
  490. return int2str(elem->beg, elem->end);
  491. case CURL_ASN1_BIT_STRING:
  492. return bit2str(elem->beg, elem->end);
  493. case CURL_ASN1_OCTET_STRING:
  494. return octet2str(elem->beg, elem->end);
  495. case CURL_ASN1_NULL:
  496. return strdup(&zero);
  497. case CURL_ASN1_OBJECT_IDENTIFIER:
  498. return OID2str(elem->beg, elem->end, TRUE);
  499. case CURL_ASN1_UTC_TIME:
  500. return UTime2str(elem->beg, elem->end);
  501. case CURL_ASN1_GENERALIZED_TIME:
  502. return GTime2str(elem->beg, elem->end);
  503. case CURL_ASN1_UTF8_STRING:
  504. case CURL_ASN1_NUMERIC_STRING:
  505. case CURL_ASN1_PRINTABLE_STRING:
  506. case CURL_ASN1_TELETEX_STRING:
  507. case CURL_ASN1_IA5_STRING:
  508. case CURL_ASN1_VISIBLE_STRING:
  509. case CURL_ASN1_UNIVERSAL_STRING:
  510. case CURL_ASN1_BMP_STRING:
  511. return string2str(type, elem->beg, elem->end);
  512. }
  513. return (const char *) NULL; /* Unsupported. */
  514. }
  515. static ssize_t encodeDN(char * buf, size_t n, curl_asn1Element * dn)
  516. {
  517. curl_asn1Element rdn;
  518. curl_asn1Element atv;
  519. curl_asn1Element oid;
  520. curl_asn1Element value;
  521. size_t l = 0;
  522. const char * p1;
  523. const char * p2;
  524. const char * p3;
  525. const char * str;
  526. /* ASCII encode distinguished name at `dn' into the `n'-byte buffer at `buf'.
  527. Return the total string length, even if larger than `n'. */
  528. for(p1 = dn->beg; p1 < dn->end;) {
  529. p1 = Curl_getASN1Element(&rdn, p1, dn->end);
  530. for(p2 = rdn.beg; p2 < rdn.end;) {
  531. p2 = Curl_getASN1Element(&atv, p2, rdn.end);
  532. p3 = Curl_getASN1Element(&oid, atv.beg, atv.end);
  533. Curl_getASN1Element(&value, p3, atv.end);
  534. str = Curl_ASN1tostr(&oid, 0);
  535. if(!str)
  536. return -1;
  537. /* Encode delimiter.
  538. If attribute has a short uppercase name, delimiter is ", ". */
  539. if(l) {
  540. for(p3 = str; isupper(*p3); p3++)
  541. ;
  542. for(p3 = (*p3 || p3 - str > 2)? "/": ", "; *p3; p3++) {
  543. if(l < n)
  544. buf[l] = *p3;
  545. l++;
  546. }
  547. }
  548. /* Encode attribute name. */
  549. for(p3 = str; *p3; p3++) {
  550. if(l < n)
  551. buf[l] = *p3;
  552. l++;
  553. }
  554. free((char *) str);
  555. /* Generate equal sign. */
  556. if(l < n)
  557. buf[l] = '=';
  558. l++;
  559. /* Generate value. */
  560. str = Curl_ASN1tostr(&value, 0);
  561. if(!str)
  562. return -1;
  563. for(p3 = str; *p3; p3++) {
  564. if(l < n)
  565. buf[l] = *p3;
  566. l++;
  567. }
  568. free((char *) str);
  569. }
  570. }
  571. return l;
  572. }
  573. const char * Curl_DNtostr(curl_asn1Element * dn)
  574. {
  575. char * buf = (char *) NULL;
  576. ssize_t n = encodeDN(buf, 0, dn);
  577. /* Convert an ASN.1 distinguished name into a printable string.
  578. Return the dynamically allocated string, or NULL if an error occurs. */
  579. if(n >= 0) {
  580. buf = malloc(n + 1);
  581. if(buf) {
  582. encodeDN(buf, n + 1, dn);
  583. buf[n] = '\0';
  584. }
  585. }
  586. return (const char *) buf;
  587. }
  588. /*
  589. * X509 parser.
  590. */
  591. void Curl_parseX509(curl_X509certificate * cert,
  592. const char * beg, const char * end)
  593. {
  594. curl_asn1Element elem;
  595. curl_asn1Element tbsCertificate;
  596. const char * ccp;
  597. static const char defaultVersion = 0; /* v1. */
  598. /* ASN.1 parse an X509 certificate into structure subfields.
  599. Syntax is assumed to have already been checked by the SSL backend.
  600. See RFC 5280. */
  601. cert->certificate.header = NULL;
  602. cert->certificate.beg = beg;
  603. cert->certificate.end = end;
  604. /* Get the sequence content. */
  605. Curl_getASN1Element(&elem, beg, end);
  606. beg = elem.beg;
  607. end = elem.end;
  608. /* Get tbsCertificate. */
  609. beg = Curl_getASN1Element(&tbsCertificate, beg, end);
  610. /* Skip the signatureAlgorithm. */
  611. beg = Curl_getASN1Element(&cert->signatureAlgorithm, beg, end);
  612. /* Get the signatureValue. */
  613. Curl_getASN1Element(&cert->signature, beg, end);
  614. /* Parse TBSCertificate. */
  615. beg = tbsCertificate.beg;
  616. end = tbsCertificate.end;
  617. /* Get optional version, get serialNumber. */
  618. cert->version.header = NULL;
  619. cert->version.beg = &defaultVersion;
  620. cert->version.end = &defaultVersion + sizeof defaultVersion;;
  621. beg = Curl_getASN1Element(&elem, beg, end);
  622. if(elem.tag == 0) {
  623. Curl_getASN1Element(&cert->version, elem.beg, elem.end);
  624. beg = Curl_getASN1Element(&elem, beg, end);
  625. }
  626. cert->serialNumber = elem;
  627. /* Get signature algorithm. */
  628. beg = Curl_getASN1Element(&cert->signatureAlgorithm, beg, end);
  629. /* Get issuer. */
  630. beg = Curl_getASN1Element(&cert->issuer, beg, end);
  631. /* Get notBefore and notAfter. */
  632. beg = Curl_getASN1Element(&elem, beg, end);
  633. ccp = Curl_getASN1Element(&cert->notBefore, elem.beg, elem.end);
  634. Curl_getASN1Element(&cert->notAfter, ccp, elem.end);
  635. /* Get subject. */
  636. beg = Curl_getASN1Element(&cert->subject, beg, end);
  637. /* Get subjectPublicKeyAlgorithm and subjectPublicKey. */
  638. beg = Curl_getASN1Element(&cert->subjectPublicKeyInfo, beg, end);
  639. ccp = Curl_getASN1Element(&cert->subjectPublicKeyAlgorithm,
  640. cert->subjectPublicKeyInfo.beg,
  641. cert->subjectPublicKeyInfo.end);
  642. Curl_getASN1Element(&cert->subjectPublicKey, ccp,
  643. cert->subjectPublicKeyInfo.end);
  644. /* Get optional issuerUiqueID, subjectUniqueID and extensions. */
  645. cert->issuerUniqueID.tag = cert->subjectUniqueID.tag = 0;
  646. cert->extensions.tag = elem.tag = 0;
  647. cert->issuerUniqueID.header = cert->subjectUniqueID.header = NULL;
  648. cert->issuerUniqueID.beg = cert->issuerUniqueID.end = "";
  649. cert->subjectUniqueID.beg = cert->subjectUniqueID.end = "";
  650. cert->extensions.header = NULL;
  651. cert->extensions.beg = cert->extensions.end = "";
  652. if(beg < end)
  653. beg = Curl_getASN1Element(&elem, beg, end);
  654. if(elem.tag == 1) {
  655. cert->issuerUniqueID = elem;
  656. if(beg < end)
  657. beg = Curl_getASN1Element(&elem, beg, end);
  658. }
  659. if(elem.tag == 2) {
  660. cert->subjectUniqueID = elem;
  661. if(beg < end)
  662. beg = Curl_getASN1Element(&elem, beg, end);
  663. }
  664. if(elem.tag == 3)
  665. Curl_getASN1Element(&cert->extensions, elem.beg, elem.end);
  666. }
  667. static size_t copySubstring(char * to, const char * from)
  668. {
  669. size_t i;
  670. /* Copy at most 64-characters, terminate with a newline and returns the
  671. effective number of stored characters. */
  672. for(i = 0; i < 64; i++) {
  673. to[i] = *from;
  674. if(!*from++)
  675. break;
  676. }
  677. to[i++] = '\n';
  678. return i;
  679. }
  680. static const char * dumpAlgo(curl_asn1Element * param,
  681. const char * beg, const char * end)
  682. {
  683. curl_asn1Element oid;
  684. /* Get algorithm parameters and return algorithm name. */
  685. beg = Curl_getASN1Element(&oid, beg, end);
  686. param->header = NULL;
  687. param->tag = 0;
  688. param->beg = param->end = end;
  689. if(beg < end)
  690. Curl_getASN1Element(param, beg, end);
  691. return OID2str(oid.beg, oid.end, TRUE);
  692. }
  693. static void do_pubkey_field(struct SessionHandle * data, int certnum,
  694. const char * label, curl_asn1Element * elem)
  695. {
  696. const char * output;
  697. /* Generate a certificate information record for the public key. */
  698. output = Curl_ASN1tostr(elem, 0);
  699. if(output) {
  700. if(data->set.ssl.certinfo)
  701. Curl_ssl_push_certinfo(data, certnum, label, output);
  702. if(!certnum)
  703. infof(data, " %s: %s\n", label, output);
  704. free((char *) output);
  705. }
  706. }
  707. static void do_pubkey(struct SessionHandle * data, int certnum,
  708. const char * algo, curl_asn1Element * param,
  709. curl_asn1Element * pubkey)
  710. {
  711. curl_asn1Element elem;
  712. curl_asn1Element pk;
  713. const char * p;
  714. const char * q;
  715. unsigned long len;
  716. unsigned int i;
  717. /* Generate all information records for the public key. */
  718. /* Get the public key (single element). */
  719. Curl_getASN1Element(&pk, pubkey->beg + 1, pubkey->end);
  720. if(curl_strequal(algo, "rsaEncryption")) {
  721. p = Curl_getASN1Element(&elem, pk.beg, pk.end);
  722. /* Compute key length. */
  723. for(q = elem.beg; !*q && q < elem.end; q++)
  724. ;
  725. len = (elem.end - q) * 8;
  726. if(len)
  727. for(i = *(unsigned char *) q; !(i & 0x80); i <<= 1)
  728. len--;
  729. if(len > 32)
  730. elem.beg = q; /* Strip leading zero bytes. */
  731. if(!certnum)
  732. infof(data, " RSA Public Key (%lu bits)\n", len);
  733. if(data->set.ssl.certinfo) {
  734. q = curl_maprintf("%lu", len);
  735. if(q) {
  736. Curl_ssl_push_certinfo(data, certnum, "RSA Public Key", q);
  737. free((char *) q);
  738. }
  739. }
  740. /* Generate coefficients. */
  741. do_pubkey_field(data, certnum, "rsa(n)", &elem);
  742. Curl_getASN1Element(&elem, p, pk.end);
  743. do_pubkey_field(data, certnum, "rsa(e)", &elem);
  744. }
  745. else if(curl_strequal(algo, "dsa")) {
  746. p = Curl_getASN1Element(&elem, param->beg, param->end);
  747. do_pubkey_field(data, certnum, "dsa(p)", &elem);
  748. p = Curl_getASN1Element(&elem, p, param->end);
  749. do_pubkey_field(data, certnum, "dsa(q)", &elem);
  750. Curl_getASN1Element(&elem, p, param->end);
  751. do_pubkey_field(data, certnum, "dsa(g)", &elem);
  752. do_pubkey_field(data, certnum, "dsa(pub_key)", &pk);
  753. }
  754. else if(curl_strequal(algo, "dhpublicnumber")) {
  755. p = Curl_getASN1Element(&elem, param->beg, param->end);
  756. do_pubkey_field(data, certnum, "dh(p)", &elem);
  757. Curl_getASN1Element(&elem, param->beg, param->end);
  758. do_pubkey_field(data, certnum, "dh(g)", &elem);
  759. do_pubkey_field(data, certnum, "dh(pub_key)", &pk);
  760. }
  761. #if 0 /* Patent-encumbered. */
  762. else if(curl_strequal(algo, "ecPublicKey")) {
  763. /* Left TODO. */
  764. }
  765. #endif
  766. }
  767. CURLcode Curl_extract_certinfo(struct connectdata * conn,
  768. int certnum,
  769. const char * beg,
  770. const char * end)
  771. {
  772. curl_X509certificate cert;
  773. struct SessionHandle * data = conn->data;
  774. curl_asn1Element param;
  775. const char * ccp;
  776. char * cp1;
  777. size_t cl1;
  778. char * cp2;
  779. CURLcode result;
  780. unsigned long version;
  781. size_t i;
  782. size_t j;
  783. if(!data->set.ssl.certinfo)
  784. if(certnum)
  785. return CURLE_OK;
  786. /* Prepare the certificate information for curl_easy_getinfo(). */
  787. /* Extract the certificate ASN.1 elements. */
  788. Curl_parseX509(&cert, beg, end);
  789. /* Subject. */
  790. ccp = Curl_DNtostr(&cert.subject);
  791. if(!ccp)
  792. return CURLE_OUT_OF_MEMORY;
  793. if(data->set.ssl.certinfo)
  794. Curl_ssl_push_certinfo(data, certnum, "Subject", ccp);
  795. if(!certnum)
  796. infof(data, "%2d Subject: %s\n", certnum, ccp);
  797. free((char *) ccp);
  798. /* Issuer. */
  799. ccp = Curl_DNtostr(&cert.issuer);
  800. if(!ccp)
  801. return CURLE_OUT_OF_MEMORY;
  802. if(data->set.ssl.certinfo)
  803. Curl_ssl_push_certinfo(data, certnum, "Issuer", ccp);
  804. if(!certnum)
  805. infof(data, " Issuer: %s\n", ccp);
  806. free((char *) ccp);
  807. /* Version (always fits in less than 32 bits). */
  808. version = 0;
  809. for(ccp = cert.version.beg; ccp < cert.version.end; ccp++)
  810. version = (version << 8) | *(const unsigned char *) ccp;
  811. if(data->set.ssl.certinfo) {
  812. ccp = curl_maprintf("%lx", version);
  813. if(!ccp)
  814. return CURLE_OUT_OF_MEMORY;
  815. Curl_ssl_push_certinfo(data, certnum, "Version", ccp);
  816. free((char *) ccp);
  817. }
  818. if(!certnum)
  819. infof(data, " Version: %lu (0x%lx)\n", version + 1, version);
  820. /* Serial number. */
  821. ccp = Curl_ASN1tostr(&cert.serialNumber, 0);
  822. if(!ccp)
  823. return CURLE_OUT_OF_MEMORY;
  824. if(data->set.ssl.certinfo)
  825. Curl_ssl_push_certinfo(data, certnum, "Serial Number", ccp);
  826. if(!certnum)
  827. infof(data, " Serial Number: %s\n", ccp);
  828. free((char *) ccp);
  829. /* Signature algorithm .*/
  830. ccp = dumpAlgo(&param, cert.signatureAlgorithm.beg,
  831. cert.signatureAlgorithm.end);
  832. if(!ccp)
  833. return CURLE_OUT_OF_MEMORY;
  834. if(data->set.ssl.certinfo)
  835. Curl_ssl_push_certinfo(data, certnum, "Signature Algorithm", ccp);
  836. if(!certnum)
  837. infof(data, " Signature Algorithm: %s\n", ccp);
  838. free((char *) ccp);
  839. /* Start Date. */
  840. ccp = Curl_ASN1tostr(&cert.notBefore, 0);
  841. if(!ccp)
  842. return CURLE_OUT_OF_MEMORY;
  843. if(data->set.ssl.certinfo)
  844. Curl_ssl_push_certinfo(data, certnum, "Start Date", ccp);
  845. if(!certnum)
  846. infof(data, " Start Date: %s\n", ccp);
  847. free((char *) ccp);
  848. /* Expire Date. */
  849. ccp = Curl_ASN1tostr(&cert.notAfter, 0);
  850. if(!ccp)
  851. return CURLE_OUT_OF_MEMORY;
  852. if(data->set.ssl.certinfo)
  853. Curl_ssl_push_certinfo(data, certnum, "Expire Date", ccp);
  854. if(!certnum)
  855. infof(data, " Expire Date: %s\n", ccp);
  856. free((char *) ccp);
  857. /* Public Key Algorithm. */
  858. ccp = dumpAlgo(&param, cert.subjectPublicKeyAlgorithm.beg,
  859. cert.subjectPublicKeyAlgorithm.end);
  860. if(!ccp)
  861. return CURLE_OUT_OF_MEMORY;
  862. if(data->set.ssl.certinfo)
  863. Curl_ssl_push_certinfo(data, certnum, "Public Key Algorithm", ccp);
  864. if(!certnum)
  865. infof(data, " Public Key Algorithm: %s\n", ccp);
  866. do_pubkey(data, certnum, ccp, &param, &cert.subjectPublicKey);
  867. free((char *) ccp);
  868. /* TODO: extensions. */
  869. /* Signature. */
  870. ccp = Curl_ASN1tostr(&cert.signature, 0);
  871. if(!ccp)
  872. return CURLE_OUT_OF_MEMORY;
  873. if(data->set.ssl.certinfo)
  874. Curl_ssl_push_certinfo(data, certnum, "Signature", ccp);
  875. if(!certnum)
  876. infof(data, " Signature: %s\n", ccp);
  877. free((char *) ccp);
  878. /* Generate PEM certificate. */
  879. result = Curl_base64_encode(data, cert.certificate.beg,
  880. cert.certificate.end - cert.certificate.beg,
  881. &cp1, &cl1);
  882. if(result)
  883. return result;
  884. /* Compute the number of characters in final certificate string. Format is:
  885. -----BEGIN CERTIFICATE-----\n
  886. <max 64 base64 characters>\n
  887. .
  888. .
  889. .
  890. -----END CERTIFICATE-----\n
  891. */
  892. i = 28 + cl1 + (cl1 + 64 - 1) / 64 + 26;
  893. cp2 = malloc(i + 1);
  894. if(!cp2) {
  895. free(cp1);
  896. return CURLE_OUT_OF_MEMORY;
  897. }
  898. /* Build the certificate string. */
  899. i = copySubstring(cp2, "-----BEGIN CERTIFICATE-----");
  900. for(j = 0; j < cl1; j += 64)
  901. i += copySubstring(cp2 + i, cp1 + j);
  902. i += copySubstring(cp2 + i, "-----END CERTIFICATE-----");
  903. cp2[i] = '\0';
  904. free(cp1);
  905. if(data->set.ssl.certinfo)
  906. Curl_ssl_push_certinfo(data, certnum, "Cert", cp2);
  907. if(!certnum)
  908. infof(data, "%s\n", cp2);
  909. free(cp2);
  910. return CURLE_OK;
  911. }
  912. #endif /* USE_GSKIT or USE_NSS */
  913. #if defined(USE_GSKIT)
  914. static const char * checkOID(const char * beg, const char * end,
  915. const char * oid)
  916. {
  917. curl_asn1Element e;
  918. const char * ccp;
  919. const char * p;
  920. bool matched;
  921. /* Check if first ASN.1 element at `beg' is the given OID.
  922. Return a pointer in the source after the OID if found, else NULL. */
  923. ccp = Curl_getASN1Element(&e, beg, end);
  924. if(!ccp || e.tag != CURL_ASN1_OBJECT_IDENTIFIER)
  925. return (const char *) NULL;
  926. p = OID2str(e.beg, e.end, FALSE);
  927. if(!p)
  928. return (const char *) NULL;
  929. matched = !strcmp(p, oid);
  930. free((char *) p);
  931. return matched? ccp: (const char *) NULL;
  932. }
  933. CURLcode Curl_verifyhost(struct connectdata * conn,
  934. const char * beg, const char * end)
  935. {
  936. struct SessionHandle * data = conn->data;
  937. curl_X509certificate cert;
  938. curl_asn1Element dn;
  939. curl_asn1Element elem;
  940. curl_asn1Element ext;
  941. curl_asn1Element name;
  942. int i;
  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. i = 0;
  987. len = utf8asn1str(&dnsname, CURL_ASN1_IA5_STRING,
  988. name.beg, name.end);
  989. if(len > 0)
  990. if(strlen(dnsname) == (size_t) len)
  991. i = Curl_cert_hostcheck((const char *) dnsname, conn->host.name);
  992. if(dnsname)
  993. free(dnsname);
  994. if(!i)
  995. return CURLE_PEER_FAILED_VERIFICATION;
  996. matched = i;
  997. break;
  998. case 7: /* IP address. */
  999. matched = (size_t) (name.end - q) == addrlen &&
  1000. !memcmp(&addr, q, addrlen);
  1001. break;
  1002. }
  1003. }
  1004. }
  1005. }
  1006. switch (matched) {
  1007. case 1:
  1008. /* an alternative name matched the server hostname */
  1009. infof(data, "\t subjectAltName: %s matched\n", conn->host.dispname);
  1010. return CURLE_OK;
  1011. case 0:
  1012. /* an alternative name field existed, but didn't match and then
  1013. we MUST fail */
  1014. infof(data, "\t subjectAltName does not match %s\n", conn->host.dispname);
  1015. return CURLE_PEER_FAILED_VERIFICATION;
  1016. }
  1017. /* Process subject. */
  1018. name.header = NULL;
  1019. name.beg = name.end = "";
  1020. q = cert.subject.beg;
  1021. /* we have to look to the last occurrence of a commonName in the
  1022. distinguished one to get the most significant one. */
  1023. while(q < cert.subject.end) {
  1024. q = Curl_getASN1Element(&dn, q, cert.subject.end);
  1025. for(p = dn.beg; p < dn.end;) {
  1026. p = Curl_getASN1Element(&elem, p, dn.end);
  1027. /* We have a DN's AttributeTypeAndValue: check it in case it's a CN. */
  1028. elem.beg = checkOID(elem.beg, elem.end, cnOID);
  1029. if(elem.beg)
  1030. name = elem; /* Latch CN. */
  1031. }
  1032. }
  1033. /* Check the CN if found. */
  1034. if(!Curl_getASN1Element(&elem, name.beg, name.end))
  1035. failf(data, "SSL: unable to obtain common name from peer certificate");
  1036. else {
  1037. len = utf8asn1str(&dnsname, elem.tag, elem.beg, elem.end);
  1038. if(len < 0) {
  1039. free(dnsname);
  1040. return CURLE_OUT_OF_MEMORY;
  1041. }
  1042. if(strlen(dnsname) != (size_t) len) /* Nul byte in string ? */
  1043. failf(data, "SSL: illegal cert name field");
  1044. else if(Curl_cert_hostcheck((const char *) dnsname, conn->host.name)) {
  1045. infof(data, "\t common name: %s (matched)\n", dnsname);
  1046. free(dnsname);
  1047. return CURLE_OK;
  1048. }
  1049. else
  1050. failf(data, "SSL: certificate subject name '%s' does not match "
  1051. "target host name '%s'", dnsname, conn->host.dispname);
  1052. free(dnsname);
  1053. }
  1054. return CURLE_PEER_FAILED_VERIFICATION;
  1055. }
  1056. #endif /* USE_GSKIT */