ssluse.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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: '%s' type %s\n",
  246. key_file, key_type?key_type:"PEM");
  247. return 0;
  248. }
  249. break;
  250. case SSL_FILETYPE_ENGINE:
  251. #ifdef HAVE_OPENSSL_ENGINE_H
  252. { /* XXXX still needs some work */
  253. EVP_PKEY *priv_key = NULL;
  254. if (conn && conn->data && conn->data->engine) {
  255. #ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
  256. UI_METHOD *ui_method = UI_OpenSSL();
  257. #endif
  258. if (!key_file || !key_file[0]) {
  259. failf(data, "no key set to load from crypto engine\n");
  260. return 0;
  261. }
  262. priv_key = ENGINE_load_private_key(conn->data->engine,key_file,
  263. #ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
  264. ui_method,
  265. #endif
  266. data->set.key_passwd);
  267. if (!priv_key) {
  268. failf(data, "failed to load private key from crypto engine\n");
  269. return 0;
  270. }
  271. if (SSL_CTX_use_PrivateKey(conn->ssl.ctx, priv_key) != 1) {
  272. failf(data, "unable to set private key\n");
  273. EVP_PKEY_free(priv_key);
  274. return 0;
  275. }
  276. EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
  277. }
  278. else {
  279. failf(data, "crypto engine not set, can't load private key\n");
  280. return 0;
  281. }
  282. }
  283. #else
  284. failf(data, "file type ENG for private key not supported\n");
  285. return 0;
  286. #endif
  287. break;
  288. default:
  289. failf(data, "not supported file type for private key\n");
  290. return 0;
  291. }
  292. ssl=SSL_new(conn->ssl.ctx);
  293. x509=SSL_get_certificate(ssl);
  294. /* This version was provided by Evan Jordan and is supposed to not
  295. leak memory as the previous version: */
  296. if (x509 != NULL) {
  297. EVP_PKEY *pktmp = X509_get_pubkey(x509);
  298. EVP_PKEY_copy_parameters(pktmp,SSL_get_privatekey(ssl));
  299. EVP_PKEY_free(pktmp);
  300. }
  301. SSL_free(ssl);
  302. /* If we are using DSA, we can copy the parameters from
  303. * the private key */
  304. /* Now we know that a key and cert have been set against
  305. * the SSL context */
  306. if (!SSL_CTX_check_private_key(conn->ssl.ctx)) {
  307. failf(data, "Private key does not match the certificate public key");
  308. return(0);
  309. }
  310. #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
  311. /* erase it now */
  312. memset(global_passwd, 0, sizeof(global_passwd));
  313. #endif
  314. }
  315. return(1);
  316. }
  317. static
  318. int cert_verify_callback(int ok, X509_STORE_CTX *ctx)
  319. {
  320. X509 *err_cert;
  321. char buf[256];
  322. err_cert=X509_STORE_CTX_get_current_cert(ctx);
  323. X509_NAME_oneline(X509_get_subject_name(err_cert),buf,256);
  324. return ok;
  325. }
  326. #endif
  327. #ifdef USE_SSLEAY
  328. /* "global" init done? */
  329. static int init_ssl=0;
  330. /* we have the "SSL is seeded" boolean global for the application to
  331. prevent multiple time-consuming seedings in vain */
  332. static bool ssl_seeded = FALSE;
  333. #endif
  334. /* Global init */
  335. void Curl_SSL_init(void)
  336. {
  337. #ifdef USE_SSLEAY
  338. /* make sure this is only done once */
  339. if(0 != init_ssl)
  340. return;
  341. init_ssl++; /* never again */
  342. #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
  343. ENGINE_load_builtin_engines();
  344. #endif
  345. /* Lets get nice error messages */
  346. SSL_load_error_strings();
  347. /* Setup all the global SSL stuff */
  348. SSLeay_add_ssl_algorithms();
  349. #else
  350. /* SSL disabled, do nothing */
  351. #endif
  352. }
  353. /* Global cleanup */
  354. void Curl_SSL_cleanup(void)
  355. {
  356. #ifdef USE_SSLEAY
  357. if(init_ssl) {
  358. /* only cleanup if we did a previous init */
  359. /* Free the SSL error strings */
  360. ERR_free_strings();
  361. /* EVP_cleanup() removes all ciphers and digests from the
  362. table. */
  363. EVP_cleanup();
  364. #ifdef HAVE_ENGINE_cleanup
  365. ENGINE_cleanup();
  366. #endif
  367. init_ssl=0; /* not inited any more */
  368. }
  369. #else
  370. /* SSL disabled, do nothing */
  371. #endif
  372. }
  373. #ifdef USE_SSLEAY
  374. /*
  375. * This function is called when an SSL connection is closed.
  376. */
  377. void Curl_SSL_Close(struct connectdata *conn)
  378. {
  379. if (conn->ssl.use) {
  380. /*
  381. ERR_remove_state() frees the error queue associated with
  382. thread pid. If pid == 0, the current thread will have its
  383. error queue removed.
  384. Since error queue data structures are allocated
  385. automatically for new threads, they must be freed when
  386. threads are terminated in oder to avoid memory leaks.
  387. */
  388. ERR_remove_state(0);
  389. if(conn->ssl.handle) {
  390. (void)SSL_shutdown(conn->ssl.handle);
  391. SSL_set_connect_state(conn->ssl.handle);
  392. SSL_free (conn->ssl.handle);
  393. conn->ssl.handle = NULL;
  394. }
  395. if(conn->ssl.ctx) {
  396. SSL_CTX_free (conn->ssl.ctx);
  397. conn->ssl.ctx = NULL;
  398. }
  399. conn->ssl.use = FALSE; /* get back to ordinary socket usage */
  400. }
  401. }
  402. /*
  403. * This sets up a session cache to the specified size.
  404. */
  405. CURLcode Curl_SSL_InitSessions(struct SessionHandle *data, long amount)
  406. {
  407. struct curl_ssl_session *session;
  408. if(data->state.session)
  409. /* this is just a precaution to prevent multiple inits */
  410. return CURLE_OK;
  411. session = (struct curl_ssl_session *)
  412. malloc(amount * sizeof(struct curl_ssl_session));
  413. if(!session)
  414. return CURLE_OUT_OF_MEMORY;
  415. /* "blank out" the newly allocated memory */
  416. memset(session, 0, amount * sizeof(struct curl_ssl_session));
  417. /* store the info in the SSL section */
  418. data->set.ssl.numsessions = amount;
  419. data->state.session = session;
  420. data->state.sessionage = 1; /* this is brand new */
  421. return CURLE_OK;
  422. }
  423. /*
  424. * Check if there's a session ID for the given connection in the cache,
  425. * and if there's one suitable, it is returned.
  426. */
  427. static int Get_SSL_Session(struct connectdata *conn,
  428. SSL_SESSION **ssl_sessionid)
  429. {
  430. struct curl_ssl_session *check;
  431. struct SessionHandle *data = conn->data;
  432. long i;
  433. for(i=0; i< data->set.ssl.numsessions; i++) {
  434. check = &data->state.session[i];
  435. if(!check->sessionid)
  436. /* not session ID means blank entry */
  437. continue;
  438. if(strequal(conn->name, check->name) &&
  439. (conn->remote_port == check->remote_port) ) {
  440. /* yes, we have a session ID! */
  441. data->state.sessionage++; /* increase general age */
  442. check->age = data->state.sessionage; /* set this as used in this age */
  443. *ssl_sessionid = check->sessionid;
  444. return FALSE;
  445. }
  446. }
  447. *ssl_sessionid = (SSL_SESSION *)NULL;
  448. return TRUE;
  449. }
  450. /*
  451. * Kill a single session ID entry in the cache.
  452. */
  453. static int Kill_Single_Session(struct curl_ssl_session *session)
  454. {
  455. if(session->sessionid) {
  456. /* defensive check */
  457. /* free the ID */
  458. SSL_SESSION_free(session->sessionid);
  459. session->sessionid=NULL;
  460. session->age = 0; /* fresh */
  461. free(session->name);
  462. session->name = NULL; /* no name */
  463. return 0; /* ok */
  464. }
  465. else
  466. return 1;
  467. }
  468. /*
  469. * This function is called when the 'data' struct is going away. Close
  470. * down everything and free all resources!
  471. */
  472. int Curl_SSL_Close_All(struct SessionHandle *data)
  473. {
  474. int i;
  475. if(data->state.session) {
  476. for(i=0; i< data->set.ssl.numsessions; i++)
  477. /* the single-killer function handles empty table slots */
  478. Kill_Single_Session(&data->state.session[i]);
  479. /* free the cache data */
  480. free(data->state.session);
  481. }
  482. #ifdef HAVE_OPENSSL_ENGINE_H
  483. if (data->engine)
  484. {
  485. ENGINE_free(data->engine);
  486. data->engine = NULL;
  487. }
  488. #endif
  489. return 0;
  490. }
  491. /*
  492. * Extract the session id and store it in the session cache.
  493. */
  494. static int Store_SSL_Session(struct connectdata *conn)
  495. {
  496. SSL_SESSION *ssl_sessionid;
  497. int i;
  498. struct SessionHandle *data=conn->data; /* the mother of all structs */
  499. struct curl_ssl_session *store = &data->state.session[0];
  500. int oldest_age=data->state.session[0].age; /* zero if unused */
  501. /* ask OpenSSL, say please */
  502. #ifdef HAVE_SSL_GET1_SESSION
  503. ssl_sessionid = SSL_get1_session(conn->ssl.handle);
  504. /* SSL_get1_session() will increment the reference
  505. count and the session will stay in memory until explicitly freed with
  506. SSL_SESSION_free(3), regardless of its state.
  507. This function was introduced in openssl 0.9.5a. */
  508. #else
  509. ssl_sessionid = SSL_get_session(conn->ssl.handle);
  510. /* if SSL_get1_session() is unavailable, use SSL_get_session().
  511. This is an inferior option because the session can be flushed
  512. at any time by openssl. It is included only so curl compiles
  513. under versions of openssl < 0.9.5a.
  514. WARNING: How curl behaves if it's session is flushed is
  515. untested.
  516. */
  517. #endif
  518. /* Now we should add the session ID and the host name to the cache, (remove
  519. the oldest if necessary) */
  520. /* find an empty slot for us, or find the oldest */
  521. for(i=1; (i<data->set.ssl.numsessions) &&
  522. data->state.session[i].sessionid; i++) {
  523. if(data->state.session[i].age < oldest_age) {
  524. oldest_age = data->state.session[i].age;
  525. store = &data->state.session[i];
  526. }
  527. }
  528. if(i == data->set.ssl.numsessions)
  529. /* cache is full, we must "kill" the oldest entry! */
  530. Kill_Single_Session(store);
  531. else
  532. store = &data->state.session[i]; /* use this slot */
  533. /* now init the session struct wisely */
  534. store->sessionid = ssl_sessionid;
  535. store->age = data->state.sessionage; /* set current age */
  536. store->name = strdup(conn->name); /* clone host name */
  537. store->remote_port = conn->remote_port; /* port number */
  538. return 0;
  539. }
  540. static int Curl_ASN1_UTCTIME_output(struct connectdata *conn,
  541. const char *prefix,
  542. ASN1_UTCTIME *tm)
  543. {
  544. char *asn1_string;
  545. int gmt=FALSE;
  546. int i;
  547. int year=0,month=0,day=0,hour=0,minute=0,second=0;
  548. struct SessionHandle *data = conn->data;
  549. if(!data->set.verbose)
  550. return 0;
  551. i=tm->length;
  552. asn1_string=(char *)tm->data;
  553. if (i < 10)
  554. return 1;
  555. if (asn1_string[i-1] == 'Z')
  556. gmt=TRUE;
  557. for (i=0; i<10; i++)
  558. if ((asn1_string[i] > '9') || (asn1_string[i] < '0'))
  559. return 2;
  560. year= (asn1_string[0]-'0')*10+(asn1_string[1]-'0');
  561. if (year < 50)
  562. year+=100;
  563. month= (asn1_string[2]-'0')*10+(asn1_string[3]-'0');
  564. if ((month > 12) || (month < 1))
  565. return 3;
  566. day= (asn1_string[4]-'0')*10+(asn1_string[5]-'0');
  567. hour= (asn1_string[6]-'0')*10+(asn1_string[7]-'0');
  568. minute= (asn1_string[8]-'0')*10+(asn1_string[9]-'0');
  569. if ( (asn1_string[10] >= '0') && (asn1_string[10] <= '9') &&
  570. (asn1_string[11] >= '0') && (asn1_string[11] <= '9'))
  571. second= (asn1_string[10]-'0')*10+(asn1_string[11]-'0');
  572. infof(data,
  573. "%s%04d-%02d-%02d %02d:%02d:%02d %s\n",
  574. prefix, year+1900, month, day, hour, minute, second, (gmt?"GMT":""));
  575. return 0;
  576. }
  577. #endif
  578. /* ====================================================== */
  579. #ifdef USE_SSLEAY
  580. static int
  581. cert_hostcheck(const char *certname, const char *hostname)
  582. {
  583. char *tmp;
  584. const char *certdomain;
  585. if(!certname ||
  586. strlen(certname)<3 ||
  587. !hostname ||
  588. !strlen(hostname)) /* sanity check */
  589. return 0;
  590. if(strequal(certname, hostname)) /* trivial case */
  591. return 1;
  592. certdomain = certname + 1;
  593. if((certname[0] != '*') || (certdomain[0] != '.'))
  594. return 0; /* not a wildcard certificate, check failed */
  595. if(!strchr(certdomain+1, '.'))
  596. return 0; /* the certificate must have at least another dot in its name */
  597. /* find 'certdomain' within 'hostname' */
  598. tmp = strstr(hostname, certdomain);
  599. if(tmp) {
  600. /* ok the certname's domain matches the hostname, let's check that it's a
  601. tail-match */
  602. if(strequal(tmp, certdomain))
  603. /* looks like a match. Just check we havent swallowed a '.' */
  604. return tmp == strchr(hostname, '.');
  605. else
  606. return 0;
  607. }
  608. return 0;
  609. }
  610. #endif
  611. /* ====================================================== */
  612. CURLcode
  613. Curl_SSLConnect(struct connectdata *conn)
  614. {
  615. CURLcode retcode = CURLE_OK;
  616. #ifdef USE_SSLEAY
  617. struct SessionHandle *data = conn->data;
  618. int err;
  619. char * str;
  620. SSL_METHOD *req_method;
  621. SSL_SESSION *ssl_sessionid=NULL;
  622. ASN1_TIME *certdate;
  623. /* mark this is being ssl enabled from here on out. */
  624. conn->ssl.use = TRUE;
  625. if(!ssl_seeded || data->set.ssl.random_file || data->set.ssl.egdsocket) {
  626. /* Make funny stuff to get random input */
  627. random_the_seed(data);
  628. ssl_seeded = TRUE;
  629. }
  630. /* check to see if we've been told to use an explicit SSL/TLS version */
  631. switch(data->set.ssl.version) {
  632. default:
  633. case CURL_SSLVERSION_DEFAULT:
  634. /* we try to figure out version */
  635. req_method = SSLv23_client_method();
  636. break;
  637. case CURL_SSLVERSION_TLSv1:
  638. req_method = TLSv1_client_method();
  639. break;
  640. case CURL_SSLVERSION_SSLv2:
  641. req_method = SSLv2_client_method();
  642. break;
  643. case CURL_SSLVERSION_SSLv3:
  644. req_method = SSLv3_client_method();
  645. break;
  646. }
  647. conn->ssl.ctx = SSL_CTX_new(req_method);
  648. if(!conn->ssl.ctx) {
  649. failf(data, "SSL: couldn't create a context!");
  650. return CURLE_OUT_OF_MEMORY;
  651. }
  652. if(data->set.cert) {
  653. if (!cert_stuff(conn,
  654. data->set.cert,
  655. data->set.cert_type,
  656. data->set.key,
  657. data->set.key_type)) {
  658. /* failf() is already done in cert_stuff() */
  659. return CURLE_SSL_CERTPROBLEM;
  660. }
  661. }
  662. if(data->set.ssl.cipher_list) {
  663. if (!SSL_CTX_set_cipher_list(conn->ssl.ctx,
  664. data->set.ssl.cipher_list)) {
  665. failf(data, "failed setting cipher list");
  666. return CURLE_SSL_CIPHER;
  667. }
  668. }
  669. if(data->set.ssl.verifypeer){
  670. SSL_CTX_set_verify(conn->ssl.ctx,
  671. SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT|
  672. SSL_VERIFY_CLIENT_ONCE,
  673. cert_verify_callback);
  674. if ((data->set.ssl.CAfile || data->set.ssl.CApath) &&
  675. !SSL_CTX_load_verify_locations(conn->ssl.ctx,
  676. data->set.ssl.CAfile,
  677. data->set.ssl.CApath)) {
  678. failf(data,"error setting cerficate verify locations");
  679. return CURLE_SSL_CACERT;
  680. }
  681. }
  682. else
  683. SSL_CTX_set_verify(conn->ssl.ctx, SSL_VERIFY_NONE, cert_verify_callback);
  684. /* Lets make an SSL structure */
  685. conn->ssl.handle = SSL_new (conn->ssl.ctx);
  686. SSL_set_connect_state (conn->ssl.handle);
  687. conn->ssl.server_cert = 0x0;
  688. if(!conn->bits.reuse) {
  689. /* We're not re-using a connection, check if there's a cached ID we
  690. can/should use here! */
  691. if(!Get_SSL_Session(conn, &ssl_sessionid)) {
  692. /* we got a session id, use it! */
  693. SSL_set_session(conn->ssl.handle, ssl_sessionid);
  694. /* Informational message */
  695. infof (data, "SSL re-using session ID\n");
  696. }
  697. }
  698. /* pass the raw socket into the SSL layers */
  699. SSL_set_fd(conn->ssl.handle, conn->firstsocket);
  700. do {
  701. int what;
  702. fd_set writefd;
  703. fd_set readfd;
  704. struct timeval interval;
  705. long timeout_ms;
  706. err = SSL_connect(conn->ssl.handle);
  707. what = SSL_get_error(conn->ssl.handle, err);
  708. FD_ZERO(&writefd);
  709. FD_ZERO(&readfd);
  710. if(SSL_ERROR_WANT_READ == what)
  711. FD_SET(conn->firstsocket, &readfd);
  712. else if(SSL_ERROR_WANT_WRITE == what)
  713. FD_SET(conn->firstsocket, &writefd);
  714. else
  715. break; /* untreated error */
  716. /* Find out if any timeout is set. If not, use 300 seconds.
  717. Otherwise, figure out the most strict timeout of the two possible one
  718. and then how much time that has elapsed to know how much time we
  719. allow for the connect call */
  720. if(data->set.timeout || data->set.connecttimeout) {
  721. double has_passed;
  722. /* Evaluate in milliseconds how much time that has passed */
  723. has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.start);
  724. #ifndef min
  725. #define min(a, b) ((a) < (b) ? (a) : (b))
  726. #endif
  727. /* get the most strict timeout of the ones converted to milliseconds */
  728. if(data->set.timeout &&
  729. (data->set.timeout>data->set.connecttimeout))
  730. timeout_ms = data->set.timeout*1000;
  731. else
  732. timeout_ms = data->set.connecttimeout*1000;
  733. /* subtract the passed time */
  734. timeout_ms -= (long)has_passed;
  735. if(timeout_ms < 0) {
  736. /* a precaution, no need to continue if time already is up */
  737. failf(data, "SSL connection timeout");
  738. return CURLE_OPERATION_TIMEOUTED;
  739. }
  740. }
  741. else
  742. /* no particular time-out has been set */
  743. timeout_ms=300000; /* milliseconds, default to five minutes */
  744. interval.tv_sec = timeout_ms/1000;
  745. timeout_ms -= interval.tv_sec*1000;
  746. interval.tv_usec = timeout_ms*1000;
  747. what = select(conn->firstsocket+1, &readfd, &writefd, NULL, &interval);
  748. if(what > 0)
  749. /* reabable or writable, go loop yourself */
  750. continue;
  751. else if(0 == what) {
  752. /* timeout */
  753. failf(data, "SSL connection timeout");
  754. return CURLE_OPERATION_TIMEOUTED;
  755. }
  756. else
  757. break; /* get out of loop */
  758. } while(1);
  759. /* 1 is fine
  760. 0 is "not successful but was shut down controlled"
  761. <0 is "handshake was not successful, because a fatal error occurred" */
  762. if (err <= 0) {
  763. err = ERR_get_error();
  764. failf(data, "SSL: %s", ERR_error_string(err, NULL));
  765. return CURLE_SSL_CONNECT_ERROR;
  766. }
  767. /* Informational message */
  768. infof (data, "SSL connection using %s\n",
  769. SSL_get_cipher(conn->ssl.handle));
  770. if(!ssl_sessionid) {
  771. /* Since this is not a cached session ID, then we want to stach this one
  772. in the cache! */
  773. Store_SSL_Session(conn);
  774. }
  775. /* Get server's certificate (note: beware of dynamic allocation) - opt */
  776. /* major serious hack alert -- we should check certificates
  777. * to authenticate the server; otherwise we risk man-in-the-middle
  778. * attack
  779. */
  780. conn->ssl.server_cert = SSL_get_peer_certificate (conn->ssl.handle);
  781. if(!conn->ssl.server_cert) {
  782. failf(data, "SSL: couldn't get peer certificate!");
  783. return CURLE_SSL_PEER_CERTIFICATE;
  784. }
  785. infof (data, "Server certificate:\n");
  786. str = X509_NAME_oneline (X509_get_subject_name (conn->ssl.server_cert),
  787. NULL, 0);
  788. if(!str) {
  789. failf(data, "SSL: couldn't get X509-subject!");
  790. X509_free(conn->ssl.server_cert);
  791. return CURLE_SSL_CONNECT_ERROR;
  792. }
  793. infof(data, "\t subject: %s\n", str);
  794. CRYPTO_free(str);
  795. certdate = X509_get_notBefore(conn->ssl.server_cert);
  796. Curl_ASN1_UTCTIME_output(conn, "\t start date: ", certdate);
  797. certdate = X509_get_notAfter(conn->ssl.server_cert);
  798. Curl_ASN1_UTCTIME_output(conn, "\t expire date: ", certdate);
  799. if (data->set.ssl.verifyhost) {
  800. char peer_CN[257];
  801. if (X509_NAME_get_text_by_NID(X509_get_subject_name(conn->ssl.server_cert),
  802. NID_commonName,
  803. peer_CN,
  804. sizeof(peer_CN)) < 0) {
  805. failf(data, "SSL: unable to obtain common name from peer certificate");
  806. X509_free(conn->ssl.server_cert);
  807. return CURLE_SSL_PEER_CERTIFICATE;
  808. }
  809. if (!cert_hostcheck(peer_CN, conn->hostname)) {
  810. if (data->set.ssl.verifyhost > 1) {
  811. failf(data, "SSL: certificate subject name '%s' does not match "
  812. "target host name '%s'",
  813. peer_CN, conn->hostname);
  814. X509_free(conn->ssl.server_cert);
  815. return CURLE_SSL_PEER_CERTIFICATE;
  816. }
  817. else
  818. infof(data,
  819. "\t common name: %s (does not match '%s')\n",
  820. peer_CN, conn->hostname);
  821. }
  822. else
  823. infof(data, "\t common name: %s (matched)\n", peer_CN);
  824. }
  825. str = X509_NAME_oneline (X509_get_issuer_name (conn->ssl.server_cert),
  826. NULL, 0);
  827. if(!str) {
  828. failf(data, "SSL: couldn't get X509-issuer name!");
  829. X509_free(conn->ssl.server_cert);
  830. return CURLE_SSL_CONNECT_ERROR;
  831. }
  832. infof(data, "\t issuer: %s\n", str);
  833. CRYPTO_free(str);
  834. /* We could do all sorts of certificate verification stuff here before
  835. deallocating the certificate. */
  836. if(data->set.ssl.verifypeer) {
  837. data->set.ssl.certverifyresult=SSL_get_verify_result(conn->ssl.handle);
  838. if (data->set.ssl.certverifyresult != X509_V_OK) {
  839. failf(data, "SSL certificate verify result: %d",
  840. data->set.ssl.certverifyresult);
  841. retcode = CURLE_SSL_PEER_CERTIFICATE;
  842. }
  843. }
  844. else
  845. data->set.ssl.certverifyresult=0;
  846. X509_free(conn->ssl.server_cert);
  847. #else /* USE_SSLEAY */
  848. /* this is for "-ansi -Wall -pedantic" to stop complaining! (rabe) */
  849. (void) conn;
  850. #endif
  851. return retcode;
  852. }
  853. /*
  854. * local variables:
  855. * eval: (load-file "../curl-mode.el")
  856. * end:
  857. * vim600: fdm=marker
  858. * vim: et sw=2 ts=2 sts=2 tw=78
  859. */