ssluse.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2002, 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 "urldata.h"
  31. #include "sendf.h"
  32. #include "formdata.h" /* for the boundary function */
  33. #ifdef USE_SSLEAY
  34. #include <openssl/rand.h>
  35. /* The last #include file should be: */
  36. #ifdef MALLOCDEBUG
  37. #include "memdebug.h"
  38. #endif
  39. #if OPENSSL_VERSION_NUMBER >= 0x0090581fL
  40. #define HAVE_SSL_GET1_SESSION 1
  41. #else
  42. #undef HAVE_SSL_GET1_SESSION
  43. #endif
  44. #if OPENSSL_VERSION_NUMBER >= 0x00904100L
  45. #define HAVE_USERDATA_IN_PWD_CALLBACK 1
  46. #else
  47. #undef HAVE_USERDATA_IN_PWD_CALLBACK
  48. #endif
  49. #if OPENSSL_VERSION_NUMBER >= 0x00907001L
  50. /* ENGINE_load_private_key() takes four arguments */
  51. #define HAVE_ENGINE_LOAD_FOUR_ARGS
  52. #else
  53. /* ENGINE_load_private_key() takes three arguments */
  54. #undef HAVE_ENGINE_LOAD_FOUR_ARGS
  55. #endif
  56. #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
  57. static char global_passwd[64];
  58. #endif
  59. static int passwd_callback(char *buf, int num, int verify
  60. #if HAVE_USERDATA_IN_PWD_CALLBACK
  61. /* This was introduced in 0.9.4, we can set this
  62. using SSL_CTX_set_default_passwd_cb_userdata()
  63. */
  64. , void *global_passwd
  65. #endif
  66. )
  67. {
  68. if(verify)
  69. fprintf(stderr, "%s\n", buf);
  70. else {
  71. if(num > (int)strlen((char *)global_passwd)) {
  72. strcpy(buf, global_passwd);
  73. return strlen(buf);
  74. }
  75. }
  76. return 0;
  77. }
  78. static
  79. bool seed_enough(int nread)
  80. {
  81. #ifdef HAVE_RAND_STATUS
  82. nread = 0; /* to prevent compiler warnings */
  83. /* only available in OpenSSL 0.9.5a and later */
  84. if(RAND_status())
  85. return TRUE;
  86. #else
  87. if(nread > 500)
  88. /* this is a very silly decision to make */
  89. return TRUE;
  90. #endif
  91. return FALSE; /* not enough */
  92. }
  93. static
  94. int random_the_seed(struct SessionHandle *data)
  95. {
  96. char *buf = data->state.buffer; /* point to the big buffer */
  97. int nread=0;
  98. /* Q: should we add support for a random file name as a libcurl option?
  99. A: Yes, it is here */
  100. #ifndef RANDOM_FILE
  101. /* if RANDOM_FILE isn't defined, we only perform this if an option tells
  102. us to! */
  103. if(data->set.ssl.random_file)
  104. #define RANDOM_FILE "" /* doesn't matter won't be used */
  105. #endif
  106. {
  107. /* let the option override the define */
  108. nread += RAND_load_file((data->set.ssl.random_file?
  109. data->set.ssl.random_file:RANDOM_FILE),
  110. 16384);
  111. if(seed_enough(nread))
  112. return nread;
  113. }
  114. #if defined(HAVE_RAND_EGD)
  115. /* only available in OpenSSL 0.9.5 and later */
  116. /* EGD_SOCKET is set at configure time or not at all */
  117. #ifndef EGD_SOCKET
  118. /* If we don't have the define set, we only do this if the egd-option
  119. is set */
  120. if(data->set.ssl.egdsocket)
  121. #define EGD_SOCKET "" /* doesn't matter won't be used */
  122. #endif
  123. {
  124. /* If there's an option and a define, the option overrides the
  125. define */
  126. int ret = RAND_egd(data->set.ssl.egdsocket?data->set.ssl.egdsocket:EGD_SOCKET);
  127. if(-1 != ret) {
  128. nread += ret;
  129. if(seed_enough(nread))
  130. return nread;
  131. }
  132. }
  133. #endif
  134. /* If we get here, it means we need to seed the PRNG using a "silly"
  135. approach! */
  136. #ifdef HAVE_RAND_SCREEN
  137. /* This one gets a random value by reading the currently shown screen */
  138. RAND_screen();
  139. nread = 100; /* just a value */
  140. #else
  141. {
  142. int len;
  143. char *area = Curl_FormBoundary();
  144. if(!area)
  145. return 3; /* out of memory */
  146. len = strlen(area);
  147. RAND_seed(area, len);
  148. free(area); /* now remove the random junk */
  149. }
  150. #endif
  151. /* generates a default path for the random seed file */
  152. buf[0]=0; /* blank it first */
  153. RAND_file_name(buf, BUFSIZE);
  154. if ( buf[0] ) {
  155. /* we got a file name to try */
  156. nread += RAND_load_file(buf, 16384);
  157. if(seed_enough(nread))
  158. return nread;
  159. }
  160. infof(data, "libcurl is now using a weak random seed!\n");
  161. return nread;
  162. }
  163. #ifndef SSL_FILETYPE_ENGINE
  164. #define SSL_FILETYPE_ENGINE 42
  165. #endif
  166. static int do_file_type(const char *type)
  167. {
  168. if (!type || !type[0])
  169. return SSL_FILETYPE_PEM;
  170. if (curl_strequal(type, "PEM"))
  171. return SSL_FILETYPE_PEM;
  172. if (curl_strequal(type, "DER"))
  173. return SSL_FILETYPE_ASN1;
  174. if (curl_strequal(type, "ENG"))
  175. return SSL_FILETYPE_ENGINE;
  176. return -1;
  177. }
  178. static
  179. int cert_stuff(struct connectdata *conn,
  180. char *cert_file,
  181. const char *cert_type,
  182. char *key_file,
  183. const char *key_type)
  184. {
  185. struct SessionHandle *data = conn->data;
  186. int file_type;
  187. if (cert_file != NULL) {
  188. SSL *ssl;
  189. X509 *x509;
  190. if(data->set.key_passwd) {
  191. #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
  192. /*
  193. * If password has been given, we store that in the global
  194. * area (*shudder*) for a while:
  195. */
  196. strcpy(global_passwd, data->set.key_passwd);
  197. #else
  198. /*
  199. * We set the password in the callback userdata
  200. */
  201. SSL_CTX_set_default_passwd_cb_userdata(conn->ssl.ctx,
  202. data->set.key_passwd);
  203. #endif
  204. /* Set passwd callback: */
  205. SSL_CTX_set_default_passwd_cb(conn->ssl.ctx, passwd_callback);
  206. }
  207. file_type = do_file_type(cert_type);
  208. switch(file_type) {
  209. case SSL_FILETYPE_PEM:
  210. /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
  211. if (SSL_CTX_use_certificate_chain_file(conn->ssl.ctx,
  212. cert_file) != 1) {
  213. failf(data, "unable to set certificate file (wrong password?)");
  214. return 0;
  215. }
  216. break;
  217. case SSL_FILETYPE_ASN1:
  218. /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
  219. we use the case above for PEM so this can only be performed with
  220. ASN1 files. */
  221. if (SSL_CTX_use_certificate_file(conn->ssl.ctx,
  222. cert_file,
  223. file_type) != 1) {
  224. failf(data, "unable to set certificate file (wrong password?)");
  225. return 0;
  226. }
  227. break;
  228. case SSL_FILETYPE_ENGINE:
  229. failf(data, "file type ENG for certificate not implemented");
  230. return 0;
  231. default:
  232. failf(data, "not supported file type '%s' for certificate", cert_type);
  233. return 0;
  234. }
  235. file_type = do_file_type(key_type);
  236. switch(file_type) {
  237. case SSL_FILETYPE_PEM:
  238. if (key_file == NULL)
  239. /* cert & key can only be in PEM case in the same file */
  240. key_file=cert_file;
  241. case SSL_FILETYPE_ASN1:
  242. if (SSL_CTX_use_PrivateKey_file(conn->ssl.ctx,
  243. key_file,
  244. file_type) != 1) {
  245. failf(data, "unable to set private key file\n");
  246. return 0;
  247. }
  248. break;
  249. case SSL_FILETYPE_ENGINE:
  250. #ifdef HAVE_OPENSSL_ENGINE_H
  251. { /* XXXX still needs some work */
  252. EVP_PKEY *priv_key = NULL;
  253. if (conn && conn->data && conn->data->engine) {
  254. #ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
  255. UI_METHOD *ui_method = UI_OpenSSL();
  256. #endif
  257. if (!key_file || !key_file[0]) {
  258. failf(data, "no key set to load from crypto engine\n");
  259. return 0;
  260. }
  261. priv_key = ENGINE_load_private_key(conn->data->engine,key_file,
  262. #ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
  263. ui_method,
  264. #endif
  265. data->set.key_passwd);
  266. if (!priv_key) {
  267. failf(data, "failed to load private key from crypto engine\n");
  268. return 0;
  269. }
  270. if (SSL_CTX_use_PrivateKey(conn->ssl.ctx, priv_key) != 1) {
  271. failf(data, "unable to set private key\n");
  272. EVP_PKEY_free(priv_key);
  273. return 0;
  274. }
  275. EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
  276. }
  277. else {
  278. failf(data, "crypto engine not set, can't load private key\n");
  279. return 0;
  280. }
  281. }
  282. #else
  283. failf(data, "file type ENG for private key not supported\n");
  284. return 0;
  285. #endif
  286. break;
  287. default:
  288. failf(data, "not supported file type for private key\n");
  289. return 0;
  290. }
  291. ssl=SSL_new(conn->ssl.ctx);
  292. x509=SSL_get_certificate(ssl);
  293. if (x509 != NULL)
  294. EVP_PKEY_copy_parameters(X509_get_pubkey(x509),
  295. SSL_get_privatekey(ssl));
  296. SSL_free(ssl);
  297. /* If we are using DSA, we can copy the parameters from
  298. * the private key */
  299. /* Now we know that a key and cert have been set against
  300. * the SSL context */
  301. if (!SSL_CTX_check_private_key(conn->ssl.ctx)) {
  302. failf(data, "Private key does not match the certificate public key");
  303. return(0);
  304. }
  305. #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
  306. /* erase it now */
  307. memset(global_passwd, 0, sizeof(global_passwd));
  308. #endif
  309. }
  310. return(1);
  311. }
  312. static
  313. int cert_verify_callback(int ok, X509_STORE_CTX *ctx)
  314. {
  315. X509 *err_cert;
  316. char buf[256];
  317. err_cert=X509_STORE_CTX_get_current_cert(ctx);
  318. X509_NAME_oneline(X509_get_subject_name(err_cert),buf,256);
  319. return ok;
  320. }
  321. #endif
  322. #ifdef USE_SSLEAY
  323. /* "global" init done? */
  324. static int init_ssl=0;
  325. /* we have the "SSL is seeded" boolean global for the application to
  326. prevent multiple time-consuming seedings in vain */
  327. static bool ssl_seeded = FALSE;
  328. #endif
  329. /* Global init */
  330. void Curl_SSL_init(void)
  331. {
  332. #ifdef USE_SSLEAY
  333. /* make sure this is only done once */
  334. if(0 != init_ssl)
  335. return;
  336. init_ssl++; /* never again */
  337. #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
  338. ENGINE_load_builtin_engines();
  339. #endif
  340. /* Lets get nice error messages */
  341. SSL_load_error_strings();
  342. /* Setup all the global SSL stuff */
  343. SSLeay_add_ssl_algorithms();
  344. #else
  345. /* SSL disabled, do nothing */
  346. #endif
  347. }
  348. /* Global cleanup */
  349. void Curl_SSL_cleanup(void)
  350. {
  351. #ifdef USE_SSLEAY
  352. if(init_ssl) {
  353. /* only cleanup if we did a previous init */
  354. /* Free the SSL error strings */
  355. ERR_free_strings();
  356. /* EVP_cleanup() removes all ciphers and digests from the
  357. table. */
  358. EVP_cleanup();
  359. #ifdef HAVE_ENGINE_cleanup
  360. ENGINE_cleanup();
  361. #endif
  362. init_ssl=0; /* not inited any more */
  363. }
  364. #else
  365. /* SSL disabled, do nothing */
  366. #endif
  367. }
  368. #ifdef USE_SSLEAY
  369. /*
  370. * This function is called when an SSL connection is closed.
  371. */
  372. void Curl_SSL_Close(struct connectdata *conn)
  373. {
  374. if (conn->ssl.use) {
  375. /*
  376. ERR_remove_state() frees the error queue associated with
  377. thread pid. If pid == 0, the current thread will have its
  378. error queue removed.
  379. Since error queue data structures are allocated
  380. automatically for new threads, they must be freed when
  381. threads are terminated in oder to avoid memory leaks.
  382. */
  383. ERR_remove_state(0);
  384. if(conn->ssl.handle) {
  385. (void)SSL_shutdown(conn->ssl.handle);
  386. SSL_set_connect_state(conn->ssl.handle);
  387. SSL_free (conn->ssl.handle);
  388. conn->ssl.handle = NULL;
  389. }
  390. if(conn->ssl.ctx) {
  391. SSL_CTX_free (conn->ssl.ctx);
  392. conn->ssl.ctx = NULL;
  393. }
  394. conn->ssl.use = FALSE; /* get back to ordinary socket usage */
  395. }
  396. }
  397. /*
  398. * This sets up a session cache to the specified size.
  399. */
  400. CURLcode Curl_SSL_InitSessions(struct SessionHandle *data, long amount)
  401. {
  402. struct curl_ssl_session *session;
  403. if(data->state.session)
  404. /* this is just a precaution to prevent multiple inits */
  405. return CURLE_OK;
  406. session = (struct curl_ssl_session *)
  407. malloc(amount * sizeof(struct curl_ssl_session));
  408. if(!session)
  409. return CURLE_OUT_OF_MEMORY;
  410. /* "blank out" the newly allocated memory */
  411. memset(session, 0, amount * sizeof(struct curl_ssl_session));
  412. /* store the info in the SSL section */
  413. data->set.ssl.numsessions = amount;
  414. data->state.session = session;
  415. data->state.sessionage = 1; /* this is brand new */
  416. return CURLE_OK;
  417. }
  418. /*
  419. * Check if there's a session ID for the given connection in the cache,
  420. * and if there's one suitable, it is returned.
  421. */
  422. static int Get_SSL_Session(struct connectdata *conn,
  423. SSL_SESSION **ssl_sessionid)
  424. {
  425. struct curl_ssl_session *check;
  426. struct SessionHandle *data = conn->data;
  427. long i;
  428. for(i=0; i< data->set.ssl.numsessions; i++) {
  429. check = &data->state.session[i];
  430. if(!check->sessionid)
  431. /* not session ID means blank entry */
  432. continue;
  433. if(strequal(conn->name, check->name) &&
  434. (conn->remote_port == check->remote_port) ) {
  435. /* yes, we have a session ID! */
  436. data->state.sessionage++; /* increase general age */
  437. check->age = data->state.sessionage; /* set this as used in this age */
  438. *ssl_sessionid = check->sessionid;
  439. return FALSE;
  440. }
  441. }
  442. *ssl_sessionid = (SSL_SESSION *)NULL;
  443. return TRUE;
  444. }
  445. /*
  446. * Kill a single session ID entry in the cache.
  447. */
  448. static int Kill_Single_Session(struct curl_ssl_session *session)
  449. {
  450. if(session->sessionid) {
  451. /* defensive check */
  452. /* free the ID */
  453. SSL_SESSION_free(session->sessionid);
  454. session->sessionid=NULL;
  455. session->age = 0; /* fresh */
  456. free(session->name);
  457. session->name = NULL; /* no name */
  458. return 0; /* ok */
  459. }
  460. else
  461. return 1;
  462. }
  463. /*
  464. * This function is called when the 'data' struct is going away. Close
  465. * down everything and free all resources!
  466. */
  467. int Curl_SSL_Close_All(struct SessionHandle *data)
  468. {
  469. int i;
  470. if(data->state.session) {
  471. for(i=0; i< data->set.ssl.numsessions; i++)
  472. /* the single-killer function handles empty table slots */
  473. Kill_Single_Session(&data->state.session[i]);
  474. /* free the cache data */
  475. free(data->state.session);
  476. }
  477. #ifdef HAVE_OPENSSL_ENGINE_H
  478. if (data->engine)
  479. {
  480. ENGINE_free(data->engine);
  481. data->engine = NULL;
  482. }
  483. #endif
  484. return 0;
  485. }
  486. /*
  487. * Extract the session id and store it in the session cache.
  488. */
  489. static int Store_SSL_Session(struct connectdata *conn)
  490. {
  491. SSL_SESSION *ssl_sessionid;
  492. int i;
  493. struct SessionHandle *data=conn->data; /* the mother of all structs */
  494. struct curl_ssl_session *store = &data->state.session[0];
  495. int oldest_age=data->state.session[0].age; /* zero if unused */
  496. /* ask OpenSSL, say please */
  497. #ifdef HAVE_SSL_GET1_SESSION
  498. ssl_sessionid = SSL_get1_session(conn->ssl.handle);
  499. /* SSL_get1_session() will increment the reference
  500. count and the session will stay in memory until explicitly freed with
  501. SSL_SESSION_free(3), regardless of its state.
  502. This function was introduced in openssl 0.9.5a. */
  503. #else
  504. ssl_sessionid = SSL_get_session(conn->ssl.handle);
  505. /* if SSL_get1_session() is unavailable, use SSL_get_session().
  506. This is an inferior option because the session can be flushed
  507. at any time by openssl. It is included only so curl compiles
  508. under versions of openssl < 0.9.5a.
  509. WARNING: How curl behaves if it's session is flushed is
  510. untested.
  511. */
  512. #endif
  513. /* Now we should add the session ID and the host name to the cache, (remove
  514. the oldest if necessary) */
  515. /* find an empty slot for us, or find the oldest */
  516. for(i=1; (i<data->set.ssl.numsessions) &&
  517. data->state.session[i].sessionid; i++) {
  518. if(data->state.session[i].age < oldest_age) {
  519. oldest_age = data->state.session[i].age;
  520. store = &data->state.session[i];
  521. }
  522. }
  523. if(i == data->set.ssl.numsessions)
  524. /* cache is full, we must "kill" the oldest entry! */
  525. Kill_Single_Session(store);
  526. else
  527. store = &data->state.session[i]; /* use this slot */
  528. /* now init the session struct wisely */
  529. store->sessionid = ssl_sessionid;
  530. store->age = data->state.sessionage; /* set current age */
  531. store->name = strdup(conn->name); /* clone host name */
  532. store->remote_port = conn->remote_port; /* port number */
  533. return 0;
  534. }
  535. static int Curl_ASN1_UTCTIME_output(struct connectdata *conn,
  536. const char *prefix,
  537. ASN1_UTCTIME *tm)
  538. {
  539. char *asn1_string;
  540. int gmt=FALSE;
  541. int i;
  542. int year=0,month=0,day=0,hour=0,minute=0,second=0;
  543. struct SessionHandle *data = conn->data;
  544. if(!data->set.verbose)
  545. return 0;
  546. i=tm->length;
  547. asn1_string=(char *)tm->data;
  548. if (i < 10)
  549. return 1;
  550. if (asn1_string[i-1] == 'Z')
  551. gmt=TRUE;
  552. for (i=0; i<10; i++)
  553. if ((asn1_string[i] > '9') || (asn1_string[i] < '0'))
  554. return 2;
  555. year= (asn1_string[0]-'0')*10+(asn1_string[1]-'0');
  556. if (year < 50)
  557. year+=100;
  558. month= (asn1_string[2]-'0')*10+(asn1_string[3]-'0');
  559. if ((month > 12) || (month < 1))
  560. return 3;
  561. day= (asn1_string[4]-'0')*10+(asn1_string[5]-'0');
  562. hour= (asn1_string[6]-'0')*10+(asn1_string[7]-'0');
  563. minute= (asn1_string[8]-'0')*10+(asn1_string[9]-'0');
  564. if ( (asn1_string[10] >= '0') && (asn1_string[10] <= '9') &&
  565. (asn1_string[11] >= '0') && (asn1_string[11] <= '9'))
  566. second= (asn1_string[10]-'0')*10+(asn1_string[11]-'0');
  567. infof(data,
  568. "%s%04d-%02d-%02d %02d:%02d:%02d %s\n",
  569. prefix, year+1900, month, day, hour, minute, second, (gmt?"GMT":""));
  570. return 0;
  571. }
  572. #endif
  573. /* ====================================================== */
  574. CURLcode
  575. Curl_SSLConnect(struct connectdata *conn)
  576. {
  577. CURLcode retcode = CURLE_OK;
  578. #ifdef USE_SSLEAY
  579. struct SessionHandle *data = conn->data;
  580. int err;
  581. char * str;
  582. SSL_METHOD *req_method;
  583. SSL_SESSION *ssl_sessionid=NULL;
  584. ASN1_TIME *certdate;
  585. /* mark this is being ssl enabled from here on out. */
  586. conn->ssl.use = TRUE;
  587. if(!ssl_seeded || data->set.ssl.random_file || data->set.ssl.egdsocket) {
  588. /* Make funny stuff to get random input */
  589. random_the_seed(data);
  590. ssl_seeded = TRUE;
  591. }
  592. /* check to see if we've been told to use an explicit SSL/TLS version */
  593. switch(data->set.ssl.version) {
  594. default:
  595. case CURL_SSLVERSION_DEFAULT:
  596. /* we try to figure out version */
  597. req_method = SSLv23_client_method();
  598. break;
  599. case CURL_SSLVERSION_TLSv1:
  600. req_method = TLSv1_client_method();
  601. break;
  602. case CURL_SSLVERSION_SSLv2:
  603. req_method = SSLv2_client_method();
  604. break;
  605. case CURL_SSLVERSION_SSLv3:
  606. req_method = SSLv3_client_method();
  607. break;
  608. }
  609. conn->ssl.ctx = SSL_CTX_new(req_method);
  610. if(!conn->ssl.ctx) {
  611. failf(data, "SSL: couldn't create a context!");
  612. return CURLE_OUT_OF_MEMORY;
  613. }
  614. if(data->set.cert) {
  615. if (!cert_stuff(conn,
  616. data->set.cert,
  617. data->set.cert_type,
  618. data->set.key,
  619. data->set.key_type)) {
  620. /* failf() is already done in cert_stuff() */
  621. return CURLE_SSL_CERTPROBLEM;
  622. }
  623. }
  624. if(data->set.ssl.cipher_list) {
  625. if (!SSL_CTX_set_cipher_list(conn->ssl.ctx,
  626. data->set.ssl.cipher_list)) {
  627. failf(data, "failed setting cipher list");
  628. return CURLE_SSL_CIPHER;
  629. }
  630. }
  631. if(data->set.ssl.verifypeer){
  632. SSL_CTX_set_verify(conn->ssl.ctx,
  633. SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT|
  634. SSL_VERIFY_CLIENT_ONCE,
  635. cert_verify_callback);
  636. if ((data->set.ssl.CAfile || data->set.ssl.CApath) &&
  637. !SSL_CTX_load_verify_locations(conn->ssl.ctx,
  638. data->set.ssl.CAfile,
  639. data->set.ssl.CApath)) {
  640. failf(data,"error setting cerficate verify locations");
  641. return CURLE_SSL_CACERT;
  642. }
  643. }
  644. else
  645. SSL_CTX_set_verify(conn->ssl.ctx, SSL_VERIFY_NONE, cert_verify_callback);
  646. /* Lets make an SSL structure */
  647. conn->ssl.handle = SSL_new (conn->ssl.ctx);
  648. SSL_set_connect_state (conn->ssl.handle);
  649. conn->ssl.server_cert = 0x0;
  650. if(!conn->bits.reuse) {
  651. /* We're not re-using a connection, check if there's a cached ID we
  652. can/should use here! */
  653. if(!Get_SSL_Session(conn, &ssl_sessionid)) {
  654. /* we got a session id, use it! */
  655. SSL_set_session(conn->ssl.handle, ssl_sessionid);
  656. /* Informational message */
  657. infof (data, "SSL re-using session ID\n");
  658. }
  659. }
  660. /* pass the raw socket into the SSL layers */
  661. SSL_set_fd(conn->ssl.handle, conn->firstsocket);
  662. do {
  663. int what;
  664. fd_set writefd;
  665. fd_set readfd;
  666. struct timeval interval;
  667. long timeout_ms;
  668. err = SSL_connect(conn->ssl.handle);
  669. what = SSL_get_error(conn->ssl.handle, err);
  670. FD_ZERO(&writefd);
  671. FD_ZERO(&readfd);
  672. if(SSL_ERROR_WANT_READ == what)
  673. FD_SET(conn->firstsocket, &readfd);
  674. else if(SSL_ERROR_WANT_WRITE == what)
  675. FD_SET(conn->firstsocket, &writefd);
  676. else
  677. break; /* untreated error */
  678. /* Find out if any timeout is set. If not, use 300 seconds.
  679. Otherwise, figure out the most strict timeout of the two possible one
  680. and then how much time that has elapsed to know how much time we
  681. allow for the connect call */
  682. if(data->set.timeout || data->set.connecttimeout) {
  683. double has_passed;
  684. /* Evaluate in milliseconds how much time that has passed */
  685. has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.start);
  686. #ifndef min
  687. #define min(a, b) ((a) < (b) ? (a) : (b))
  688. #endif
  689. /* get the most strict timeout of the ones converted to milliseconds */
  690. if(data->set.timeout &&
  691. (data->set.timeout>data->set.connecttimeout))
  692. timeout_ms = data->set.timeout*1000;
  693. else
  694. timeout_ms = data->set.connecttimeout*1000;
  695. /* subtract the passed time */
  696. timeout_ms -= (long)has_passed;
  697. if(timeout_ms < 0) {
  698. /* a precaution, no need to continue if time already is up */
  699. failf(data, "SSL connection timeout");
  700. return CURLE_OPERATION_TIMEOUTED;
  701. }
  702. }
  703. else
  704. /* no particular time-out has been set */
  705. timeout_ms=300000; /* milliseconds, default to five minutes */
  706. interval.tv_sec = timeout_ms/1000;
  707. timeout_ms -= interval.tv_sec*1000;
  708. interval.tv_usec = timeout_ms*1000;
  709. what = select(conn->firstsocket+1, &readfd, &writefd, NULL, &interval);
  710. if(what > 0)
  711. /* reabable or writable, go loop yourself */
  712. continue;
  713. else if(0 == what) {
  714. /* timeout */
  715. failf(data, "SSL connection timeout");
  716. return CURLE_OPERATION_TIMEOUTED;
  717. }
  718. else
  719. break; /* get out of loop */
  720. } while(1);
  721. /* 1 is fine
  722. 0 is "not successful but was shut down controlled"
  723. <0 is "handshake was not successful, because a fatal error occurred" */
  724. if (err <= 0) {
  725. err = ERR_get_error();
  726. failf(data, "SSL: %s", ERR_error_string(err, NULL));
  727. return CURLE_SSL_CONNECT_ERROR;
  728. }
  729. /* Informational message */
  730. infof (data, "SSL connection using %s\n",
  731. SSL_get_cipher(conn->ssl.handle));
  732. if(!ssl_sessionid) {
  733. /* Since this is not a cached session ID, then we want to stach this one
  734. in the cache! */
  735. Store_SSL_Session(conn);
  736. }
  737. /* Get server's certificate (note: beware of dynamic allocation) - opt */
  738. /* major serious hack alert -- we should check certificates
  739. * to authenticate the server; otherwise we risk man-in-the-middle
  740. * attack
  741. */
  742. conn->ssl.server_cert = SSL_get_peer_certificate (conn->ssl.handle);
  743. if(!conn->ssl.server_cert) {
  744. failf(data, "SSL: couldn't get peer certificate!");
  745. return CURLE_SSL_PEER_CERTIFICATE;
  746. }
  747. infof (data, "Server certificate:\n");
  748. str = X509_NAME_oneline (X509_get_subject_name (conn->ssl.server_cert),
  749. NULL, 0);
  750. if(!str) {
  751. failf(data, "SSL: couldn't get X509-subject!");
  752. X509_free(conn->ssl.server_cert);
  753. return CURLE_SSL_CONNECT_ERROR;
  754. }
  755. infof(data, "\t subject: %s\n", str);
  756. CRYPTO_free(str);
  757. certdate = X509_get_notBefore(conn->ssl.server_cert);
  758. Curl_ASN1_UTCTIME_output(conn, "\t start date: ", certdate);
  759. certdate = X509_get_notAfter(conn->ssl.server_cert);
  760. Curl_ASN1_UTCTIME_output(conn, "\t expire date: ", certdate);
  761. if (data->set.ssl.verifyhost) {
  762. char peer_CN[257];
  763. if (X509_NAME_get_text_by_NID(X509_get_subject_name(conn->ssl.server_cert),
  764. NID_commonName,
  765. peer_CN,
  766. sizeof(peer_CN)) < 0) {
  767. failf(data, "SSL: unable to obtain common name from peer certificate");
  768. X509_free(conn->ssl.server_cert);
  769. return CURLE_SSL_PEER_CERTIFICATE;
  770. }
  771. if (!strequal(peer_CN, conn->hostname)) {
  772. if (data->set.ssl.verifyhost > 1) {
  773. failf(data, "SSL: certificate subject name '%s' does not match "
  774. "target host name '%s'",
  775. peer_CN, conn->hostname);
  776. X509_free(conn->ssl.server_cert);
  777. return CURLE_SSL_PEER_CERTIFICATE;
  778. }
  779. else
  780. infof(data,
  781. "\t common name: %s (does not match '%s')\n",
  782. peer_CN, conn->hostname);
  783. }
  784. else
  785. infof(data, "\t common name: %s (matched)\n", peer_CN);
  786. }
  787. str = X509_NAME_oneline (X509_get_issuer_name (conn->ssl.server_cert),
  788. NULL, 0);
  789. if(!str) {
  790. failf(data, "SSL: couldn't get X509-issuer name!");
  791. X509_free(conn->ssl.server_cert);
  792. return CURLE_SSL_CONNECT_ERROR;
  793. }
  794. infof(data, "\t issuer: %s\n", str);
  795. CRYPTO_free(str);
  796. /* We could do all sorts of certificate verification stuff here before
  797. deallocating the certificate. */
  798. if(data->set.ssl.verifypeer) {
  799. data->set.ssl.certverifyresult=SSL_get_verify_result(conn->ssl.handle);
  800. if (data->set.ssl.certverifyresult != X509_V_OK) {
  801. failf(data, "SSL certificate verify result: %d",
  802. data->set.ssl.certverifyresult);
  803. retcode = CURLE_SSL_PEER_CERTIFICATE;
  804. }
  805. }
  806. else
  807. data->set.ssl.certverifyresult=0;
  808. X509_free(conn->ssl.server_cert);
  809. #else /* USE_SSLEAY */
  810. /* this is for "-ansi -Wall -pedantic" to stop complaining! (rabe) */
  811. (void) conn;
  812. #endif
  813. return retcode;
  814. }
  815. /*
  816. * local variables:
  817. * eval: (load-file "../curl-mode.el")
  818. * end:
  819. * vim600: fdm=marker
  820. * vim: et sw=2 ts=2 sts=2 tw=78
  821. */