ssluse.c 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2005, 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. * $Id$
  22. ***************************************************************************/
  23. /*
  24. * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code
  25. * but sslgen.c should ever call or use these functions.
  26. */
  27. /*
  28. * The original SSLeay-using code for curl was written by Linas Vepstas and
  29. * Sampo Kellomaki 1998.
  30. */
  31. #include "setup.h"
  32. #include <string.h>
  33. #include <stdlib.h>
  34. #include <ctype.h>
  35. #ifdef HAVE_SYS_TYPES_H
  36. #include <sys/types.h>
  37. #endif
  38. #ifdef HAVE_SYS_SOCKET_H
  39. #include <sys/socket.h>
  40. #endif
  41. #include "urldata.h"
  42. #include "sendf.h"
  43. #include "formdata.h" /* for the boundary function */
  44. #include "url.h" /* for the ssl config check function */
  45. #include "inet_pton.h"
  46. #include "ssluse.h"
  47. #include "connect.h" /* Curl_ourerrno() proto */
  48. #include "strequal.h"
  49. #include "select.h"
  50. #include "sslgen.h"
  51. #define _MPRINTF_REPLACE /* use the internal *printf() functions */
  52. #include <curl/mprintf.h>
  53. #ifdef USE_SSLEAY
  54. #ifdef USE_OPENSSL
  55. #include <openssl/rand.h>
  56. #include <openssl/x509v3.h>
  57. #else
  58. #include <rand.h>
  59. #include <x509v3.h>
  60. #endif
  61. #include "memory.h"
  62. /* The last #include file should be: */
  63. #include "memdebug.h"
  64. #ifndef min
  65. #define min(a, b) ((a) < (b) ? (a) : (b))
  66. #endif
  67. #if OPENSSL_VERSION_NUMBER >= 0x0090581fL
  68. #define HAVE_SSL_GET1_SESSION 1
  69. #else
  70. #undef HAVE_SSL_GET1_SESSION
  71. #endif
  72. #if OPENSSL_VERSION_NUMBER >= 0x00904100L
  73. #define HAVE_USERDATA_IN_PWD_CALLBACK 1
  74. #else
  75. #undef HAVE_USERDATA_IN_PWD_CALLBACK
  76. #endif
  77. #if OPENSSL_VERSION_NUMBER >= 0x00907001L
  78. /* ENGINE_load_private_key() takes four arguments */
  79. #define HAVE_ENGINE_LOAD_FOUR_ARGS
  80. #else
  81. /* ENGINE_load_private_key() takes three arguments */
  82. #undef HAVE_ENGINE_LOAD_FOUR_ARGS
  83. #endif
  84. #if (OPENSSL_VERSION_NUMBER >= 0x00903001L) && defined(HAVE_OPENSSL_PKCS12_H)
  85. /* OpenSSL has PKCS 12 support */
  86. #define HAVE_PKCS12_SUPPORT
  87. #else
  88. /* OpenSSL/SSLEay does not have PKCS12 support */
  89. #undef HAVE_PKCS12_SUPPORT
  90. #endif
  91. #if OPENSSL_VERSION_NUMBER >= 0x00906001L
  92. #define HAVE_ERR_ERROR_STRING_N 1
  93. #endif
  94. /*
  95. * Number of bytes to read from the random number seed file. This must be
  96. * a finite value (because some entropy "files" like /dev/urandom have
  97. * an infinite length), but must be large enough to provide enough
  98. * entopy to properly seed OpenSSL's PRNG.
  99. */
  100. #define RAND_LOAD_LENGTH 1024
  101. #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
  102. static char global_passwd[64];
  103. #endif
  104. static int passwd_callback(char *buf, int num, int verify
  105. #if HAVE_USERDATA_IN_PWD_CALLBACK
  106. /* This was introduced in 0.9.4, we can set this
  107. using SSL_CTX_set_default_passwd_cb_userdata()
  108. */
  109. , void *global_passwd
  110. #endif
  111. )
  112. {
  113. if(verify)
  114. fprintf(stderr, "%s\n", buf);
  115. else {
  116. if(num > (int)strlen((char *)global_passwd)) {
  117. strcpy(buf, global_passwd);
  118. return (int)strlen(buf);
  119. }
  120. }
  121. return 0;
  122. }
  123. /*
  124. * rand_enough() is a function that returns TRUE if we have seeded the random
  125. * engine properly. We use some preprocessor magic to provide a seed_enough()
  126. * macro to use, just to prevent a compiler warning on this function if we
  127. * pass in an argument that is never used.
  128. */
  129. #ifdef HAVE_RAND_STATUS
  130. #define seed_enough(x) rand_enough()
  131. static bool rand_enough(void)
  132. {
  133. return RAND_status()?TRUE:FALSE;
  134. }
  135. #else
  136. #define seed_enough(x) rand_enough(x)
  137. static bool rand_enough(int nread)
  138. {
  139. /* this is a very silly decision to make */
  140. return (nread > 500)?TRUE:FALSE;
  141. }
  142. #endif
  143. static
  144. int random_the_seed(struct SessionHandle *data)
  145. {
  146. char *buf = data->state.buffer; /* point to the big buffer */
  147. int nread=0;
  148. /* Q: should we add support for a random file name as a libcurl option?
  149. A: Yes, it is here */
  150. #ifndef RANDOM_FILE
  151. /* if RANDOM_FILE isn't defined, we only perform this if an option tells
  152. us to! */
  153. if(data->set.ssl.random_file)
  154. #define RANDOM_FILE "" /* doesn't matter won't be used */
  155. #endif
  156. {
  157. /* let the option override the define */
  158. nread += RAND_load_file((data->set.ssl.random_file?
  159. data->set.ssl.random_file:RANDOM_FILE),
  160. RAND_LOAD_LENGTH);
  161. if(seed_enough(nread))
  162. return nread;
  163. }
  164. #if defined(HAVE_RAND_EGD)
  165. /* only available in OpenSSL 0.9.5 and later */
  166. /* EGD_SOCKET is set at configure time or not at all */
  167. #ifndef EGD_SOCKET
  168. /* If we don't have the define set, we only do this if the egd-option
  169. is set */
  170. if(data->set.ssl.egdsocket)
  171. #define EGD_SOCKET "" /* doesn't matter won't be used */
  172. #endif
  173. {
  174. /* If there's an option and a define, the option overrides the
  175. define */
  176. int ret = RAND_egd(data->set.ssl.egdsocket?
  177. data->set.ssl.egdsocket:EGD_SOCKET);
  178. if(-1 != ret) {
  179. nread += ret;
  180. if(seed_enough(nread))
  181. return nread;
  182. }
  183. }
  184. #endif
  185. /* If we get here, it means we need to seed the PRNG using a "silly"
  186. approach! */
  187. #ifdef HAVE_RAND_SCREEN
  188. /* This one gets a random value by reading the currently shown screen */
  189. RAND_screen();
  190. nread = 100; /* just a value */
  191. #else
  192. {
  193. int len;
  194. char *area;
  195. /* Changed call to RAND_seed to use the underlying RAND_add implementation
  196. * directly. Do this in a loop, with the amount of additional entropy
  197. * being dependent upon the algorithm used by Curl_FormBoundary(): N bytes
  198. * of a 7-bit ascii set. -- Richard Gorton, March 11 2003.
  199. */
  200. do {
  201. area = Curl_FormBoundary();
  202. if(!area)
  203. return 3; /* out of memory */
  204. len = (int)strlen(area);
  205. RAND_add(area, len, (len >> 1));
  206. free(area); /* now remove the random junk */
  207. } while (!RAND_status());
  208. }
  209. #endif
  210. /* generates a default path for the random seed file */
  211. buf[0]=0; /* blank it first */
  212. RAND_file_name(buf, BUFSIZE);
  213. if(buf[0]) {
  214. /* we got a file name to try */
  215. nread += RAND_load_file(buf, RAND_LOAD_LENGTH);
  216. if(seed_enough(nread))
  217. return nread;
  218. }
  219. infof(data, "libcurl is now using a weak random seed!\n");
  220. return nread;
  221. }
  222. #ifndef SSL_FILETYPE_ENGINE
  223. #define SSL_FILETYPE_ENGINE 42
  224. #endif
  225. #ifndef SSL_FILETYPE_PKCS12
  226. #define SSL_FILETYPE_PKCS12 43
  227. #endif
  228. static int do_file_type(const char *type)
  229. {
  230. if(!type || !type[0])
  231. return SSL_FILETYPE_PEM;
  232. if(curl_strequal(type, "PEM"))
  233. return SSL_FILETYPE_PEM;
  234. if(curl_strequal(type, "DER"))
  235. return SSL_FILETYPE_ASN1;
  236. if(curl_strequal(type, "ENG"))
  237. return SSL_FILETYPE_ENGINE;
  238. if(curl_strequal(type, "P12"))
  239. return SSL_FILETYPE_PKCS12;
  240. return -1;
  241. }
  242. static
  243. int cert_stuff(struct connectdata *conn,
  244. SSL_CTX* ctx,
  245. char *cert_file,
  246. const char *cert_type,
  247. char *key_file,
  248. const char *key_type)
  249. {
  250. struct SessionHandle *data = conn->data;
  251. int file_type;
  252. if(cert_file != NULL) {
  253. SSL *ssl;
  254. X509 *x509;
  255. int cert_done = 0;
  256. if(data->set.key_passwd) {
  257. #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
  258. /*
  259. * If password has been given, we store that in the global
  260. * area (*shudder*) for a while:
  261. */
  262. size_t len = strlen(data->set.key_passwd);
  263. if(len < sizeof(global_passwd))
  264. memcpy(global_passwd, data->set.key_passwd, len+1);
  265. #else
  266. /*
  267. * We set the password in the callback userdata
  268. */
  269. SSL_CTX_set_default_passwd_cb_userdata(ctx,
  270. data->set.key_passwd);
  271. #endif
  272. /* Set passwd callback: */
  273. SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
  274. }
  275. file_type = do_file_type(cert_type);
  276. #define SSL_CLIENT_CERT_ERR \
  277. "unable to use client certificate (no key found or wrong pass phrase?)"
  278. switch(file_type) {
  279. case SSL_FILETYPE_PEM:
  280. /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
  281. if(SSL_CTX_use_certificate_chain_file(ctx,
  282. cert_file) != 1) {
  283. failf(data, SSL_CLIENT_CERT_ERR);
  284. return 0;
  285. }
  286. break;
  287. case SSL_FILETYPE_ASN1:
  288. /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
  289. we use the case above for PEM so this can only be performed with
  290. ASN1 files. */
  291. if(SSL_CTX_use_certificate_file(ctx,
  292. cert_file,
  293. file_type) != 1) {
  294. failf(data, SSL_CLIENT_CERT_ERR);
  295. return 0;
  296. }
  297. break;
  298. case SSL_FILETYPE_ENGINE:
  299. failf(data, "file type ENG for certificate not implemented");
  300. return 0;
  301. case SSL_FILETYPE_PKCS12:
  302. {
  303. #ifdef HAVE_PKCS12_SUPPORT
  304. FILE *f;
  305. PKCS12 *p12;
  306. EVP_PKEY *pri;
  307. f = fopen(cert_file,"rb");
  308. if (!f) {
  309. failf(data, "could not open PKCS12 file '%s'", cert_file);
  310. return 0;
  311. }
  312. p12 = d2i_PKCS12_fp(f, NULL);
  313. fclose(f);
  314. PKCS12_PBE_add();
  315. if (!PKCS12_parse(p12, data->set.key_passwd, &pri, &x509, NULL)) {
  316. failf(data,
  317. "could not parse PKCS12 file, check password, OpenSSL error %s",
  318. ERR_error_string(ERR_get_error(), NULL) );
  319. return 0;
  320. }
  321. PKCS12_free(p12);
  322. if(SSL_CTX_use_certificate(ctx, x509) != 1) {
  323. failf(data, SSL_CLIENT_CERT_ERR);
  324. EVP_PKEY_free(pri);
  325. X509_free(x509);
  326. return 0;
  327. }
  328. if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
  329. failf(data, "unable to use private key from PKCS12 file '%s'",
  330. cert_file);
  331. EVP_PKEY_free(pri);
  332. X509_free(x509);
  333. return 0;
  334. }
  335. EVP_PKEY_free(pri);
  336. X509_free(x509);
  337. cert_done = 1;
  338. break;
  339. #else
  340. failf(data, "file type P12 for certificate not supported");
  341. return 0;
  342. #endif
  343. }
  344. default:
  345. failf(data, "not supported file type '%s' for certificate", cert_type);
  346. return 0;
  347. }
  348. file_type = do_file_type(key_type);
  349. switch(file_type) {
  350. case SSL_FILETYPE_PEM:
  351. if(cert_done)
  352. break;
  353. if(key_file == NULL)
  354. /* cert & key can only be in PEM case in the same file */
  355. key_file=cert_file;
  356. case SSL_FILETYPE_ASN1:
  357. if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
  358. failf(data, "unable to set private key file: '%s' type %s\n",
  359. key_file, key_type?key_type:"PEM");
  360. return 0;
  361. }
  362. break;
  363. case SSL_FILETYPE_ENGINE:
  364. #ifdef HAVE_OPENSSL_ENGINE_H
  365. { /* XXXX still needs some work */
  366. EVP_PKEY *priv_key = NULL;
  367. if(conn && conn->data && conn->data->state.engine) {
  368. #ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
  369. UI_METHOD *ui_method = UI_OpenSSL();
  370. #endif
  371. if(!key_file || !key_file[0]) {
  372. failf(data, "no key set to load from crypto engine\n");
  373. return 0;
  374. }
  375. /* the typecast below was added to please mingw32 */
  376. priv_key = (EVP_PKEY *)
  377. ENGINE_load_private_key(conn->data->state.engine,key_file,
  378. #ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
  379. ui_method,
  380. #endif
  381. data->set.key_passwd);
  382. if(!priv_key) {
  383. failf(data, "failed to load private key from crypto engine\n");
  384. return 0;
  385. }
  386. if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
  387. failf(data, "unable to set private key\n");
  388. EVP_PKEY_free(priv_key);
  389. return 0;
  390. }
  391. EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
  392. }
  393. else {
  394. failf(data, "crypto engine not set, can't load private key\n");
  395. return 0;
  396. }
  397. }
  398. break;
  399. #else
  400. failf(data, "file type ENG for private key not supported\n");
  401. return 0;
  402. #endif
  403. case SSL_FILETYPE_PKCS12:
  404. if(!cert_done) {
  405. failf(data, "file type P12 for private key not supported\n");
  406. return 0;
  407. }
  408. break;
  409. default:
  410. failf(data, "not supported file type for private key\n");
  411. return 0;
  412. }
  413. ssl=SSL_new(ctx);
  414. if (NULL == ssl) {
  415. failf(data,"unable to create an SSL structure\n");
  416. return 0;
  417. }
  418. x509=SSL_get_certificate(ssl);
  419. /* This version was provided by Evan Jordan and is supposed to not
  420. leak memory as the previous version: */
  421. if(x509 != NULL) {
  422. EVP_PKEY *pktmp = X509_get_pubkey(x509);
  423. EVP_PKEY_copy_parameters(pktmp,SSL_get_privatekey(ssl));
  424. EVP_PKEY_free(pktmp);
  425. }
  426. SSL_free(ssl);
  427. /* If we are using DSA, we can copy the parameters from
  428. * the private key */
  429. /* Now we know that a key and cert have been set against
  430. * the SSL context */
  431. if(!SSL_CTX_check_private_key(ctx)) {
  432. failf(data, "Private key does not match the certificate public key");
  433. return(0);
  434. }
  435. #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
  436. /* erase it now */
  437. memset(global_passwd, 0, sizeof(global_passwd));
  438. #endif
  439. }
  440. return(1);
  441. }
  442. static
  443. int cert_verify_callback(int ok, X509_STORE_CTX *ctx)
  444. {
  445. X509 *err_cert;
  446. char buf[256];
  447. err_cert=X509_STORE_CTX_get_current_cert(ctx);
  448. X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
  449. return ok;
  450. }
  451. /* Return error string for last OpenSSL error
  452. */
  453. static char *SSL_strerror(unsigned long error, char *buf, size_t size)
  454. {
  455. #ifdef HAVE_ERR_ERROR_STRING_N
  456. /* OpenSSL 0.9.6 and later has a function named
  457. ERRO_error_string_n() that takes the size of the buffer as a
  458. third argument */
  459. ERR_error_string_n(error, buf, size);
  460. #else
  461. (void) size;
  462. ERR_error_string(error, buf);
  463. #endif
  464. return (buf);
  465. }
  466. /* we have the "SSL is seeded" boolean global for the application to
  467. prevent multiple time-consuming seedings in vain */
  468. static bool ssl_seeded = FALSE;
  469. #endif /* USE_SSLEAY */
  470. #ifdef USE_SSLEAY
  471. /**
  472. * Global SSL init
  473. *
  474. * @retval 0 error initializing SSL
  475. * @retval 1 SSL initialized successfully
  476. */
  477. int Curl_ossl_init(void)
  478. {
  479. #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
  480. ENGINE_load_builtin_engines();
  481. #endif
  482. /* Lets get nice error messages */
  483. SSL_load_error_strings();
  484. /* Setup all the global SSL stuff */
  485. if (!SSLeay_add_ssl_algorithms())
  486. return 0;
  487. return 1;
  488. }
  489. #endif /* USE_SSLEAY */
  490. #ifdef USE_SSLEAY
  491. /* Global cleanup */
  492. void Curl_ossl_cleanup(void)
  493. {
  494. /* Free the SSL error strings */
  495. ERR_free_strings();
  496. /* EVP_cleanup() removes all ciphers and digests from the
  497. table. */
  498. EVP_cleanup();
  499. #ifdef HAVE_ENGINE_cleanup
  500. ENGINE_cleanup();
  501. #endif
  502. #ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
  503. /* this function was not present in 0.9.6b, but was added sometimes
  504. later */
  505. CRYPTO_cleanup_all_ex_data();
  506. #endif
  507. }
  508. #endif /* USE_SSLEAY */
  509. /* Selects an OpenSSL crypto engine
  510. */
  511. CURLcode Curl_ossl_set_engine(struct SessionHandle *data, const char *engine)
  512. {
  513. #if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
  514. ENGINE *e = ENGINE_by_id(engine);
  515. if (!e) {
  516. failf(data, "SSL Engine '%s' not found", engine);
  517. return (CURLE_SSL_ENGINE_NOTFOUND);
  518. }
  519. if (data->state.engine) {
  520. ENGINE_finish(data->state.engine);
  521. ENGINE_free(data->state.engine);
  522. }
  523. data->state.engine = NULL;
  524. if (!ENGINE_init(e)) {
  525. char buf[256];
  526. ENGINE_free(e);
  527. failf(data, "Failed to initialise SSL Engine '%s':\n%s",
  528. engine, SSL_strerror(ERR_get_error(), buf, sizeof(buf)));
  529. return (CURLE_SSL_ENGINE_INITFAILED);
  530. }
  531. data->state.engine = e;
  532. return (CURLE_OK);
  533. #else
  534. (void)engine;
  535. failf(data, "SSL Engine not supported");
  536. return (CURLE_SSL_ENGINE_NOTFOUND);
  537. #endif
  538. }
  539. #ifdef USE_SSLEAY
  540. /* Sets engine as default for all SSL operations
  541. */
  542. CURLcode Curl_ossl_set_engine_default(struct SessionHandle *data)
  543. {
  544. #ifdef HAVE_OPENSSL_ENGINE_H
  545. if (data->state.engine) {
  546. if (ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
  547. infof(data,"set default crypto engine %s\n", data->state.engine);
  548. }
  549. else {
  550. failf(data, "set default crypto engine %s failed", data->state.engine);
  551. return CURLE_SSL_ENGINE_SETFAILED;
  552. }
  553. }
  554. #else
  555. (void) data;
  556. #endif
  557. return CURLE_OK;
  558. }
  559. #endif /* USE_SSLEAY */
  560. /* Return list of OpenSSL crypto engine names.
  561. */
  562. struct curl_slist *Curl_ossl_engines_list(struct SessionHandle *data)
  563. {
  564. struct curl_slist *list = NULL;
  565. #if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
  566. ENGINE *e;
  567. for (e = ENGINE_get_first(); e; e = ENGINE_get_next(e))
  568. list = curl_slist_append(list, ENGINE_get_id(e));
  569. #endif
  570. (void) data;
  571. return (list);
  572. }
  573. #ifdef USE_SSLEAY
  574. /*
  575. * This function is called when an SSL connection is closed.
  576. */
  577. void Curl_ossl_close(struct connectdata *conn)
  578. {
  579. int i;
  580. /*
  581. ERR_remove_state() frees the error queue associated with
  582. thread pid. If pid == 0, the current thread will have its
  583. error queue removed.
  584. Since error queue data structures are allocated
  585. automatically for new threads, they must be freed when
  586. threads are terminated in oder to avoid memory leaks.
  587. */
  588. ERR_remove_state(0);
  589. for(i=0; i<2; i++) {
  590. struct ssl_connect_data *connssl = &conn->ssl[i];
  591. if(connssl->handle) {
  592. (void)SSL_shutdown(connssl->handle);
  593. SSL_set_connect_state(connssl->handle);
  594. SSL_free (connssl->handle);
  595. connssl->handle = NULL;
  596. }
  597. if(connssl->ctx) {
  598. SSL_CTX_free (connssl->ctx);
  599. connssl->ctx = NULL;
  600. }
  601. connssl->use = FALSE; /* get back to ordinary socket usage */
  602. }
  603. }
  604. void Curl_ossl_session_free(void *ptr)
  605. {
  606. /* free the ID */
  607. SSL_SESSION_free(ptr);
  608. }
  609. /*
  610. * This function is called when the 'data' struct is going away. Close
  611. * down everything and free all resources!
  612. */
  613. int Curl_ossl_close_all(struct SessionHandle *data)
  614. {
  615. #ifdef HAVE_OPENSSL_ENGINE_H
  616. if(data->state.engine) {
  617. ENGINE_finish(data->state.engine);
  618. ENGINE_free(data->state.engine);
  619. data->state.engine = NULL;
  620. }
  621. #else
  622. (void)data;
  623. #endif
  624. return 0;
  625. }
  626. static int Curl_ASN1_UTCTIME_output(struct connectdata *conn,
  627. const char *prefix,
  628. ASN1_UTCTIME *tm)
  629. {
  630. char *asn1_string;
  631. int gmt=FALSE;
  632. int i;
  633. int year=0,month=0,day=0,hour=0,minute=0,second=0;
  634. struct SessionHandle *data = conn->data;
  635. if(!data->set.verbose)
  636. return 0;
  637. i=tm->length;
  638. asn1_string=(char *)tm->data;
  639. if(i < 10)
  640. return 1;
  641. if(asn1_string[i-1] == 'Z')
  642. gmt=TRUE;
  643. for (i=0; i<10; i++)
  644. if((asn1_string[i] > '9') || (asn1_string[i] < '0'))
  645. return 2;
  646. year= (asn1_string[0]-'0')*10+(asn1_string[1]-'0');
  647. if(year < 50)
  648. year+=100;
  649. month= (asn1_string[2]-'0')*10+(asn1_string[3]-'0');
  650. if((month > 12) || (month < 1))
  651. return 3;
  652. day= (asn1_string[4]-'0')*10+(asn1_string[5]-'0');
  653. hour= (asn1_string[6]-'0')*10+(asn1_string[7]-'0');
  654. minute= (asn1_string[8]-'0')*10+(asn1_string[9]-'0');
  655. if((asn1_string[10] >= '0') && (asn1_string[10] <= '9') &&
  656. (asn1_string[11] >= '0') && (asn1_string[11] <= '9'))
  657. second= (asn1_string[10]-'0')*10+(asn1_string[11]-'0');
  658. infof(data,
  659. "%s%04d-%02d-%02d %02d:%02d:%02d %s\n",
  660. prefix, year+1900, month, day, hour, minute, second, (gmt?"GMT":""));
  661. return 0;
  662. }
  663. #endif
  664. /* ====================================================== */
  665. #ifdef USE_SSLEAY
  666. /*
  667. * Match a hostname against a wildcard pattern.
  668. * E.g.
  669. * "foo.host.com" matches "*.host.com".
  670. *
  671. * We are a bit more liberal than RFC2818 describes in that we
  672. * accept multiple "*" in pattern (similar to what some other browsers do).
  673. * E.g.
  674. * "abc.def.domain.com" should strickly not match "*.domain.com", but we
  675. * don't consider "." to be important in CERT checking.
  676. */
  677. #define HOST_NOMATCH 0
  678. #define HOST_MATCH 1
  679. static int hostmatch(const char *hostname, const char *pattern)
  680. {
  681. while (1) {
  682. int c = *pattern++;
  683. if (c == '\0')
  684. return (*hostname ? HOST_NOMATCH : HOST_MATCH);
  685. if (c == '*') {
  686. c = *pattern;
  687. if (c == '\0') /* "*\0" matches anything remaining */
  688. return HOST_MATCH;
  689. while (*hostname) {
  690. /* The only recursive function in libcurl! */
  691. if (hostmatch(hostname++,pattern) == HOST_MATCH)
  692. return HOST_MATCH;
  693. }
  694. return HOST_NOMATCH;
  695. }
  696. if (toupper(c) != toupper(*hostname++))
  697. return HOST_NOMATCH;
  698. }
  699. }
  700. static int
  701. cert_hostcheck(const char *match_pattern, const char *hostname)
  702. {
  703. if (!match_pattern || !*match_pattern ||
  704. !hostname || !*hostname) /* sanity check */
  705. return 0;
  706. if(curl_strequal(hostname,match_pattern)) /* trivial case */
  707. return 1;
  708. if (hostmatch(hostname,match_pattern) == HOST_MATCH)
  709. return 1;
  710. return 0;
  711. }
  712. /* Quote from RFC2818 section 3.1 "Server Identity"
  713. If a subjectAltName extension of type dNSName is present, that MUST
  714. be used as the identity. Otherwise, the (most specific) Common Name
  715. field in the Subject field of the certificate MUST be used. Although
  716. the use of the Common Name is existing practice, it is deprecated and
  717. Certification Authorities are encouraged to use the dNSName instead.
  718. Matching is performed using the matching rules specified by
  719. [RFC2459]. If more than one identity of a given type is present in
  720. the certificate (e.g., more than one dNSName name, a match in any one
  721. of the set is considered acceptable.) Names may contain the wildcard
  722. character * which is considered to match any single domain name
  723. component or component fragment. E.g., *.a.com matches foo.a.com but
  724. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  725. In some cases, the URI is specified as an IP address rather than a
  726. hostname. In this case, the iPAddress subjectAltName must be present
  727. in the certificate and must exactly match the IP in the URI.
  728. */
  729. static CURLcode verifyhost(struct connectdata *conn,
  730. X509 *server_cert)
  731. {
  732. bool matched = FALSE; /* no alternative match yet */
  733. int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
  734. int addrlen = 0;
  735. struct SessionHandle *data = conn->data;
  736. STACK_OF(GENERAL_NAME) *altnames;
  737. #ifdef ENABLE_IPV6
  738. struct in6_addr addr;
  739. #else
  740. struct in_addr addr;
  741. #endif
  742. CURLcode res = CURLE_OK;
  743. #ifdef ENABLE_IPV6
  744. if(conn->bits.ipv6_ip &&
  745. Curl_inet_pton(AF_INET6, conn->host.name, &addr)) {
  746. target = GEN_IPADD;
  747. addrlen = sizeof(struct in6_addr);
  748. }
  749. else
  750. #endif
  751. if(Curl_inet_pton(AF_INET, conn->host.name, &addr)) {
  752. target = GEN_IPADD;
  753. addrlen = sizeof(struct in_addr);
  754. }
  755. /* get a "list" of alternative names */
  756. altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
  757. if(altnames) {
  758. int numalts;
  759. int i;
  760. /* get amount of alternatives, RFC2459 claims there MUST be at least
  761. one, but we don't depend on it... */
  762. numalts = sk_GENERAL_NAME_num(altnames);
  763. /* loop through all alternatives while none has matched */
  764. for (i=0; (i<numalts) && !matched; i++) {
  765. /* get a handle to alternative name number i */
  766. const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
  767. /* only check alternatives of the same type the target is */
  768. if(check->type == target) {
  769. /* get data and length */
  770. const char *altptr = (char *)ASN1_STRING_data(check->d.ia5);
  771. int altlen;
  772. switch(target) {
  773. case GEN_DNS: /* name/pattern comparison */
  774. /* The OpenSSL man page explicitly says: "In general it cannot be
  775. assumed that the data returned by ASN1_STRING_data() is null
  776. terminated or does not contain embedded nulls." But also that
  777. "The actual format of the data will depend on the actual string
  778. type itself: for example for and IA5String the data will be ASCII"
  779. Gisle researched the OpenSSL sources:
  780. "I checked the 0.9.6 and 0.9.8 sources before my patch and
  781. it always 0-terminates an IA5String."
  782. */
  783. if (cert_hostcheck(altptr, conn->host.name))
  784. matched = TRUE;
  785. break;
  786. case GEN_IPADD: /* IP address comparison */
  787. /* compare alternative IP address if the data chunk is the same size
  788. our server IP address is */
  789. altlen = ASN1_STRING_length(check->d.ia5);
  790. if((altlen == addrlen) && !memcmp(altptr, &addr, altlen))
  791. matched = TRUE;
  792. break;
  793. }
  794. }
  795. }
  796. GENERAL_NAMES_free(altnames);
  797. }
  798. if(matched)
  799. /* an alternative name matched the server hostname */
  800. infof(data, "\t subjectAltName: %s matched\n", conn->host.dispname);
  801. else {
  802. /* we have to look to the last occurence of a commonName in the
  803. distinguished one to get the most significant one. */
  804. int j,i=-1 ;
  805. /* The following is done because of a bug in 0.9.6b */
  806. unsigned char *nulstr = (unsigned char *)"";
  807. unsigned char *peer_CN = nulstr;
  808. X509_NAME *name = X509_get_subject_name(server_cert) ;
  809. if (name)
  810. while ((j=X509_NAME_get_index_by_NID(name,NID_commonName,i))>=0)
  811. i=j;
  812. /* we have the name entry and we will now convert this to a string
  813. that we can use for comparison. Doing this we support BMPstring,
  814. UTF8 etc. */
  815. if (i>=0) {
  816. ASN1_STRING *tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name,i));
  817. /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
  818. is already UTF-8 encoded. We check for this case and copy the raw
  819. string manually to avoid the problem. This code can be made
  820. conditional in the future when OpenSSL has been fixed. Work-around
  821. brought by Alexis S. L. Carvalho. */
  822. if (tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
  823. j = ASN1_STRING_length(tmp);
  824. if (j >= 0) {
  825. peer_CN = OPENSSL_malloc(j+1);
  826. if (peer_CN) {
  827. memcpy(peer_CN, ASN1_STRING_data(tmp), j);
  828. peer_CN[j] = '\0';
  829. }
  830. }
  831. }
  832. else /* not a UTF8 name */
  833. j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
  834. }
  835. if (peer_CN == nulstr)
  836. peer_CN = NULL;
  837. if (!peer_CN) {
  838. if(data->set.ssl.verifyhost > 1) {
  839. failf(data,
  840. "SSL: unable to obtain common name from peer certificate");
  841. return CURLE_SSL_PEER_CERTIFICATE;
  842. }
  843. else {
  844. /* Consider verifyhost == 1 as an "OK" for a missing CN field, but we
  845. output a note about the situation */
  846. infof(data, "\t common name: WARNING couldn't obtain\n");
  847. }
  848. }
  849. else if(!cert_hostcheck((const char *)peer_CN, conn->host.name)) {
  850. if(data->set.ssl.verifyhost > 1) {
  851. failf(data, "SSL: certificate subject name '%s' does not match "
  852. "target host name '%s'", peer_CN, conn->host.dispname);
  853. res = CURLE_SSL_PEER_CERTIFICATE;
  854. }
  855. else
  856. infof(data, "\t common name: %s (does not match '%s')\n",
  857. peer_CN, conn->host.dispname);
  858. }
  859. else {
  860. infof(data, "\t common name: %s (matched)\n", peer_CN);
  861. }
  862. if(peer_CN)
  863. OPENSSL_free(peer_CN);
  864. }
  865. return res;
  866. }
  867. #endif
  868. /* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
  869. and thus this cannot be done there. */
  870. #ifdef SSL_CTRL_SET_MSG_CALLBACK
  871. static const char *ssl_msg_type(int ssl_ver, int msg)
  872. {
  873. if (ssl_ver == SSL2_VERSION_MAJOR) {
  874. switch (msg) {
  875. case SSL2_MT_ERROR:
  876. return "Error";
  877. case SSL2_MT_CLIENT_HELLO:
  878. return "Client hello";
  879. case SSL2_MT_CLIENT_MASTER_KEY:
  880. return "Client key";
  881. case SSL2_MT_CLIENT_FINISHED:
  882. return "Client finished";
  883. case SSL2_MT_SERVER_HELLO:
  884. return "Server hello";
  885. case SSL2_MT_SERVER_VERIFY:
  886. return "Server verify";
  887. case SSL2_MT_SERVER_FINISHED:
  888. return "Server finished";
  889. case SSL2_MT_REQUEST_CERTIFICATE:
  890. return "Request CERT";
  891. case SSL2_MT_CLIENT_CERTIFICATE:
  892. return "Client CERT";
  893. }
  894. }
  895. else if (ssl_ver == SSL3_VERSION_MAJOR) {
  896. switch (msg) {
  897. case SSL3_MT_HELLO_REQUEST:
  898. return "Hello request";
  899. case SSL3_MT_CLIENT_HELLO:
  900. return "Client hello";
  901. case SSL3_MT_SERVER_HELLO:
  902. return "Server hello";
  903. case SSL3_MT_CERTIFICATE:
  904. return "CERT";
  905. case SSL3_MT_SERVER_KEY_EXCHANGE:
  906. return "Server key exchange";
  907. case SSL3_MT_CLIENT_KEY_EXCHANGE:
  908. return "Client key exchange";
  909. case SSL3_MT_CERTIFICATE_REQUEST:
  910. return "Request CERT";
  911. case SSL3_MT_SERVER_DONE:
  912. return "Server finished";
  913. case SSL3_MT_CERTIFICATE_VERIFY:
  914. return "CERT verify";
  915. case SSL3_MT_FINISHED:
  916. return "Finished";
  917. }
  918. }
  919. return "Unknown";
  920. }
  921. static const char *tls_rt_type(int type)
  922. {
  923. return (
  924. type == SSL3_RT_CHANGE_CIPHER_SPEC ? "TLS change cipher, " :
  925. type == SSL3_RT_ALERT ? "TLS alert, " :
  926. type == SSL3_RT_HANDSHAKE ? "TLS handshake, " :
  927. type == SSL3_RT_APPLICATION_DATA ? "TLS app data, " :
  928. "TLS Unknown, ");
  929. }
  930. /*
  931. * Our callback from the SSL/TLS layers.
  932. */
  933. static void ssl_tls_trace(int direction, int ssl_ver, int content_type,
  934. const void *buf, size_t len, const SSL *ssl,
  935. struct connectdata *conn)
  936. {
  937. struct SessionHandle *data;
  938. const char *msg_name, *tls_rt_name;
  939. char ssl_buf[1024];
  940. int ver, msg_type, txt_len;
  941. if (!conn || !conn->data || !conn->data->set.fdebug ||
  942. (direction != 0 && direction != 1))
  943. return;
  944. data = conn->data;
  945. ssl_ver >>= 8;
  946. ver = (ssl_ver == SSL2_VERSION_MAJOR ? '2' :
  947. ssl_ver == SSL3_VERSION_MAJOR ? '3' : '?');
  948. /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
  949. * always pass-up content-type as 0. But the interesting message-type
  950. * is at 'buf[0]'.
  951. */
  952. if (ssl_ver == SSL3_VERSION_MAJOR && content_type != 0)
  953. tls_rt_name = tls_rt_type(content_type);
  954. else
  955. tls_rt_name = "";
  956. msg_type = *(char*)buf;
  957. msg_name = ssl_msg_type(ssl_ver, msg_type);
  958. txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "SSLv%c, %s%s (%d):\n",
  959. ver, tls_rt_name, msg_name, msg_type);
  960. Curl_debug(data, CURLINFO_TEXT, ssl_buf, txt_len, NULL);
  961. Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
  962. CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL);
  963. (void) ssl;
  964. }
  965. #endif
  966. #ifdef USE_SSLEAY
  967. /* ====================================================== */
  968. CURLcode
  969. Curl_ossl_connect(struct connectdata *conn,
  970. int sockindex)
  971. {
  972. CURLcode retcode = CURLE_OK;
  973. struct SessionHandle *data = conn->data;
  974. int err;
  975. long lerr;
  976. int what;
  977. char * str;
  978. SSL_METHOD *req_method;
  979. void *ssl_sessionid=NULL;
  980. ASN1_TIME *certdate;
  981. curl_socket_t sockfd = conn->sock[sockindex];
  982. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  983. if(!ssl_seeded || data->set.ssl.random_file || data->set.ssl.egdsocket) {
  984. /* Make funny stuff to get random input */
  985. random_the_seed(data);
  986. ssl_seeded = TRUE;
  987. }
  988. /* check to see if we've been told to use an explicit SSL/TLS version */
  989. switch(data->set.ssl.version) {
  990. default:
  991. case CURL_SSLVERSION_DEFAULT:
  992. /* we try to figure out version */
  993. req_method = SSLv23_client_method();
  994. break;
  995. case CURL_SSLVERSION_TLSv1:
  996. req_method = TLSv1_client_method();
  997. break;
  998. case CURL_SSLVERSION_SSLv2:
  999. req_method = SSLv2_client_method();
  1000. break;
  1001. case CURL_SSLVERSION_SSLv3:
  1002. req_method = SSLv3_client_method();
  1003. break;
  1004. }
  1005. connssl->ctx = SSL_CTX_new(req_method);
  1006. if(!connssl->ctx) {
  1007. failf(data, "SSL: couldn't create a context!");
  1008. return CURLE_OUT_OF_MEMORY;
  1009. }
  1010. #ifdef SSL_CTRL_SET_MSG_CALLBACK
  1011. if (data->set.fdebug) {
  1012. if (!SSL_CTX_callback_ctrl(connssl->ctx, SSL_CTRL_SET_MSG_CALLBACK,
  1013. ssl_tls_trace)) {
  1014. failf(data, "SSL: couldn't set callback!");
  1015. return CURLE_SSL_CONNECT_ERROR;
  1016. }
  1017. if (!SSL_CTX_ctrl(connssl->ctx, SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, conn)) {
  1018. failf(data, "SSL: couldn't set callback argument!");
  1019. return CURLE_SSL_CONNECT_ERROR;
  1020. }
  1021. }
  1022. #endif
  1023. /* OpenSSL contains code to work-around lots of bugs and flaws in various
  1024. SSL-implementations. SSL_CTX_set_options() is used to enabled those
  1025. work-arounds. The man page for this option states that SSL_OP_ALL enables
  1026. ll the work-arounds and that "It is usually safe to use SSL_OP_ALL to
  1027. enable the bug workaround options if compatibility with somewhat broken
  1028. implementations is desired."
  1029. */
  1030. SSL_CTX_set_options(connssl->ctx, SSL_OP_ALL);
  1031. #if 0
  1032. /*
  1033. * Not sure it's needed to tell SSL_connect() that socket is
  1034. * non-blocking. It doesn't seem to care, but just return with
  1035. * SSL_ERROR_WANT_x.
  1036. */
  1037. if (data->state.used_interface == Curl_if_multi)
  1038. SSL_CTX_ctrl(connssl->ctx, BIO_C_SET_NBIO, 1, NULL);
  1039. #endif
  1040. if(data->set.cert) {
  1041. if(!cert_stuff(conn,
  1042. connssl->ctx,
  1043. data->set.cert,
  1044. data->set.cert_type,
  1045. data->set.key,
  1046. data->set.key_type)) {
  1047. /* failf() is already done in cert_stuff() */
  1048. return CURLE_SSL_CERTPROBLEM;
  1049. }
  1050. }
  1051. if(data->set.ssl.cipher_list) {
  1052. if(!SSL_CTX_set_cipher_list(connssl->ctx,
  1053. data->set.ssl.cipher_list)) {
  1054. failf(data, "failed setting cipher list");
  1055. return CURLE_SSL_CIPHER;
  1056. }
  1057. }
  1058. if (data->set.ssl.CAfile || data->set.ssl.CApath) {
  1059. /* tell SSL where to find CA certificates that are used to verify
  1060. the servers certificate. */
  1061. if (!SSL_CTX_load_verify_locations(connssl->ctx, data->set.ssl.CAfile,
  1062. data->set.ssl.CApath)) {
  1063. if (data->set.ssl.verifypeer) {
  1064. /* Fail if we insist on successfully verifying the server. */
  1065. failf(data,"error setting certificate verify locations:\n"
  1066. " CAfile: %s\n CApath: %s\n",
  1067. data->set.ssl.CAfile ? data->set.ssl.CAfile : "none",
  1068. data->set.ssl.CApath ? data->set.ssl.CApath : "none");
  1069. return CURLE_SSL_CACERT;
  1070. }
  1071. else {
  1072. /* Just continue with a warning if no strict certificate verification
  1073. is required. */
  1074. infof(data, "error setting certificate verify locations,"
  1075. " continuing anyway:\n");
  1076. }
  1077. }
  1078. else {
  1079. /* Everything is fine. */
  1080. infof(data, "successfully set certificate verify locations:\n");
  1081. }
  1082. infof(data,
  1083. " CAfile: %s\n"
  1084. " CApath: %s\n",
  1085. data->set.ssl.CAfile ? data->set.ssl.CAfile : "none",
  1086. data->set.ssl.CApath ? data->set.ssl.CApath : "none");
  1087. }
  1088. /* SSL always tries to verify the peer, this only says whether it should
  1089. * fail to connect if the verification fails, or if it should continue
  1090. * anyway. In the latter case the result of the verification is checked with
  1091. * SSL_get_verify_result() below. */
  1092. SSL_CTX_set_verify(connssl->ctx,
  1093. data->set.ssl.verifypeer?SSL_VERIFY_PEER:SSL_VERIFY_NONE,
  1094. cert_verify_callback);
  1095. /* give application a chance to interfere with SSL set up. */
  1096. if(data->set.ssl.fsslctx) {
  1097. retcode = (*data->set.ssl.fsslctx)(data, connssl->ctx,
  1098. data->set.ssl.fsslctxp);
  1099. if(retcode) {
  1100. failf(data,"error signaled by ssl ctx callback");
  1101. return retcode;
  1102. }
  1103. }
  1104. /* Lets make an SSL structure */
  1105. connssl->handle = SSL_new(connssl->ctx);
  1106. if (!connssl->handle) {
  1107. failf(data, "SSL: couldn't create a context (handle)!");
  1108. return CURLE_OUT_OF_MEMORY;
  1109. }
  1110. SSL_set_connect_state(connssl->handle);
  1111. connssl->server_cert = 0x0;
  1112. /* Check if there's a cached ID we can/should use here! */
  1113. if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)) {
  1114. /* we got a session id, use it! */
  1115. if (!SSL_set_session(connssl->handle, ssl_sessionid)) {
  1116. failf(data, "SSL: SSL_set_session failed: %s",
  1117. ERR_error_string(ERR_get_error(),NULL));
  1118. return CURLE_SSL_CONNECT_ERROR;
  1119. }
  1120. /* Informational message */
  1121. infof (data, "SSL re-using session ID\n");
  1122. }
  1123. /* pass the raw socket into the SSL layers */
  1124. if (!SSL_set_fd(connssl->handle, sockfd)) {
  1125. failf(data, "SSL: SSL_set_fd failed: %s",
  1126. ERR_error_string(ERR_get_error(),NULL));
  1127. return CURLE_SSL_CONNECT_ERROR;
  1128. }
  1129. while(1) {
  1130. int writefd;
  1131. int readfd;
  1132. long timeout_ms;
  1133. long has_passed;
  1134. /* Find out if any timeout is set. If not, use 300 seconds.
  1135. Otherwise, figure out the most strict timeout of the two possible one
  1136. and then how much time that has elapsed to know how much time we
  1137. allow for the connect call */
  1138. if(data->set.timeout || data->set.connecttimeout) {
  1139. /* get the most strict timeout of the ones converted to milliseconds */
  1140. if(data->set.timeout &&
  1141. (data->set.timeout>data->set.connecttimeout))
  1142. timeout_ms = data->set.timeout*1000;
  1143. else
  1144. timeout_ms = data->set.connecttimeout*1000;
  1145. }
  1146. else
  1147. /* no particular time-out has been set */
  1148. timeout_ms= DEFAULT_CONNECT_TIMEOUT;
  1149. /* Evaluate in milliseconds how much time that has passed */
  1150. has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.t_startsingle);
  1151. /* subtract the passed time */
  1152. timeout_ms -= has_passed;
  1153. if(timeout_ms < 0) {
  1154. /* a precaution, no need to continue if time already is up */
  1155. failf(data, "SSL connection timeout");
  1156. return CURLE_OPERATION_TIMEOUTED;
  1157. }
  1158. readfd = CURL_SOCKET_BAD;
  1159. writefd = CURL_SOCKET_BAD;
  1160. err = SSL_connect(connssl->handle);
  1161. /* 1 is fine
  1162. 0 is "not successful but was shut down controlled"
  1163. <0 is "handshake was not successful, because a fatal error occurred" */
  1164. if(1 != err) {
  1165. int detail = SSL_get_error(connssl->handle, err);
  1166. if(SSL_ERROR_WANT_READ == detail)
  1167. readfd = sockfd;
  1168. else if(SSL_ERROR_WANT_WRITE == detail)
  1169. writefd = sockfd;
  1170. else {
  1171. /* untreated error */
  1172. unsigned long errdetail;
  1173. char error_buffer[120]; /* OpenSSL documents that this must be at least
  1174. 120 bytes long. */
  1175. CURLcode rc;
  1176. const char *cert_problem = NULL;
  1177. errdetail = ERR_get_error(); /* Gets the earliest error code from the
  1178. thread's error queue and removes the
  1179. entry. */
  1180. switch(errdetail) {
  1181. case 0x1407E086:
  1182. /* 1407E086:
  1183. SSL routines:
  1184. SSL2_SET_CERTIFICATE:
  1185. certificate verify failed */
  1186. /* fall-through */
  1187. case 0x14090086:
  1188. /* 14090086:
  1189. SSL routines:
  1190. SSL3_GET_SERVER_CERTIFICATE:
  1191. certificate verify failed */
  1192. cert_problem = "SSL certificate problem, verify that the CA cert is"
  1193. " OK. Details:\n";
  1194. rc = CURLE_SSL_CACERT;
  1195. break;
  1196. default:
  1197. rc = CURLE_SSL_CONNECT_ERROR;
  1198. break;
  1199. }
  1200. /* detail is already set to the SSL error above */
  1201. /* If we e.g. use SSLv2 request-method and the server doesn't like us
  1202. * (RST connection etc.), OpenSSL gives no explanation whatsoever and
  1203. * the SO_ERROR is also lost.
  1204. */
  1205. if (CURLE_SSL_CONNECT_ERROR == rc && errdetail == 0) {
  1206. failf(data, "Unknown SSL protocol error in connection to %s:%d ",
  1207. conn->host.name, conn->port);
  1208. return rc;
  1209. }
  1210. /* Could be a CERT problem */
  1211. SSL_strerror(errdetail, error_buffer, sizeof(error_buffer));
  1212. failf(data, "%s%s", cert_problem ? cert_problem : "", error_buffer);
  1213. return rc;
  1214. }
  1215. }
  1216. else
  1217. /* we have been connected fine, get out of the connect loop */
  1218. break;
  1219. while(1) {
  1220. what = Curl_select(readfd, writefd, (int)timeout_ms);
  1221. if(what > 0)
  1222. /* reabable or writable, go loop in the outer loop */
  1223. break;
  1224. else if(0 == what) {
  1225. /* timeout */
  1226. failf(data, "SSL connection timeout");
  1227. return CURLE_OPERATION_TIMEDOUT;
  1228. }
  1229. else {
  1230. /* anything that gets here is fatally bad */
  1231. failf(data, "select on SSL socket, errno: %d", Curl_ourerrno());
  1232. return CURLE_SSL_CONNECT_ERROR;
  1233. }
  1234. } /* while()-loop for the select() */
  1235. } /* while()-loop for the SSL_connect() */
  1236. /* Informational message */
  1237. infof (data, "SSL connection using %s\n",
  1238. SSL_get_cipher(connssl->handle));
  1239. if(!ssl_sessionid) {
  1240. /* Since this is not a cached session ID, then we want to stach this one
  1241. in the cache! */
  1242. SSL_SESSION *ssl_sessionid;
  1243. #ifdef HAVE_SSL_GET1_SESSION
  1244. ssl_sessionid = SSL_get1_session(connssl->handle);
  1245. /* SSL_get1_session() will increment the reference
  1246. count and the session will stay in memory until explicitly freed with
  1247. SSL_SESSION_free(3), regardless of its state.
  1248. This function was introduced in openssl 0.9.5a. */
  1249. #else
  1250. ssl_sessionid = SSL_get_session(connssl->handle);
  1251. /* if SSL_get1_session() is unavailable, use SSL_get_session().
  1252. This is an inferior option because the session can be flushed
  1253. at any time by openssl. It is included only so curl compiles
  1254. under versions of openssl < 0.9.5a.
  1255. WARNING: How curl behaves if it's session is flushed is
  1256. untested.
  1257. */
  1258. #endif
  1259. retcode = Curl_ssl_addsessionid(conn, ssl_sessionid,
  1260. 0 /* unknown size */);
  1261. if(retcode) {
  1262. failf(data, "failed to store ssl session");
  1263. return retcode;
  1264. }
  1265. }
  1266. /* Get server's certificate (note: beware of dynamic allocation) - opt */
  1267. /* major serious hack alert -- we should check certificates
  1268. * to authenticate the server; otherwise we risk man-in-the-middle
  1269. * attack
  1270. */
  1271. connssl->server_cert = SSL_get_peer_certificate(connssl->handle);
  1272. if(!connssl->server_cert) {
  1273. failf(data, "SSL: couldn't get peer certificate!");
  1274. return CURLE_SSL_PEER_CERTIFICATE;
  1275. }
  1276. infof (data, "Server certificate:\n");
  1277. str = X509_NAME_oneline(X509_get_subject_name(connssl->server_cert),
  1278. NULL, 0);
  1279. if(!str) {
  1280. failf(data, "SSL: couldn't get X509-subject!");
  1281. X509_free(connssl->server_cert);
  1282. connssl->server_cert = NULL;
  1283. return CURLE_SSL_CONNECT_ERROR;
  1284. }
  1285. infof(data, "\t subject: %s\n", str);
  1286. CRYPTO_free(str);
  1287. certdate = X509_get_notBefore(connssl->server_cert);
  1288. Curl_ASN1_UTCTIME_output(conn, "\t start date: ", certdate);
  1289. certdate = X509_get_notAfter(connssl->server_cert);
  1290. Curl_ASN1_UTCTIME_output(conn, "\t expire date: ", certdate);
  1291. if(data->set.ssl.verifyhost) {
  1292. retcode = verifyhost(conn, connssl->server_cert);
  1293. if(retcode) {
  1294. X509_free(connssl->server_cert);
  1295. connssl->server_cert = NULL;
  1296. return retcode;
  1297. }
  1298. }
  1299. str = X509_NAME_oneline(X509_get_issuer_name(connssl->server_cert),
  1300. NULL, 0);
  1301. if(!str) {
  1302. failf(data, "SSL: couldn't get X509-issuer name!");
  1303. retcode = CURLE_SSL_CONNECT_ERROR;
  1304. }
  1305. else {
  1306. infof(data, "\t issuer: %s\n", str);
  1307. CRYPTO_free(str);
  1308. /* We could do all sorts of certificate verification stuff here before
  1309. deallocating the certificate. */
  1310. lerr = data->set.ssl.certverifyresult=
  1311. SSL_get_verify_result(connssl->handle);
  1312. if(data->set.ssl.certverifyresult != X509_V_OK) {
  1313. if(data->set.ssl.verifypeer) {
  1314. /* We probably never reach this, because SSL_connect() will fail
  1315. and we return earlyer if verifypeer is set? */
  1316. failf(data, "SSL certificate verify result: %s (%ld)",
  1317. X509_verify_cert_error_string(lerr), lerr);
  1318. retcode = CURLE_SSL_PEER_CERTIFICATE;
  1319. }
  1320. else
  1321. infof(data, "SSL certificate verify result: %s (%ld),"
  1322. " continuing anyway.\n",
  1323. X509_verify_cert_error_string(err), lerr);
  1324. }
  1325. else
  1326. infof(data, "SSL certificate verify ok.\n");
  1327. }
  1328. X509_free(connssl->server_cert);
  1329. connssl->server_cert = NULL;
  1330. return retcode;
  1331. }
  1332. /* return number of sent (non-SSL) bytes */
  1333. int Curl_ossl_send(struct connectdata *conn,
  1334. int sockindex,
  1335. void *mem,
  1336. size_t len)
  1337. {
  1338. /* SSL_write() is said to return 'int' while write() and send() returns
  1339. 'size_t' */
  1340. int err;
  1341. char error_buffer[120]; /* OpenSSL documents that this must be at least 120
  1342. bytes long. */
  1343. unsigned long sslerror;
  1344. int rc = SSL_write(conn->ssl[sockindex].handle, mem, (int)len);
  1345. if(rc < 0) {
  1346. err = SSL_get_error(conn->ssl[sockindex].handle, rc);
  1347. switch(err) {
  1348. case SSL_ERROR_WANT_READ:
  1349. case SSL_ERROR_WANT_WRITE:
  1350. /* The operation did not complete; the same TLS/SSL I/O function
  1351. should be called again later. This is basicly an EWOULDBLOCK
  1352. equivalent. */
  1353. return 0;
  1354. case SSL_ERROR_SYSCALL:
  1355. failf(conn->data, "SSL_write() returned SYSCALL, errno = %d\n",
  1356. Curl_ourerrno());
  1357. return -1;
  1358. case SSL_ERROR_SSL:
  1359. /* A failure in the SSL library occurred, usually a protocol error.
  1360. The OpenSSL error queue contains more information on the error. */
  1361. sslerror = ERR_get_error();
  1362. failf(conn->data, "SSL_write() error: %s\n",
  1363. ERR_error_string(sslerror, error_buffer));
  1364. return -1;
  1365. }
  1366. /* a true error */
  1367. failf(conn->data, "SSL_write() return error %d\n", err);
  1368. return -1;
  1369. }
  1370. return rc; /* number of bytes */
  1371. }
  1372. /*
  1373. * If the read would block we return -1 and set 'wouldblock' to TRUE.
  1374. * Otherwise we return the amount of data read. Other errors should return -1
  1375. * and set 'wouldblock' to FALSE.
  1376. */
  1377. ssize_t Curl_ossl_recv(struct connectdata *conn, /* connection data */
  1378. int num, /* socketindex */
  1379. char *buf, /* store read data here */
  1380. size_t buffersize, /* max amount to read */
  1381. bool *wouldblock)
  1382. {
  1383. char error_buffer[120]; /* OpenSSL documents that this must be at
  1384. least 120 bytes long. */
  1385. unsigned long sslerror;
  1386. ssize_t nread = (ssize_t)SSL_read(conn->ssl[num].handle, buf,
  1387. (int)buffersize);
  1388. *wouldblock = FALSE;
  1389. if(nread < 0) {
  1390. /* failed SSL_read */
  1391. int err = SSL_get_error(conn->ssl[num].handle, (int)nread);
  1392. switch(err) {
  1393. case SSL_ERROR_NONE: /* this is not an error */
  1394. case SSL_ERROR_ZERO_RETURN: /* no more data */
  1395. break;
  1396. case SSL_ERROR_WANT_READ:
  1397. case SSL_ERROR_WANT_WRITE:
  1398. /* there's data pending, re-invoke SSL_read() */
  1399. *wouldblock = TRUE;
  1400. return -1; /* basically EWOULDBLOCK */
  1401. default:
  1402. /* openssl/ssl.h says "look at error stack/return value/errno" */
  1403. sslerror = ERR_get_error();
  1404. failf(conn->data, "SSL read: %s, errno %d",
  1405. ERR_error_string(sslerror, error_buffer),
  1406. Curl_ourerrno() );
  1407. return -1;
  1408. }
  1409. }
  1410. return nread;
  1411. }
  1412. size_t Curl_ossl_version(char *buffer, size_t size)
  1413. {
  1414. #if (SSLEAY_VERSION_NUMBER >= 0x905000)
  1415. {
  1416. char sub[2];
  1417. unsigned long ssleay_value;
  1418. sub[1]='\0';
  1419. ssleay_value=SSLeay();
  1420. if(ssleay_value < 0x906000) {
  1421. ssleay_value=SSLEAY_VERSION_NUMBER;
  1422. sub[0]='\0';
  1423. }
  1424. else {
  1425. if(ssleay_value&0xff0) {
  1426. sub[0]=(char)((ssleay_value>>4)&0xff) + 'a' -1;
  1427. }
  1428. else
  1429. sub[0]='\0';
  1430. }
  1431. return snprintf(buffer, size, " OpenSSL/%lx.%lx.%lx%s",
  1432. (ssleay_value>>28)&0xf,
  1433. (ssleay_value>>20)&0xff,
  1434. (ssleay_value>>12)&0xff,
  1435. sub);
  1436. }
  1437. #else /* SSLEAY_VERSION_NUMBER is less than 0.9.5 */
  1438. #if (SSLEAY_VERSION_NUMBER >= 0x900000)
  1439. return snprintf(buffer, size, " OpenSSL/%lx.%lx.%lx",
  1440. (SSLEAY_VERSION_NUMBER>>28)&0xff,
  1441. (SSLEAY_VERSION_NUMBER>>20)&0xff,
  1442. (SSLEAY_VERSION_NUMBER>>12)&0xf);
  1443. #else /* (SSLEAY_VERSION_NUMBER >= 0x900000) */
  1444. {
  1445. char sub[2];
  1446. sub[1]='\0';
  1447. if(SSLEAY_VERSION_NUMBER&0x0f) {
  1448. sub[0]=(SSLEAY_VERSION_NUMBER&0x0f) + 'a' -1;
  1449. }
  1450. else
  1451. sub[0]='\0';
  1452. return snprintf(buffer, size, " SSL/%x.%x.%x%s",
  1453. (SSLEAY_VERSION_NUMBER>>12)&0xff,
  1454. (SSLEAY_VERSION_NUMBER>>8)&0xf,
  1455. (SSLEAY_VERSION_NUMBER>>4)&0xf, sub);
  1456. }
  1457. #endif /* (SSLEAY_VERSION_NUMBER >= 0x900000) */
  1458. #endif /* SSLEAY_VERSION_NUMBER is less than 0.9.5 */
  1459. }
  1460. #endif /* USE_SSLEAY */