ssluse.c 73 KB

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