openssl.c 88 KB

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