ssluse.c 79 KB

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