ssluse.c 80 KB

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