openssl.c 88 KB

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