ssluse.c 73 KB

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