ssluse.c 26 KB

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