x509asn1.c 35 KB

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