ssluse.c 44 KB

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