x509asn1.c 34 KB

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