2
0

ssluse.c 77 KB

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