x509asn1.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2013, 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)
  24. #include <curl/curl.h>
  25. #include "urldata.h"
  26. #include "strequal.h"
  27. #include "hostcheck.h"
  28. #include "sslgen.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 chsize;
  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. chsize = 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. chsize++;
  281. }
  282. buf[outlength + 2] = (char) (0x80 | (wc & 0x3F));
  283. wc = (wc >> 6) | 0x00000800;
  284. chsize++;
  285. }
  286. buf[outlength + 1] = (char) (0x80 | (wc & 0x3F));
  287. wc = (wc >> 6) | 0x000000C0;
  288. chsize++;
  289. }
  290. buf[outlength] = (char) wc;
  291. outlength += chsize;
  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. static const char * checkOID(const char * beg, const char * end,
  588. const char * oid)
  589. {
  590. curl_asn1Element e;
  591. const char * ccp;
  592. const char * p;
  593. bool matched;
  594. /* Check if first ASN.1 element at `beg' is the given OID.
  595. Return a pointer in the source after the OID if found, else NULL. */
  596. ccp = Curl_getASN1Element(&e, beg, end);
  597. if(!ccp || e.tag != CURL_ASN1_OBJECT_IDENTIFIER)
  598. return (const char *) NULL;
  599. p = OID2str(e.beg, e.end, FALSE);
  600. if(!p)
  601. return (const char *) NULL;
  602. matched = !strcmp(p, oid);
  603. free((char *) p);
  604. return matched? ccp: (const char *) NULL;
  605. }
  606. /*
  607. * X509 parser.
  608. */
  609. void Curl_parseX509(curl_X509certificate * cert,
  610. const char * beg, const char * end)
  611. {
  612. curl_asn1Element elem;
  613. curl_asn1Element tbsCertificate;
  614. const char * ccp;
  615. static const char defaultVersion = 0; /* v1. */
  616. /* ASN.1 parse an X509 certificate into structure subfields.
  617. Syntax is assumed to have already been checked by the SSL backend.
  618. See RFC 5280. */
  619. cert->certificate.beg = beg;
  620. cert->certificate.end = end;
  621. /* Get the sequence content. */
  622. Curl_getASN1Element(&elem, beg, end);
  623. beg = elem.beg;
  624. end = elem.end;
  625. /* Get tbsCertificate. */
  626. beg = Curl_getASN1Element(&tbsCertificate, beg, end);
  627. /* Skip the signatureAlgorithm. */
  628. beg = Curl_getASN1Element(&cert->signatureAlgorithm, beg, end);
  629. /* Get the signatureValue. */
  630. Curl_getASN1Element(&cert->signature, beg, end);
  631. /* Parse TBSCertificate. */
  632. beg = tbsCertificate.beg;
  633. end = tbsCertificate.end;
  634. /* Get optional version, get serialNumber. */
  635. cert->version.beg = &defaultVersion;
  636. cert->version.end = &defaultVersion + sizeof defaultVersion;;
  637. beg = Curl_getASN1Element(&elem, beg, end);
  638. if(elem.tag == 0) {
  639. Curl_getASN1Element(&cert->version, elem.beg, elem.end);
  640. beg = Curl_getASN1Element(&elem, beg, end);
  641. }
  642. cert->serialNumber = elem;
  643. /* Get signature algorithm. */
  644. beg = Curl_getASN1Element(&cert->signatureAlgorithm, beg, end);
  645. /* Get issuer. */
  646. beg = Curl_getASN1Element(&cert->issuer, beg, end);
  647. /* Get notBefore and notAfter. */
  648. beg = Curl_getASN1Element(&elem, beg, end);
  649. ccp = Curl_getASN1Element(&cert->notBefore, elem.beg, elem.end);
  650. Curl_getASN1Element(&cert->notAfter, ccp, elem.end);
  651. /* Get subject. */
  652. beg = Curl_getASN1Element(&cert->subject, beg, end);
  653. /* Get subjectPublicKeyAlgorithm and subjectPublicKey. */
  654. beg = Curl_getASN1Element(&elem, beg, end);
  655. ccp = Curl_getASN1Element(&cert->subjectPublicKeyAlgorithm,
  656. elem.beg, elem.end);
  657. Curl_getASN1Element(&cert->subjectPublicKey, ccp, elem.end);
  658. /* Get optional issuerUiqueID, subjectUniqueID and extensions. */
  659. cert->issuerUniqueID.tag = cert->subjectUniqueID.tag = 0;
  660. cert->extensions.tag = elem.tag = 0;
  661. cert->issuerUniqueID.beg = cert->issuerUniqueID.end = "";
  662. cert->subjectUniqueID.beg = cert->subjectUniqueID.end = "";
  663. cert->extensions.beg = cert->extensions.end = "";
  664. if(beg < end)
  665. beg = Curl_getASN1Element(&elem, beg, end);
  666. if(elem.tag == 1) {
  667. cert->issuerUniqueID = elem;
  668. if(beg < end)
  669. beg = Curl_getASN1Element(&elem, beg, end);
  670. }
  671. if(elem.tag == 2) {
  672. cert->subjectUniqueID = elem;
  673. if(beg < end)
  674. beg = Curl_getASN1Element(&elem, beg, end);
  675. }
  676. if(elem.tag == 3)
  677. Curl_getASN1Element(&cert->extensions, elem.beg, elem.end);
  678. }
  679. static size_t copySubstring(char * to, const char * from)
  680. {
  681. size_t i;
  682. /* Copy at most 64-characters, terminate with a newline and returns the
  683. effective number of stored characters. */
  684. for(i = 0; i < 64; i++) {
  685. to[i] = *from;
  686. if(!*from++)
  687. break;
  688. }
  689. to[i++] = '\n';
  690. return i;
  691. }
  692. static const char * dumpAlgo(curl_asn1Element * param,
  693. const char * beg, const char * end)
  694. {
  695. curl_asn1Element oid;
  696. /* Get algorithm parameters and return algorithm name. */
  697. beg = Curl_getASN1Element(&oid, beg, end);
  698. param->tag = 0;
  699. param->beg = param->end = end;
  700. if(beg < end)
  701. Curl_getASN1Element(param, beg, end);
  702. return OID2str(oid.beg, oid.end, TRUE);
  703. }
  704. static void do_pubkey_field(struct SessionHandle *data, int certnum,
  705. const char * label, curl_asn1Element * elem)
  706. {
  707. const char * output;
  708. /* Generate a certificate information record for the public key. */
  709. output = Curl_ASN1tostr(elem, 0);
  710. if(output) {
  711. Curl_ssl_push_certinfo(data, certnum, label, output);
  712. infof(data, " %s: %s\n", label, output);
  713. free((char *) output);
  714. }
  715. }
  716. static void do_pubkey(struct SessionHandle * data, int certnum,
  717. const char * algo, curl_asn1Element * param,
  718. curl_asn1Element * pubkey)
  719. {
  720. curl_asn1Element elem;
  721. curl_asn1Element pk;
  722. const char * p;
  723. const char * q;
  724. unsigned long len;
  725. unsigned int i;
  726. /* Generate all information records for the public key. */
  727. /* Get the public key (single element). */
  728. Curl_getASN1Element(&pk, pubkey->beg + 1, pubkey->end);
  729. if(curl_strequal(algo, "rsaEncryption")) {
  730. p = Curl_getASN1Element(&elem, pk.beg, pk.end);
  731. /* Compute key length. */
  732. for(q = elem.beg; !*q && q < elem.end; q++)
  733. ;
  734. len = (elem.end - q) * 8;
  735. if(len)
  736. for(i = *(unsigned char *) q; !(i & 0x80); i <<= 1)
  737. len--;
  738. if(len > 32)
  739. elem.beg = q; /* Strip leading zero bytes. */
  740. infof(data, " RSA Public Key (%lu bits)\n", len);
  741. q = curl_maprintf("%lu", len);
  742. if(q) {
  743. Curl_ssl_push_certinfo(data, certnum, "RSA Public Key", q);
  744. free((char *) q);
  745. }
  746. /* Generate coefficients. */
  747. do_pubkey_field(data, certnum, "rsa(n)", &elem);
  748. Curl_getASN1Element(&elem, p, pk.end);
  749. do_pubkey_field(data, certnum, "rsa(e)", &elem);
  750. }
  751. else if(curl_strequal(algo, "dsa")) {
  752. p = Curl_getASN1Element(&elem, param->beg, param->end);
  753. do_pubkey_field(data, certnum, "dsa(p)", &elem);
  754. p = Curl_getASN1Element(&elem, p, param->end);
  755. do_pubkey_field(data, certnum, "dsa(q)", &elem);
  756. Curl_getASN1Element(&elem, p, param->end);
  757. do_pubkey_field(data, certnum, "dsa(g)", &elem);
  758. do_pubkey_field(data, certnum, "dsa(pub_key)", &pk);
  759. }
  760. else if(curl_strequal(algo, "dhpublicnumber")) {
  761. p = Curl_getASN1Element(&elem, param->beg, param->end);
  762. do_pubkey_field(data, certnum, "dh(p)", &elem);
  763. Curl_getASN1Element(&elem, param->beg, param->end);
  764. do_pubkey_field(data, certnum, "dh(g)", &elem);
  765. do_pubkey_field(data, certnum, "dh(pub_key)", &pk);
  766. }
  767. #if 0 /* Patent-encumbered. */
  768. else if(curl_strequal(algo, "ecPublicKey")) {
  769. /* Left TODO. */
  770. }
  771. #endif
  772. }
  773. CURLcode Curl_extract_certinfo(struct connectdata * conn,
  774. int certnum,
  775. const char * beg,
  776. const char * end)
  777. {
  778. curl_X509certificate cert;
  779. struct SessionHandle * data = conn->data;
  780. curl_asn1Element param;
  781. const char * ccp;
  782. char * cp1;
  783. size_t cl1;
  784. char * cp2;
  785. CURLcode cc;
  786. unsigned long version;
  787. size_t i;
  788. size_t j;
  789. /* Prepare the certificate information for curl_easy_getinfo(). */
  790. /* Extract the certificate ASN.1 elements. */
  791. Curl_parseX509(&cert, beg, end);
  792. /* Subject. */
  793. ccp = Curl_DNtostr(&cert.subject);
  794. if(!ccp)
  795. return CURLE_OUT_OF_MEMORY;
  796. Curl_ssl_push_certinfo(data, certnum, "Subject", ccp);
  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. Curl_ssl_push_certinfo(data, certnum, "Issuer", ccp);
  804. infof(data, " Issuer: %s\n", ccp);
  805. free((char *) ccp);
  806. /* Version (always fits in less than 32 bits). */
  807. version = 0;
  808. for(ccp = cert.version.beg; ccp < cert.version.end; ccp++)
  809. version = (version << 8) | *(const unsigned char *) ccp;
  810. ccp = curl_maprintf("%lx", version);
  811. if(!ccp)
  812. return CURLE_OUT_OF_MEMORY;
  813. Curl_ssl_push_certinfo(data, certnum, "Version", ccp);
  814. free((char *) ccp);
  815. infof(data, " Version: %lu (0x%lx)\n", version + 1, version);
  816. /* Serial number. */
  817. ccp = Curl_ASN1tostr(&cert.serialNumber, 0);
  818. if(!ccp)
  819. return CURLE_OUT_OF_MEMORY;
  820. Curl_ssl_push_certinfo(data, certnum, "Serial Number", ccp);
  821. infof(data, " Serial Number: %s\n", ccp);
  822. free((char *) ccp);
  823. /* Signature algorithm .*/
  824. ccp = dumpAlgo(&param, cert.signatureAlgorithm.beg,
  825. cert.signatureAlgorithm.end);
  826. if(!ccp)
  827. return CURLE_OUT_OF_MEMORY;
  828. Curl_ssl_push_certinfo(data, certnum, "Signature Algorithm", ccp);
  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. Curl_ssl_push_certinfo(data, certnum, "Start Date", ccp);
  836. infof(data, " Start Date: %s\n", ccp);
  837. free((char *) ccp);
  838. /* Expire Date. */
  839. ccp = Curl_ASN1tostr(&cert.notAfter, 0);
  840. if(!ccp)
  841. return CURLE_OUT_OF_MEMORY;
  842. Curl_ssl_push_certinfo(data, certnum, "Expire Date", ccp);
  843. infof(data, " Expire Date: %s\n", ccp);
  844. free((char *) ccp);
  845. /* Public Key Algorithm. */
  846. ccp = dumpAlgo(&param, cert.subjectPublicKeyAlgorithm.beg,
  847. cert.subjectPublicKeyAlgorithm.end);
  848. if(!ccp)
  849. return CURLE_OUT_OF_MEMORY;
  850. Curl_ssl_push_certinfo(data, certnum, "Public Key Algorithm", ccp);
  851. infof(data, " Public Key Algorithm: %s\n", ccp);
  852. do_pubkey(data, certnum, ccp, &param, &cert.subjectPublicKey);
  853. free((char *) ccp);
  854. /* TODO: extensions. */
  855. /* Signature. */
  856. ccp = Curl_ASN1tostr(&cert.signature, 0);
  857. if(!ccp)
  858. return CURLE_OUT_OF_MEMORY;
  859. Curl_ssl_push_certinfo(data, certnum, "Signature", ccp);
  860. infof(data, " Signature: %s\n", ccp);
  861. free((char *) ccp);
  862. /* Generate PEM certificate. */
  863. cc = Curl_base64_encode(data, cert.certificate.beg,
  864. cert.certificate.end - cert.certificate.beg,
  865. &cp1, &cl1);
  866. if(cc != CURLE_OK)
  867. return cc;
  868. /* Compute the number of charaters in final certificate string. Format is:
  869. -----BEGIN CERTIFICATE-----\n
  870. <max 64 base64 characters>\n
  871. .
  872. .
  873. .
  874. -----END CERTIFICATE-----\n
  875. */
  876. i = 28 + cl1 + (cl1 + 64 - 1) / 64 + 26;
  877. cp2 = malloc(i + 1);
  878. if(!cp2) {
  879. free(cp1);
  880. return CURLE_OUT_OF_MEMORY;
  881. }
  882. /* Build the certificate string. */
  883. i = copySubstring(cp2, "-----BEGIN CERTIFICATE-----");
  884. for(j = 0; j < cl1; j += 64)
  885. i += copySubstring(cp2 + i, cp1 + j);
  886. i += copySubstring(cp2 + i, "-----END CERTIFICATE-----");
  887. cp2[i] = '\0';
  888. free(cp1);
  889. Curl_ssl_push_certinfo(data, certnum, "Cert", cp2);
  890. infof(data, "%s\n", cp2);
  891. free(cp2);
  892. return CURLE_OK;
  893. }
  894. CURLcode Curl_verifyhost(struct connectdata * conn,
  895. const char * beg, const char * end)
  896. {
  897. struct SessionHandle * data = conn->data;
  898. curl_X509certificate cert;
  899. curl_asn1Element dn;
  900. curl_asn1Element elem;
  901. curl_asn1Element ext;
  902. curl_asn1Element name;
  903. int i;
  904. const char * p;
  905. const char * q;
  906. char * dnsname;
  907. int matched = -1;
  908. size_t addrlen = (size_t) -1;
  909. ssize_t len;
  910. #ifdef ENABLE_IPV6
  911. struct in6_addr addr;
  912. #else
  913. struct in_addr addr;
  914. #endif
  915. /* Verify that connection server matches info in X509 certificate at
  916. `beg'..`end'. */
  917. if(!data->set.ssl.verifyhost)
  918. return CURLE_OK;
  919. if(!beg)
  920. return CURLE_PEER_FAILED_VERIFICATION;
  921. Curl_parseX509(&cert, beg, end);
  922. /* Get the server IP address. */
  923. #ifdef ENABLE_IPV6
  924. if(conn->bits.ipv6_ip && Curl_inet_pton(AF_INET6, conn->host.name, &addr))
  925. addrlen = sizeof(struct in6_addr);
  926. else
  927. #endif
  928. if(Curl_inet_pton(AF_INET, conn->host.name, &addr))
  929. addrlen = sizeof(struct in_addr);
  930. /* Process extensions. */
  931. for(p = cert.extensions.beg; p < cert.extensions.end && matched != 1;) {
  932. p = Curl_getASN1Element(&ext, p, cert.extensions.end);
  933. /* Check if extension is a subjectAlternativeName. */
  934. ext.beg = checkOID(ext.beg, ext.end, sanOID);
  935. if(ext.beg) {
  936. ext.beg = Curl_getASN1Element(&elem, ext.beg, ext.end);
  937. /* Skip critical if present. */
  938. if(elem.tag == CURL_ASN1_BOOLEAN)
  939. ext.beg = Curl_getASN1Element(&elem, ext.beg, ext.end);
  940. /* Parse the octet string contents: is a single sequence. */
  941. Curl_getASN1Element(&elem, elem.beg, elem.end);
  942. /* Check all GeneralNames. */
  943. for(q = elem.beg; matched != 1 && q < elem.end;) {
  944. q = Curl_getASN1Element(&name, q, elem.end);
  945. switch (name.tag) {
  946. case 2: /* DNS name. */
  947. i = 0;
  948. len = utf8asn1str(&dnsname, CURL_ASN1_IA5_STRING,
  949. name.beg, name.end);
  950. if(len > 0)
  951. if(strlen(dnsname) == (size_t) len)
  952. i = Curl_cert_hostcheck((const char *) dnsname, conn->host.name);
  953. if(dnsname)
  954. free(dnsname);
  955. if(!i)
  956. return CURLE_PEER_FAILED_VERIFICATION;
  957. matched = i;
  958. break;
  959. case 7: /* IP address. */
  960. matched = (size_t) (name.end - q) == addrlen &&
  961. !memcmp(&addr, q, addrlen);
  962. break;
  963. }
  964. }
  965. }
  966. }
  967. switch (matched) {
  968. case 1:
  969. /* an alternative name matched the server hostname */
  970. infof(data, "\t subjectAltName: %s matched\n", conn->host.dispname);
  971. return CURLE_OK;
  972. case 0:
  973. /* an alternative name field existed, but didn't match and then
  974. we MUST fail */
  975. infof(data, "\t subjectAltName does not match %s\n", conn->host.dispname);
  976. return CURLE_PEER_FAILED_VERIFICATION;
  977. }
  978. /* Process subject. */
  979. name.beg = name.end = "";
  980. q = cert.subject.beg;
  981. /* we have to look to the last occurrence of a commonName in the
  982. distinguished one to get the most significant one. */
  983. while(q < cert.subject.end) {
  984. q = Curl_getASN1Element(&dn, q, cert.subject.end);
  985. for(p = dn.beg; p < dn.end;) {
  986. p = Curl_getASN1Element(&elem, p, dn.end);
  987. /* We have a DN's AttributeTypeAndValue: check it in case it's a CN. */
  988. elem.beg = checkOID(elem.beg, elem.end, cnOID);
  989. if(elem.beg)
  990. name = elem; /* Latch CN. */
  991. }
  992. }
  993. /* Check the CN if found. */
  994. if(!Curl_getASN1Element(&elem, name.beg, name.end))
  995. failf(data, "SSL: unable to obtain common name from peer certificate");
  996. else {
  997. len = utf8asn1str(&dnsname, elem.tag, elem.beg, elem.end);
  998. if(len < 0) {
  999. free(dnsname);
  1000. return CURLE_OUT_OF_MEMORY;
  1001. }
  1002. if(strlen(dnsname) != (size_t) len) /* Nul byte in string ? */
  1003. failf(data, "SSL: illegal cert name field");
  1004. else if(Curl_cert_hostcheck((const char *) dnsname, conn->host.name)) {
  1005. infof(data, "\t common name: %s (matched)\n", dnsname);
  1006. free(dnsname);
  1007. return CURLE_OK;
  1008. }
  1009. else
  1010. failf(data, "SSL: certificate subject name '%s' does not match "
  1011. "target host name '%s'", dnsname, conn->host.dispname);
  1012. free(dnsname);
  1013. }
  1014. return CURLE_PEER_FAILED_VERIFICATION;
  1015. }
  1016. #endif /* USE_QSOSSL or USE_GSKIT */