ssluse.c 62 KB

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