ssluse.c 57 KB

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