openssl.c 94 KB

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