openssl.c 138 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2021, 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 https://curl.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. #include "curl_setup.h"
  27. #ifdef USE_OPENSSL
  28. #include <limits.h>
  29. /* Wincrypt must be included before anything that could include OpenSSL. */
  30. #if defined(USE_WIN32_CRYPTO)
  31. #include <wincrypt.h>
  32. /* Undefine wincrypt conflicting symbols for BoringSSL. */
  33. #undef X509_NAME
  34. #undef X509_EXTENSIONS
  35. #undef PKCS7_ISSUER_AND_SERIAL
  36. #undef PKCS7_SIGNER_INFO
  37. #undef OCSP_REQUEST
  38. #undef OCSP_RESPONSE
  39. #endif
  40. #include "urldata.h"
  41. #include "sendf.h"
  42. #include "formdata.h" /* for the boundary function */
  43. #include "url.h" /* for the ssl config check function */
  44. #include "inet_pton.h"
  45. #include "openssl.h"
  46. #include "connect.h"
  47. #include "slist.h"
  48. #include "select.h"
  49. #include "vtls.h"
  50. #include "keylog.h"
  51. #include "strcase.h"
  52. #include "hostcheck.h"
  53. #include "multiif.h"
  54. #include "strerror.h"
  55. #include "curl_printf.h"
  56. #include <openssl/ssl.h>
  57. #include <openssl/rand.h>
  58. #include <openssl/x509v3.h>
  59. #ifndef OPENSSL_NO_DSA
  60. #include <openssl/dsa.h>
  61. #endif
  62. #include <openssl/dh.h>
  63. #include <openssl/err.h>
  64. #include <openssl/md5.h>
  65. #include <openssl/conf.h>
  66. #include <openssl/bn.h>
  67. #include <openssl/rsa.h>
  68. #include <openssl/bio.h>
  69. #include <openssl/buffer.h>
  70. #include <openssl/pkcs12.h>
  71. #ifdef USE_AMISSL
  72. #include "amigaos.h"
  73. #endif
  74. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_OCSP)
  75. #include <openssl/ocsp.h>
  76. #endif
  77. #if (OPENSSL_VERSION_NUMBER >= 0x0090700fL) && /* 0.9.7 or later */ \
  78. !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_UI_CONSOLE)
  79. #define USE_OPENSSL_ENGINE
  80. #include <openssl/engine.h>
  81. #endif
  82. #include "warnless.h"
  83. #include "non-ascii.h" /* for Curl_convert_from_utf8 prototype */
  84. /* The last #include files should be: */
  85. #include "curl_memory.h"
  86. #include "memdebug.h"
  87. /* Uncomment the ALLOW_RENEG line to a real #define if you want to allow TLS
  88. renegotiations when built with BoringSSL. Renegotiating is non-compliant
  89. with HTTP/2 and "an extremely dangerous protocol feature". Beware.
  90. #define ALLOW_RENEG 1
  91. */
  92. #ifndef OPENSSL_VERSION_NUMBER
  93. #error "OPENSSL_VERSION_NUMBER not defined"
  94. #endif
  95. #ifdef USE_OPENSSL_ENGINE
  96. #include <openssl/ui.h>
  97. #endif
  98. #if OPENSSL_VERSION_NUMBER >= 0x00909000L
  99. #define SSL_METHOD_QUAL const
  100. #else
  101. #define SSL_METHOD_QUAL
  102. #endif
  103. #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
  104. #define HAVE_ERR_REMOVE_THREAD_STATE 1
  105. #endif
  106. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \
  107. !(defined(LIBRESSL_VERSION_NUMBER) && \
  108. LIBRESSL_VERSION_NUMBER < 0x20700000L)
  109. #define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
  110. #define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */
  111. #define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */
  112. #define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */
  113. #define CONST_EXTS const
  114. #define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1
  115. /* funny typecast define due to difference in API */
  116. #ifdef LIBRESSL_VERSION_NUMBER
  117. #define ARG2_X509_signature_print (X509_ALGOR *)
  118. #else
  119. #define ARG2_X509_signature_print
  120. #endif
  121. #else
  122. /* For OpenSSL before 1.1.0 */
  123. #define ASN1_STRING_get0_data(x) ASN1_STRING_data(x)
  124. #define X509_get0_notBefore(x) X509_get_notBefore(x)
  125. #define X509_get0_notAfter(x) X509_get_notAfter(x)
  126. #define CONST_EXTS /* nope */
  127. #ifndef LIBRESSL_VERSION_NUMBER
  128. #define OpenSSL_version_num() SSLeay()
  129. #endif
  130. #endif
  131. #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* 1.0.2 or later */ \
  132. !(defined(LIBRESSL_VERSION_NUMBER) && \
  133. LIBRESSL_VERSION_NUMBER < 0x20700000L)
  134. #define HAVE_X509_GET0_SIGNATURE 1
  135. #endif
  136. #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) /* 1.0.2 or later */
  137. #define HAVE_SSL_GET_SHUTDOWN 1
  138. #endif
  139. #if OPENSSL_VERSION_NUMBER >= 0x10002003L && \
  140. OPENSSL_VERSION_NUMBER <= 0x10002FFFL && \
  141. !defined(OPENSSL_NO_COMP)
  142. #define HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1
  143. #endif
  144. #if (OPENSSL_VERSION_NUMBER < 0x0090808fL)
  145. /* not present in older OpenSSL */
  146. #define OPENSSL_load_builtin_modules(x)
  147. #endif
  148. /*
  149. * Whether SSL_CTX_set_keylog_callback is available.
  150. * OpenSSL: supported since 1.1.1 https://github.com/openssl/openssl/pull/2287
  151. * BoringSSL: supported since d28f59c27bac (committed 2015-11-19)
  152. * LibreSSL: unsupported in at least 2.7.2 (explicitly check for it since it
  153. * lies and pretends to be OpenSSL 2.0.0).
  154. */
  155. #if (OPENSSL_VERSION_NUMBER >= 0x10101000L && \
  156. !defined(LIBRESSL_VERSION_NUMBER)) || \
  157. defined(OPENSSL_IS_BORINGSSL)
  158. #define HAVE_KEYLOG_CALLBACK
  159. #endif
  160. /* Whether SSL_CTX_set_ciphersuites is available.
  161. * OpenSSL: supported since 1.1.1 (commit a53b5be6a05)
  162. * BoringSSL: no
  163. * LibreSSL: no
  164. */
  165. #if ((OPENSSL_VERSION_NUMBER >= 0x10101000L) && \
  166. !defined(LIBRESSL_VERSION_NUMBER) && \
  167. !defined(OPENSSL_IS_BORINGSSL))
  168. #define HAVE_SSL_CTX_SET_CIPHERSUITES
  169. #define HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH
  170. /* SET_EC_CURVES available under the same preconditions: see
  171. * https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set1_groups.html
  172. */
  173. #define HAVE_SSL_CTX_SET_EC_CURVES
  174. #endif
  175. #if defined(LIBRESSL_VERSION_NUMBER)
  176. #define OSSL_PACKAGE "LibreSSL"
  177. #elif defined(OPENSSL_IS_BORINGSSL)
  178. #define OSSL_PACKAGE "BoringSSL"
  179. #else
  180. #define OSSL_PACKAGE "OpenSSL"
  181. #endif
  182. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  183. /* up2date versions of OpenSSL maintain the default reasonably secure without
  184. * breaking compatibility, so it is better not to override the default by curl
  185. */
  186. #define DEFAULT_CIPHER_SELECTION NULL
  187. #else
  188. /* ... but it is not the case with old versions of OpenSSL */
  189. #define DEFAULT_CIPHER_SELECTION \
  190. "ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH"
  191. #endif
  192. #ifdef HAVE_OPENSSL_SRP
  193. /* the function exists */
  194. #ifdef USE_TLS_SRP
  195. /* the functionality is not disabled */
  196. #define USE_OPENSSL_SRP
  197. #endif
  198. #endif
  199. struct ssl_backend_data {
  200. struct Curl_easy *logger; /* transfer handle to pass trace logs to, only
  201. using sockindex 0 */
  202. /* these ones requires specific SSL-types */
  203. SSL_CTX* ctx;
  204. SSL* handle;
  205. X509* server_cert;
  206. #ifndef HAVE_KEYLOG_CALLBACK
  207. /* Set to true once a valid keylog entry has been created to avoid dupes. */
  208. bool keylog_done;
  209. #endif
  210. };
  211. static void ossl_associate_connection(struct Curl_easy *data,
  212. struct connectdata *conn,
  213. int sockindex);
  214. /*
  215. * Number of bytes to read from the random number seed file. This must be
  216. * a finite value (because some entropy "files" like /dev/urandom have
  217. * an infinite length), but must be large enough to provide enough
  218. * entropy to properly seed OpenSSL's PRNG.
  219. */
  220. #define RAND_LOAD_LENGTH 1024
  221. #ifdef HAVE_KEYLOG_CALLBACK
  222. static void ossl_keylog_callback(const SSL *ssl, const char *line)
  223. {
  224. (void)ssl;
  225. Curl_tls_keylog_write_line(line);
  226. }
  227. #else
  228. /*
  229. * ossl_log_tls12_secret is called by libcurl to make the CLIENT_RANDOMs if the
  230. * OpenSSL being used doesn't have native support for doing that.
  231. */
  232. static void
  233. ossl_log_tls12_secret(const SSL *ssl, bool *keylog_done)
  234. {
  235. const SSL_SESSION *session = SSL_get_session(ssl);
  236. unsigned char client_random[SSL3_RANDOM_SIZE];
  237. unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
  238. int master_key_length = 0;
  239. if(!session || *keylog_done)
  240. return;
  241. #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
  242. !(defined(LIBRESSL_VERSION_NUMBER) && \
  243. LIBRESSL_VERSION_NUMBER < 0x20700000L)
  244. /* ssl->s3 is not checked in openssl 1.1.0-pre6, but let's assume that
  245. * we have a valid SSL context if we have a non-NULL session. */
  246. SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE);
  247. master_key_length = (int)
  248. SSL_SESSION_get_master_key(session, master_key, SSL_MAX_MASTER_KEY_LENGTH);
  249. #else
  250. if(ssl->s3 && session->master_key_length > 0) {
  251. master_key_length = session->master_key_length;
  252. memcpy(master_key, session->master_key, session->master_key_length);
  253. memcpy(client_random, ssl->s3->client_random, SSL3_RANDOM_SIZE);
  254. }
  255. #endif
  256. /* The handshake has not progressed sufficiently yet, or this is a TLS 1.3
  257. * session (when curl was built with older OpenSSL headers and running with
  258. * newer OpenSSL runtime libraries). */
  259. if(master_key_length <= 0)
  260. return;
  261. *keylog_done = true;
  262. Curl_tls_keylog_write("CLIENT_RANDOM", client_random,
  263. master_key, master_key_length);
  264. }
  265. #endif /* !HAVE_KEYLOG_CALLBACK */
  266. static const char *SSL_ERROR_to_str(int err)
  267. {
  268. switch(err) {
  269. case SSL_ERROR_NONE:
  270. return "SSL_ERROR_NONE";
  271. case SSL_ERROR_SSL:
  272. return "SSL_ERROR_SSL";
  273. case SSL_ERROR_WANT_READ:
  274. return "SSL_ERROR_WANT_READ";
  275. case SSL_ERROR_WANT_WRITE:
  276. return "SSL_ERROR_WANT_WRITE";
  277. case SSL_ERROR_WANT_X509_LOOKUP:
  278. return "SSL_ERROR_WANT_X509_LOOKUP";
  279. case SSL_ERROR_SYSCALL:
  280. return "SSL_ERROR_SYSCALL";
  281. case SSL_ERROR_ZERO_RETURN:
  282. return "SSL_ERROR_ZERO_RETURN";
  283. case SSL_ERROR_WANT_CONNECT:
  284. return "SSL_ERROR_WANT_CONNECT";
  285. case SSL_ERROR_WANT_ACCEPT:
  286. return "SSL_ERROR_WANT_ACCEPT";
  287. #if defined(SSL_ERROR_WANT_ASYNC)
  288. case SSL_ERROR_WANT_ASYNC:
  289. return "SSL_ERROR_WANT_ASYNC";
  290. #endif
  291. #if defined(SSL_ERROR_WANT_ASYNC_JOB)
  292. case SSL_ERROR_WANT_ASYNC_JOB:
  293. return "SSL_ERROR_WANT_ASYNC_JOB";
  294. #endif
  295. #if defined(SSL_ERROR_WANT_EARLY)
  296. case SSL_ERROR_WANT_EARLY:
  297. return "SSL_ERROR_WANT_EARLY";
  298. #endif
  299. default:
  300. return "SSL_ERROR unknown";
  301. }
  302. }
  303. /* Return error string for last OpenSSL error
  304. */
  305. static char *ossl_strerror(unsigned long error, char *buf, size_t size)
  306. {
  307. if(size)
  308. *buf = '\0';
  309. #ifdef OPENSSL_IS_BORINGSSL
  310. ERR_error_string_n((uint32_t)error, buf, size);
  311. #else
  312. ERR_error_string_n(error, buf, size);
  313. #endif
  314. if(size > 1 && !*buf) {
  315. strncpy(buf, (error ? "Unknown error" : "No error"), size);
  316. buf[size - 1] = '\0';
  317. }
  318. return buf;
  319. }
  320. /* Return an extra data index for the transfer data.
  321. * This index can be used with SSL_get_ex_data() and SSL_set_ex_data().
  322. */
  323. static int ossl_get_ssl_data_index(void)
  324. {
  325. static int ssl_ex_data_data_index = -1;
  326. if(ssl_ex_data_data_index < 0) {
  327. ssl_ex_data_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  328. }
  329. return ssl_ex_data_data_index;
  330. }
  331. /* Return an extra data index for the connection data.
  332. * This index can be used with SSL_get_ex_data() and SSL_set_ex_data().
  333. */
  334. static int ossl_get_ssl_conn_index(void)
  335. {
  336. static int ssl_ex_data_conn_index = -1;
  337. if(ssl_ex_data_conn_index < 0) {
  338. ssl_ex_data_conn_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  339. }
  340. return ssl_ex_data_conn_index;
  341. }
  342. /* Return an extra data index for the sockindex.
  343. * This index can be used with SSL_get_ex_data() and SSL_set_ex_data().
  344. */
  345. static int ossl_get_ssl_sockindex_index(void)
  346. {
  347. static int sockindex_index = -1;
  348. if(sockindex_index < 0) {
  349. sockindex_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  350. }
  351. return sockindex_index;
  352. }
  353. /* Return an extra data index for proxy boolean.
  354. * This index can be used with SSL_get_ex_data() and SSL_set_ex_data().
  355. */
  356. static int ossl_get_proxy_index(void)
  357. {
  358. static int proxy_index = -1;
  359. if(proxy_index < 0) {
  360. proxy_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  361. }
  362. return proxy_index;
  363. }
  364. static int passwd_callback(char *buf, int num, int encrypting,
  365. void *global_passwd)
  366. {
  367. DEBUGASSERT(0 == encrypting);
  368. if(!encrypting) {
  369. int klen = curlx_uztosi(strlen((char *)global_passwd));
  370. if(num > klen) {
  371. memcpy(buf, global_passwd, klen + 1);
  372. return klen;
  373. }
  374. }
  375. return 0;
  376. }
  377. /*
  378. * rand_enough() returns TRUE if we have seeded the random engine properly.
  379. */
  380. static bool rand_enough(void)
  381. {
  382. return (0 != RAND_status()) ? TRUE : FALSE;
  383. }
  384. static CURLcode ossl_seed(struct Curl_easy *data)
  385. {
  386. /* we have the "SSL is seeded" boolean static to prevent multiple
  387. time-consuming seedings in vain */
  388. static bool ssl_seeded = FALSE;
  389. char fname[256];
  390. if(ssl_seeded)
  391. return CURLE_OK;
  392. if(rand_enough()) {
  393. /* OpenSSL 1.1.0+ will return here */
  394. ssl_seeded = TRUE;
  395. return CURLE_OK;
  396. }
  397. #ifndef RANDOM_FILE
  398. /* if RANDOM_FILE isn't defined, we only perform this if an option tells
  399. us to! */
  400. if(data->set.str[STRING_SSL_RANDOM_FILE])
  401. #define RANDOM_FILE "" /* doesn't matter won't be used */
  402. #endif
  403. {
  404. /* let the option override the define */
  405. RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
  406. data->set.str[STRING_SSL_RANDOM_FILE]:
  407. RANDOM_FILE),
  408. RAND_LOAD_LENGTH);
  409. if(rand_enough())
  410. return CURLE_OK;
  411. }
  412. #if defined(HAVE_RAND_EGD)
  413. /* only available in OpenSSL 0.9.5 and later */
  414. /* EGD_SOCKET is set at configure time or not at all */
  415. #ifndef EGD_SOCKET
  416. /* If we don't have the define set, we only do this if the egd-option
  417. is set */
  418. if(data->set.str[STRING_SSL_EGDSOCKET])
  419. #define EGD_SOCKET "" /* doesn't matter won't be used */
  420. #endif
  421. {
  422. /* If there's an option and a define, the option overrides the
  423. define */
  424. int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
  425. data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
  426. if(-1 != ret) {
  427. if(rand_enough())
  428. return CURLE_OK;
  429. }
  430. }
  431. #endif
  432. /* fallback to a custom seeding of the PRNG using a hash based on a current
  433. time */
  434. do {
  435. unsigned char randb[64];
  436. size_t len = sizeof(randb);
  437. size_t i, i_max;
  438. for(i = 0, i_max = len / sizeof(struct curltime); i < i_max; ++i) {
  439. struct curltime tv = Curl_now();
  440. Curl_wait_ms(1);
  441. tv.tv_sec *= i + 1;
  442. tv.tv_usec *= (unsigned int)i + 2;
  443. tv.tv_sec ^= ((Curl_now().tv_sec + Curl_now().tv_usec) *
  444. (i + 3)) << 8;
  445. tv.tv_usec ^= (unsigned int) ((Curl_now().tv_sec +
  446. Curl_now().tv_usec) *
  447. (i + 4)) << 16;
  448. memcpy(&randb[i * sizeof(struct curltime)], &tv,
  449. sizeof(struct curltime));
  450. }
  451. RAND_add(randb, (int)len, (double)len/2);
  452. } while(!rand_enough());
  453. /* generates a default path for the random seed file */
  454. fname[0] = 0; /* blank it first */
  455. RAND_file_name(fname, sizeof(fname));
  456. if(fname[0]) {
  457. /* we got a file name to try */
  458. RAND_load_file(fname, RAND_LOAD_LENGTH);
  459. if(rand_enough())
  460. return CURLE_OK;
  461. }
  462. infof(data, "libcurl is now using a weak random seed!\n");
  463. return (rand_enough() ? CURLE_OK :
  464. CURLE_SSL_CONNECT_ERROR /* confusing error code */);
  465. }
  466. #ifndef SSL_FILETYPE_ENGINE
  467. #define SSL_FILETYPE_ENGINE 42
  468. #endif
  469. #ifndef SSL_FILETYPE_PKCS12
  470. #define SSL_FILETYPE_PKCS12 43
  471. #endif
  472. static int do_file_type(const char *type)
  473. {
  474. if(!type || !type[0])
  475. return SSL_FILETYPE_PEM;
  476. if(strcasecompare(type, "PEM"))
  477. return SSL_FILETYPE_PEM;
  478. if(strcasecompare(type, "DER"))
  479. return SSL_FILETYPE_ASN1;
  480. if(strcasecompare(type, "ENG"))
  481. return SSL_FILETYPE_ENGINE;
  482. if(strcasecompare(type, "P12"))
  483. return SSL_FILETYPE_PKCS12;
  484. return -1;
  485. }
  486. #ifdef USE_OPENSSL_ENGINE
  487. /*
  488. * Supply default password to the engine user interface conversation.
  489. * The password is passed by OpenSSL engine from ENGINE_load_private_key()
  490. * last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
  491. */
  492. static int ssl_ui_reader(UI *ui, UI_STRING *uis)
  493. {
  494. const char *password;
  495. switch(UI_get_string_type(uis)) {
  496. case UIT_PROMPT:
  497. case UIT_VERIFY:
  498. password = (const char *)UI_get0_user_data(ui);
  499. if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
  500. UI_set_result(ui, uis, password);
  501. return 1;
  502. }
  503. default:
  504. break;
  505. }
  506. return (UI_method_get_reader(UI_OpenSSL()))(ui, uis);
  507. }
  508. /*
  509. * Suppress interactive request for a default password if available.
  510. */
  511. static int ssl_ui_writer(UI *ui, UI_STRING *uis)
  512. {
  513. switch(UI_get_string_type(uis)) {
  514. case UIT_PROMPT:
  515. case UIT_VERIFY:
  516. if(UI_get0_user_data(ui) &&
  517. (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
  518. return 1;
  519. }
  520. default:
  521. break;
  522. }
  523. return (UI_method_get_writer(UI_OpenSSL()))(ui, uis);
  524. }
  525. /*
  526. * Check if a given string is a PKCS#11 URI
  527. */
  528. static bool is_pkcs11_uri(const char *string)
  529. {
  530. return (string && strncasecompare(string, "pkcs11:", 7));
  531. }
  532. #endif
  533. static CURLcode ossl_set_engine(struct Curl_easy *data, const char *engine);
  534. static int
  535. SSL_CTX_use_certificate_blob(SSL_CTX *ctx, const struct curl_blob *blob,
  536. int type, const char *key_passwd)
  537. {
  538. int ret = 0;
  539. X509 *x = NULL;
  540. /* the typecast of blob->len is fine since it is guaranteed to never be
  541. larger than CURL_MAX_INPUT_LENGTH */
  542. BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len));
  543. if(!in)
  544. return CURLE_OUT_OF_MEMORY;
  545. if(type == SSL_FILETYPE_ASN1) {
  546. /* j = ERR_R_ASN1_LIB; */
  547. x = d2i_X509_bio(in, NULL);
  548. }
  549. else if(type == SSL_FILETYPE_PEM) {
  550. /* ERR_R_PEM_LIB; */
  551. x = PEM_read_bio_X509(in, NULL,
  552. passwd_callback, (void *)key_passwd);
  553. }
  554. else {
  555. ret = 0;
  556. goto end;
  557. }
  558. if(!x) {
  559. ret = 0;
  560. goto end;
  561. }
  562. ret = SSL_CTX_use_certificate(ctx, x);
  563. end:
  564. X509_free(x);
  565. BIO_free(in);
  566. return ret;
  567. }
  568. static int
  569. SSL_CTX_use_PrivateKey_blob(SSL_CTX *ctx, const struct curl_blob *blob,
  570. int type, const char *key_passwd)
  571. {
  572. int ret = 0;
  573. EVP_PKEY *pkey = NULL;
  574. BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len));
  575. if(!in)
  576. return CURLE_OUT_OF_MEMORY;
  577. if(type == SSL_FILETYPE_PEM)
  578. pkey = PEM_read_bio_PrivateKey(in, NULL, passwd_callback,
  579. (void *)key_passwd);
  580. else if(type == SSL_FILETYPE_ASN1)
  581. pkey = d2i_PrivateKey_bio(in, NULL);
  582. else {
  583. ret = 0;
  584. goto end;
  585. }
  586. if(!pkey) {
  587. ret = 0;
  588. goto end;
  589. }
  590. ret = SSL_CTX_use_PrivateKey(ctx, pkey);
  591. EVP_PKEY_free(pkey);
  592. end:
  593. BIO_free(in);
  594. return ret;
  595. }
  596. static int
  597. SSL_CTX_use_certificate_chain_blob(SSL_CTX *ctx, const struct curl_blob *blob,
  598. const char *key_passwd)
  599. {
  600. /* SSL_CTX_add1_chain_cert introduced in OpenSSL 1.0.2 */
  601. #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* OpenSSL 1.0.2 or later */ \
  602. !(defined(LIBRESSL_VERSION_NUMBER) && \
  603. (LIBRESSL_VERSION_NUMBER < 0x2090100fL)) /* LibreSSL 2.9.1 or later */
  604. int ret = 0;
  605. X509 *x = NULL;
  606. void *passwd_callback_userdata = (void *)key_passwd;
  607. BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len));
  608. if(!in)
  609. return CURLE_OUT_OF_MEMORY;
  610. ERR_clear_error();
  611. x = PEM_read_bio_X509_AUX(in, NULL,
  612. passwd_callback, (void *)key_passwd);
  613. if(!x) {
  614. ret = 0;
  615. goto end;
  616. }
  617. ret = SSL_CTX_use_certificate(ctx, x);
  618. if(ERR_peek_error() != 0)
  619. ret = 0;
  620. if(ret) {
  621. X509 *ca;
  622. unsigned long err;
  623. if(!SSL_CTX_clear_chain_certs(ctx)) {
  624. ret = 0;
  625. goto end;
  626. }
  627. while((ca = PEM_read_bio_X509(in, NULL, passwd_callback,
  628. passwd_callback_userdata))
  629. != NULL) {
  630. if(!SSL_CTX_add0_chain_cert(ctx, ca)) {
  631. X509_free(ca);
  632. ret = 0;
  633. goto end;
  634. }
  635. }
  636. err = ERR_peek_last_error();
  637. if((ERR_GET_LIB(err) == ERR_LIB_PEM) &&
  638. (ERR_GET_REASON(err) == PEM_R_NO_START_LINE))
  639. ERR_clear_error();
  640. else
  641. ret = 0;
  642. }
  643. end:
  644. X509_free(x);
  645. BIO_free(in);
  646. return ret;
  647. #else
  648. (void)ctx; /* unused */
  649. (void)blob; /* unused */
  650. (void)key_passwd; /* unused */
  651. return 0;
  652. #endif
  653. }
  654. static
  655. int cert_stuff(struct Curl_easy *data,
  656. SSL_CTX* ctx,
  657. char *cert_file,
  658. const struct curl_blob *cert_blob,
  659. const char *cert_type,
  660. char *key_file,
  661. const struct curl_blob *key_blob,
  662. const char *key_type,
  663. char *key_passwd)
  664. {
  665. char error_buffer[256];
  666. bool check_privkey = TRUE;
  667. int file_type = do_file_type(cert_type);
  668. if(cert_file || cert_blob || (file_type == SSL_FILETYPE_ENGINE)) {
  669. SSL *ssl;
  670. X509 *x509;
  671. int cert_done = 0;
  672. int cert_use_result;
  673. if(key_passwd) {
  674. /* set the password in the callback userdata */
  675. SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd);
  676. /* Set passwd callback: */
  677. SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
  678. }
  679. switch(file_type) {
  680. case SSL_FILETYPE_PEM:
  681. /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
  682. cert_use_result = cert_blob ?
  683. SSL_CTX_use_certificate_chain_blob(ctx, cert_blob, key_passwd) :
  684. SSL_CTX_use_certificate_chain_file(ctx, cert_file);
  685. if(cert_use_result != 1) {
  686. failf(data,
  687. "could not load PEM client certificate, " OSSL_PACKAGE
  688. " error %s, "
  689. "(no key found, wrong pass phrase, or wrong file format?)",
  690. ossl_strerror(ERR_get_error(), error_buffer,
  691. sizeof(error_buffer)) );
  692. return 0;
  693. }
  694. break;
  695. case SSL_FILETYPE_ASN1:
  696. /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
  697. we use the case above for PEM so this can only be performed with
  698. ASN1 files. */
  699. cert_use_result = cert_blob ?
  700. SSL_CTX_use_certificate_blob(ctx, cert_blob,
  701. file_type, key_passwd) :
  702. SSL_CTX_use_certificate_file(ctx, cert_file, file_type);
  703. if(cert_use_result != 1) {
  704. failf(data,
  705. "could not load ASN1 client certificate, " OSSL_PACKAGE
  706. " error %s, "
  707. "(no key found, wrong pass phrase, or wrong file format?)",
  708. ossl_strerror(ERR_get_error(), error_buffer,
  709. sizeof(error_buffer)) );
  710. return 0;
  711. }
  712. break;
  713. case SSL_FILETYPE_ENGINE:
  714. #if defined(USE_OPENSSL_ENGINE) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
  715. {
  716. /* Implicitly use pkcs11 engine if none was provided and the
  717. * cert_file is a PKCS#11 URI */
  718. if(!data->state.engine) {
  719. if(is_pkcs11_uri(cert_file)) {
  720. if(ossl_set_engine(data, "pkcs11") != CURLE_OK) {
  721. return 0;
  722. }
  723. }
  724. }
  725. if(data->state.engine) {
  726. const char *cmd_name = "LOAD_CERT_CTRL";
  727. struct {
  728. const char *cert_id;
  729. X509 *cert;
  730. } params;
  731. params.cert_id = cert_file;
  732. params.cert = NULL;
  733. /* Does the engine supports LOAD_CERT_CTRL ? */
  734. if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
  735. 0, (void *)cmd_name, NULL)) {
  736. failf(data, "ssl engine does not support loading certificates");
  737. return 0;
  738. }
  739. /* Load the certificate from the engine */
  740. if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
  741. 0, &params, NULL, 1)) {
  742. failf(data, "ssl engine cannot load client cert with id"
  743. " '%s' [%s]", cert_file,
  744. ossl_strerror(ERR_get_error(), error_buffer,
  745. sizeof(error_buffer)));
  746. return 0;
  747. }
  748. if(!params.cert) {
  749. failf(data, "ssl engine didn't initialized the certificate "
  750. "properly.");
  751. return 0;
  752. }
  753. if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
  754. failf(data, "unable to set client certificate");
  755. X509_free(params.cert);
  756. return 0;
  757. }
  758. X509_free(params.cert); /* we don't need the handle any more... */
  759. }
  760. else {
  761. failf(data, "crypto engine not set, can't load certificate");
  762. return 0;
  763. }
  764. }
  765. break;
  766. #else
  767. failf(data, "file type ENG for certificate not implemented");
  768. return 0;
  769. #endif
  770. case SSL_FILETYPE_PKCS12:
  771. {
  772. BIO *cert_bio = NULL;
  773. PKCS12 *p12 = NULL;
  774. EVP_PKEY *pri;
  775. STACK_OF(X509) *ca = NULL;
  776. if(cert_blob) {
  777. cert_bio = BIO_new_mem_buf(cert_blob->data, (int)(cert_blob->len));
  778. if(!cert_bio) {
  779. failf(data,
  780. "BIO_new_mem_buf NULL, " OSSL_PACKAGE
  781. " error %s",
  782. ossl_strerror(ERR_get_error(), error_buffer,
  783. sizeof(error_buffer)) );
  784. return 0;
  785. }
  786. }
  787. else {
  788. cert_bio = BIO_new(BIO_s_file());
  789. if(!cert_bio) {
  790. failf(data,
  791. "BIO_new return NULL, " OSSL_PACKAGE
  792. " error %s",
  793. ossl_strerror(ERR_get_error(), error_buffer,
  794. sizeof(error_buffer)) );
  795. return 0;
  796. }
  797. if(BIO_read_filename(cert_bio, cert_file) <= 0) {
  798. failf(data, "could not open PKCS12 file '%s'", cert_file);
  799. BIO_free(cert_bio);
  800. return 0;
  801. }
  802. }
  803. p12 = d2i_PKCS12_bio(cert_bio, NULL);
  804. BIO_free(cert_bio);
  805. if(!p12) {
  806. failf(data, "error reading PKCS12 file '%s'",
  807. cert_blob ? "(memory blob)" : cert_file);
  808. return 0;
  809. }
  810. PKCS12_PBE_add();
  811. if(!PKCS12_parse(p12, key_passwd, &pri, &x509,
  812. &ca)) {
  813. failf(data,
  814. "could not parse PKCS12 file, check password, " OSSL_PACKAGE
  815. " error %s",
  816. ossl_strerror(ERR_get_error(), error_buffer,
  817. sizeof(error_buffer)) );
  818. PKCS12_free(p12);
  819. return 0;
  820. }
  821. PKCS12_free(p12);
  822. if(SSL_CTX_use_certificate(ctx, x509) != 1) {
  823. failf(data,
  824. "could not load PKCS12 client certificate, " OSSL_PACKAGE
  825. " error %s",
  826. ossl_strerror(ERR_get_error(), error_buffer,
  827. sizeof(error_buffer)) );
  828. goto fail;
  829. }
  830. if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
  831. failf(data, "unable to use private key from PKCS12 file '%s'",
  832. cert_file);
  833. goto fail;
  834. }
  835. if(!SSL_CTX_check_private_key (ctx)) {
  836. failf(data, "private key from PKCS12 file '%s' "
  837. "does not match certificate in same file", cert_file);
  838. goto fail;
  839. }
  840. /* Set Certificate Verification chain */
  841. if(ca) {
  842. while(sk_X509_num(ca)) {
  843. /*
  844. * Note that sk_X509_pop() is used below to make sure the cert is
  845. * removed from the stack properly before getting passed to
  846. * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously
  847. * we used sk_X509_value() instead, but then we'd clean it in the
  848. * subsequent sk_X509_pop_free() call.
  849. */
  850. X509 *x = sk_X509_pop(ca);
  851. if(!SSL_CTX_add_client_CA(ctx, x)) {
  852. X509_free(x);
  853. failf(data, "cannot add certificate to client CA list");
  854. goto fail;
  855. }
  856. if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
  857. X509_free(x);
  858. failf(data, "cannot add certificate to certificate chain");
  859. goto fail;
  860. }
  861. }
  862. }
  863. cert_done = 1;
  864. fail:
  865. EVP_PKEY_free(pri);
  866. X509_free(x509);
  867. #ifdef USE_AMISSL
  868. sk_X509_pop_free(ca, Curl_amiga_X509_free);
  869. #else
  870. sk_X509_pop_free(ca, X509_free);
  871. #endif
  872. if(!cert_done)
  873. return 0; /* failure! */
  874. break;
  875. }
  876. default:
  877. failf(data, "not supported file type '%s' for certificate", cert_type);
  878. return 0;
  879. }
  880. if((!key_file) && (!key_blob)) {
  881. key_file = cert_file;
  882. key_blob = cert_blob;
  883. }
  884. else
  885. file_type = do_file_type(key_type);
  886. switch(file_type) {
  887. case SSL_FILETYPE_PEM:
  888. if(cert_done)
  889. break;
  890. /* FALLTHROUGH */
  891. case SSL_FILETYPE_ASN1:
  892. cert_use_result = key_blob ?
  893. SSL_CTX_use_PrivateKey_blob(ctx, key_blob, file_type, key_passwd) :
  894. SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type);
  895. if(cert_use_result != 1) {
  896. failf(data, "unable to set private key file: '%s' type %s",
  897. key_file?key_file:"(memory blob)", key_type?key_type:"PEM");
  898. return 0;
  899. }
  900. break;
  901. case SSL_FILETYPE_ENGINE:
  902. #ifdef USE_OPENSSL_ENGINE
  903. { /* XXXX still needs some work */
  904. EVP_PKEY *priv_key = NULL;
  905. /* Implicitly use pkcs11 engine if none was provided and the
  906. * key_file is a PKCS#11 URI */
  907. if(!data->state.engine) {
  908. if(is_pkcs11_uri(key_file)) {
  909. if(ossl_set_engine(data, "pkcs11") != CURLE_OK) {
  910. return 0;
  911. }
  912. }
  913. }
  914. if(data->state.engine) {
  915. UI_METHOD *ui_method =
  916. UI_create_method((char *)"curl user interface");
  917. if(!ui_method) {
  918. failf(data, "unable do create " OSSL_PACKAGE
  919. " user-interface method");
  920. return 0;
  921. }
  922. UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
  923. UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
  924. UI_method_set_reader(ui_method, ssl_ui_reader);
  925. UI_method_set_writer(ui_method, ssl_ui_writer);
  926. /* the typecast below was added to please mingw32 */
  927. priv_key = (EVP_PKEY *)
  928. ENGINE_load_private_key(data->state.engine, key_file,
  929. ui_method,
  930. key_passwd);
  931. UI_destroy_method(ui_method);
  932. if(!priv_key) {
  933. failf(data, "failed to load private key from crypto engine");
  934. return 0;
  935. }
  936. if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
  937. failf(data, "unable to set private key");
  938. EVP_PKEY_free(priv_key);
  939. return 0;
  940. }
  941. EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
  942. }
  943. else {
  944. failf(data, "crypto engine not set, can't load private key");
  945. return 0;
  946. }
  947. }
  948. break;
  949. #else
  950. failf(data, "file type ENG for private key not supported");
  951. return 0;
  952. #endif
  953. case SSL_FILETYPE_PKCS12:
  954. if(!cert_done) {
  955. failf(data, "file type P12 for private key not supported");
  956. return 0;
  957. }
  958. break;
  959. default:
  960. failf(data, "not supported file type for private key");
  961. return 0;
  962. }
  963. ssl = SSL_new(ctx);
  964. if(!ssl) {
  965. failf(data, "unable to create an SSL structure");
  966. return 0;
  967. }
  968. x509 = SSL_get_certificate(ssl);
  969. /* This version was provided by Evan Jordan and is supposed to not
  970. leak memory as the previous version: */
  971. if(x509) {
  972. EVP_PKEY *pktmp = X509_get_pubkey(x509);
  973. EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl));
  974. EVP_PKEY_free(pktmp);
  975. }
  976. #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_IS_BORINGSSL)
  977. {
  978. /* If RSA is used, don't check the private key if its flags indicate
  979. * it doesn't support it. */
  980. EVP_PKEY *priv_key = SSL_get_privatekey(ssl);
  981. int pktype;
  982. #ifdef HAVE_OPAQUE_EVP_PKEY
  983. pktype = EVP_PKEY_id(priv_key);
  984. #else
  985. pktype = priv_key->type;
  986. #endif
  987. if(pktype == EVP_PKEY_RSA) {
  988. RSA *rsa = EVP_PKEY_get1_RSA(priv_key);
  989. if(RSA_flags(rsa) & RSA_METHOD_FLAG_NO_CHECK)
  990. check_privkey = FALSE;
  991. RSA_free(rsa); /* Decrement reference count */
  992. }
  993. }
  994. #endif
  995. SSL_free(ssl);
  996. /* If we are using DSA, we can copy the parameters from
  997. * the private key */
  998. if(check_privkey == TRUE) {
  999. /* Now we know that a key and cert have been set against
  1000. * the SSL context */
  1001. if(!SSL_CTX_check_private_key(ctx)) {
  1002. failf(data, "Private key does not match the certificate public key");
  1003. return 0;
  1004. }
  1005. }
  1006. }
  1007. return 1;
  1008. }
  1009. /* returns non-zero on failure */
  1010. static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
  1011. {
  1012. BIO *bio_out = BIO_new(BIO_s_mem());
  1013. BUF_MEM *biomem;
  1014. int rc;
  1015. if(!bio_out)
  1016. return 1; /* alloc failed! */
  1017. rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC);
  1018. BIO_get_mem_ptr(bio_out, &biomem);
  1019. if((size_t)biomem->length < size)
  1020. size = biomem->length;
  1021. else
  1022. size--; /* don't overwrite the buffer end */
  1023. memcpy(buf, biomem->data, size);
  1024. buf[size] = 0;
  1025. BIO_free(bio_out);
  1026. return !rc;
  1027. }
  1028. /**
  1029. * Global SSL init
  1030. *
  1031. * @retval 0 error initializing SSL
  1032. * @retval 1 SSL initialized successfully
  1033. */
  1034. static int ossl_init(void)
  1035. {
  1036. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
  1037. !defined(LIBRESSL_VERSION_NUMBER)
  1038. const uint64_t flags =
  1039. #ifdef OPENSSL_INIT_ENGINE_ALL_BUILTIN
  1040. /* not present in BoringSSL */
  1041. OPENSSL_INIT_ENGINE_ALL_BUILTIN |
  1042. #endif
  1043. #ifdef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG
  1044. OPENSSL_INIT_NO_LOAD_CONFIG |
  1045. #else
  1046. OPENSSL_INIT_LOAD_CONFIG |
  1047. #endif
  1048. 0;
  1049. OPENSSL_init_ssl(flags, NULL);
  1050. #else
  1051. OPENSSL_load_builtin_modules();
  1052. #ifdef USE_OPENSSL_ENGINE
  1053. ENGINE_load_builtin_engines();
  1054. #endif
  1055. /* CONF_MFLAGS_DEFAULT_SECTION was introduced some time between 0.9.8b and
  1056. 0.9.8e */
  1057. #ifndef CONF_MFLAGS_DEFAULT_SECTION
  1058. #define CONF_MFLAGS_DEFAULT_SECTION 0x0
  1059. #endif
  1060. #ifndef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG
  1061. CONF_modules_load_file(NULL, NULL,
  1062. CONF_MFLAGS_DEFAULT_SECTION|
  1063. CONF_MFLAGS_IGNORE_MISSING_FILE);
  1064. #endif
  1065. /* Lets get nice error messages */
  1066. SSL_load_error_strings();
  1067. /* Init the global ciphers and digests */
  1068. if(!SSLeay_add_ssl_algorithms())
  1069. return 0;
  1070. OpenSSL_add_all_algorithms();
  1071. #endif
  1072. Curl_tls_keylog_open();
  1073. /* Initialize the extra data indexes */
  1074. if(ossl_get_ssl_data_index() < 0 || ossl_get_ssl_conn_index() < 0 ||
  1075. ossl_get_ssl_sockindex_index() < 0 || ossl_get_proxy_index() < 0)
  1076. return 0;
  1077. return 1;
  1078. }
  1079. /* Global cleanup */
  1080. static void ossl_cleanup(void)
  1081. {
  1082. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
  1083. !defined(LIBRESSL_VERSION_NUMBER)
  1084. /* OpenSSL 1.1 deprecates all these cleanup functions and
  1085. turns them into no-ops in OpenSSL 1.0 compatibility mode */
  1086. #else
  1087. /* Free ciphers and digests lists */
  1088. EVP_cleanup();
  1089. #ifdef USE_OPENSSL_ENGINE
  1090. /* Free engine list */
  1091. ENGINE_cleanup();
  1092. #endif
  1093. /* Free OpenSSL error strings */
  1094. ERR_free_strings();
  1095. /* Free thread local error state, destroying hash upon zero refcount */
  1096. #ifdef HAVE_ERR_REMOVE_THREAD_STATE
  1097. ERR_remove_thread_state(NULL);
  1098. #else
  1099. ERR_remove_state(0);
  1100. #endif
  1101. /* Free all memory allocated by all configuration modules */
  1102. CONF_modules_free();
  1103. #ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS
  1104. SSL_COMP_free_compression_methods();
  1105. #endif
  1106. #endif
  1107. Curl_tls_keylog_close();
  1108. }
  1109. /*
  1110. * This function is used to determine connection status.
  1111. *
  1112. * Return codes:
  1113. * 1 means the connection is still in place
  1114. * 0 means the connection has been closed
  1115. * -1 means the connection status is unknown
  1116. */
  1117. static int ossl_check_cxn(struct connectdata *conn)
  1118. {
  1119. /* SSL_peek takes data out of the raw recv buffer without peeking so we use
  1120. recv MSG_PEEK instead. Bug #795 */
  1121. #ifdef MSG_PEEK
  1122. char buf;
  1123. ssize_t nread;
  1124. nread = recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
  1125. (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK);
  1126. if(nread == 0)
  1127. return 0; /* connection has been closed */
  1128. if(nread == 1)
  1129. return 1; /* connection still in place */
  1130. else if(nread == -1) {
  1131. int err = SOCKERRNO;
  1132. if(err == EINPROGRESS ||
  1133. #if defined(EAGAIN) && (EAGAIN != EWOULDBLOCK)
  1134. err == EAGAIN ||
  1135. #endif
  1136. err == EWOULDBLOCK)
  1137. return 1; /* connection still in place */
  1138. if(err == ECONNRESET ||
  1139. #ifdef ECONNABORTED
  1140. err == ECONNABORTED ||
  1141. #endif
  1142. #ifdef ENETDOWN
  1143. err == ENETDOWN ||
  1144. #endif
  1145. #ifdef ENETRESET
  1146. err == ENETRESET ||
  1147. #endif
  1148. #ifdef ESHUTDOWN
  1149. err == ESHUTDOWN ||
  1150. #endif
  1151. #ifdef ETIMEDOUT
  1152. err == ETIMEDOUT ||
  1153. #endif
  1154. err == ENOTCONN)
  1155. return 0; /* connection has been closed */
  1156. }
  1157. #endif
  1158. return -1; /* connection status unknown */
  1159. }
  1160. /* Selects an OpenSSL crypto engine
  1161. */
  1162. static CURLcode ossl_set_engine(struct Curl_easy *data, const char *engine)
  1163. {
  1164. #ifdef USE_OPENSSL_ENGINE
  1165. ENGINE *e;
  1166. #if OPENSSL_VERSION_NUMBER >= 0x00909000L
  1167. e = ENGINE_by_id(engine);
  1168. #else
  1169. /* avoid memory leak */
  1170. for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
  1171. const char *e_id = ENGINE_get_id(e);
  1172. if(!strcmp(engine, e_id))
  1173. break;
  1174. }
  1175. #endif
  1176. if(!e) {
  1177. failf(data, "SSL Engine '%s' not found", engine);
  1178. return CURLE_SSL_ENGINE_NOTFOUND;
  1179. }
  1180. if(data->state.engine) {
  1181. ENGINE_finish(data->state.engine);
  1182. ENGINE_free(data->state.engine);
  1183. data->state.engine = NULL;
  1184. }
  1185. if(!ENGINE_init(e)) {
  1186. char buf[256];
  1187. ENGINE_free(e);
  1188. failf(data, "Failed to initialise SSL Engine '%s': %s",
  1189. engine, ossl_strerror(ERR_get_error(), buf, sizeof(buf)));
  1190. return CURLE_SSL_ENGINE_INITFAILED;
  1191. }
  1192. data->state.engine = e;
  1193. return CURLE_OK;
  1194. #else
  1195. (void)engine;
  1196. failf(data, "SSL Engine not supported");
  1197. return CURLE_SSL_ENGINE_NOTFOUND;
  1198. #endif
  1199. }
  1200. /* Sets engine as default for all SSL operations
  1201. */
  1202. static CURLcode ossl_set_engine_default(struct Curl_easy *data)
  1203. {
  1204. #ifdef USE_OPENSSL_ENGINE
  1205. if(data->state.engine) {
  1206. if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
  1207. infof(data, "set default crypto engine '%s'\n",
  1208. ENGINE_get_id(data->state.engine));
  1209. }
  1210. else {
  1211. failf(data, "set default crypto engine '%s' failed",
  1212. ENGINE_get_id(data->state.engine));
  1213. return CURLE_SSL_ENGINE_SETFAILED;
  1214. }
  1215. }
  1216. #else
  1217. (void) data;
  1218. #endif
  1219. return CURLE_OK;
  1220. }
  1221. /* Return list of OpenSSL crypto engine names.
  1222. */
  1223. static struct curl_slist *ossl_engines_list(struct Curl_easy *data)
  1224. {
  1225. struct curl_slist *list = NULL;
  1226. #ifdef USE_OPENSSL_ENGINE
  1227. struct curl_slist *beg;
  1228. ENGINE *e;
  1229. for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
  1230. beg = curl_slist_append(list, ENGINE_get_id(e));
  1231. if(!beg) {
  1232. curl_slist_free_all(list);
  1233. return NULL;
  1234. }
  1235. list = beg;
  1236. }
  1237. #endif
  1238. (void) data;
  1239. return list;
  1240. }
  1241. #define set_logger(conn, data) \
  1242. conn->ssl[0].backend->logger = data
  1243. static void ossl_closeone(struct Curl_easy *data,
  1244. struct connectdata *conn,
  1245. struct ssl_connect_data *connssl)
  1246. {
  1247. struct ssl_backend_data *backend = connssl->backend;
  1248. if(backend->handle) {
  1249. set_logger(conn, data);
  1250. (void)SSL_shutdown(backend->handle);
  1251. SSL_set_connect_state(backend->handle);
  1252. SSL_free(backend->handle);
  1253. backend->handle = NULL;
  1254. }
  1255. if(backend->ctx) {
  1256. SSL_CTX_free(backend->ctx);
  1257. backend->ctx = NULL;
  1258. }
  1259. }
  1260. /*
  1261. * This function is called when an SSL connection is closed.
  1262. */
  1263. static void ossl_close(struct Curl_easy *data, struct connectdata *conn,
  1264. int sockindex)
  1265. {
  1266. ossl_closeone(data, conn, &conn->ssl[sockindex]);
  1267. #ifndef CURL_DISABLE_PROXY
  1268. ossl_closeone(data, conn, &conn->proxy_ssl[sockindex]);
  1269. #endif
  1270. }
  1271. /*
  1272. * This function is called to shut down the SSL layer but keep the
  1273. * socket open (CCC - Clear Command Channel)
  1274. */
  1275. static int ossl_shutdown(struct Curl_easy *data,
  1276. struct connectdata *conn, int sockindex)
  1277. {
  1278. int retval = 0;
  1279. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1280. char buf[256]; /* We will use this for the OpenSSL error buffer, so it has
  1281. to be at least 256 bytes long. */
  1282. unsigned long sslerror;
  1283. ssize_t nread;
  1284. int buffsize;
  1285. int err;
  1286. bool done = FALSE;
  1287. struct ssl_backend_data *backend = connssl->backend;
  1288. #ifndef CURL_DISABLE_FTP
  1289. /* This has only been tested on the proftpd server, and the mod_tls code
  1290. sends a close notify alert without waiting for a close notify alert in
  1291. response. Thus we wait for a close notify alert from the server, but
  1292. we do not send one. Let's hope other servers do the same... */
  1293. if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
  1294. (void)SSL_shutdown(backend->handle);
  1295. #endif
  1296. if(backend->handle) {
  1297. buffsize = (int)sizeof(buf);
  1298. while(!done) {
  1299. int what = SOCKET_READABLE(conn->sock[sockindex],
  1300. SSL_SHUTDOWN_TIMEOUT);
  1301. if(what > 0) {
  1302. ERR_clear_error();
  1303. /* Something to read, let's do it and hope that it is the close
  1304. notify alert from the server */
  1305. nread = (ssize_t)SSL_read(backend->handle, buf, buffsize);
  1306. err = SSL_get_error(backend->handle, (int)nread);
  1307. switch(err) {
  1308. case SSL_ERROR_NONE: /* this is not an error */
  1309. case SSL_ERROR_ZERO_RETURN: /* no more data */
  1310. /* This is the expected response. There was no data but only
  1311. the close notify alert */
  1312. done = TRUE;
  1313. break;
  1314. case SSL_ERROR_WANT_READ:
  1315. /* there's data pending, re-invoke SSL_read() */
  1316. infof(data, "SSL_ERROR_WANT_READ\n");
  1317. break;
  1318. case SSL_ERROR_WANT_WRITE:
  1319. /* SSL wants a write. Really odd. Let's bail out. */
  1320. infof(data, "SSL_ERROR_WANT_WRITE\n");
  1321. done = TRUE;
  1322. break;
  1323. default:
  1324. /* openssl/ssl.h says "look at error stack/return value/errno" */
  1325. sslerror = ERR_get_error();
  1326. failf(data, OSSL_PACKAGE " SSL_read on shutdown: %s, errno %d",
  1327. (sslerror ?
  1328. ossl_strerror(sslerror, buf, sizeof(buf)) :
  1329. SSL_ERROR_to_str(err)),
  1330. SOCKERRNO);
  1331. done = TRUE;
  1332. break;
  1333. }
  1334. }
  1335. else if(0 == what) {
  1336. /* timeout */
  1337. failf(data, "SSL shutdown timeout");
  1338. done = TRUE;
  1339. }
  1340. else {
  1341. /* anything that gets here is fatally bad */
  1342. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  1343. retval = -1;
  1344. done = TRUE;
  1345. }
  1346. } /* while()-loop for the select() */
  1347. if(data->set.verbose) {
  1348. #ifdef HAVE_SSL_GET_SHUTDOWN
  1349. switch(SSL_get_shutdown(backend->handle)) {
  1350. case SSL_SENT_SHUTDOWN:
  1351. infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
  1352. break;
  1353. case SSL_RECEIVED_SHUTDOWN:
  1354. infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
  1355. break;
  1356. case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
  1357. infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
  1358. "SSL_RECEIVED__SHUTDOWN\n");
  1359. break;
  1360. }
  1361. #endif
  1362. }
  1363. SSL_free(backend->handle);
  1364. backend->handle = NULL;
  1365. }
  1366. return retval;
  1367. }
  1368. static void ossl_session_free(void *ptr)
  1369. {
  1370. /* free the ID */
  1371. SSL_SESSION_free(ptr);
  1372. }
  1373. /*
  1374. * This function is called when the 'data' struct is going away. Close
  1375. * down everything and free all resources!
  1376. */
  1377. static void ossl_close_all(struct Curl_easy *data)
  1378. {
  1379. #ifdef USE_OPENSSL_ENGINE
  1380. if(data->state.engine) {
  1381. ENGINE_finish(data->state.engine);
  1382. ENGINE_free(data->state.engine);
  1383. data->state.engine = NULL;
  1384. }
  1385. #else
  1386. (void)data;
  1387. #endif
  1388. #if !defined(HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED) && \
  1389. defined(HAVE_ERR_REMOVE_THREAD_STATE)
  1390. /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread
  1391. so we need to clean it here in case the thread will be killed. All OpenSSL
  1392. code should extract the error in association with the error so clearing
  1393. this queue here should be harmless at worst. */
  1394. ERR_remove_thread_state(NULL);
  1395. #endif
  1396. }
  1397. /* ====================================================== */
  1398. /*
  1399. * Match subjectAltName against the host name. This requires a conversion
  1400. * in CURL_DOES_CONVERSIONS builds.
  1401. */
  1402. static bool subj_alt_hostcheck(struct Curl_easy *data,
  1403. const char *match_pattern, const char *hostname,
  1404. const char *dispname)
  1405. #ifdef CURL_DOES_CONVERSIONS
  1406. {
  1407. bool res = FALSE;
  1408. /* Curl_cert_hostcheck uses host encoding, but we get ASCII from
  1409. OpenSSl.
  1410. */
  1411. char *match_pattern2 = strdup(match_pattern);
  1412. if(match_pattern2) {
  1413. if(Curl_convert_from_network(data, match_pattern2,
  1414. strlen(match_pattern2)) == CURLE_OK) {
  1415. if(Curl_cert_hostcheck(match_pattern2, hostname)) {
  1416. res = TRUE;
  1417. infof(data,
  1418. " subjectAltName: host \"%s\" matched cert's \"%s\"\n",
  1419. dispname, match_pattern2);
  1420. }
  1421. }
  1422. free(match_pattern2);
  1423. }
  1424. else {
  1425. failf(data,
  1426. "SSL: out of memory when allocating temporary for subjectAltName");
  1427. }
  1428. return res;
  1429. }
  1430. #else
  1431. {
  1432. #ifdef CURL_DISABLE_VERBOSE_STRINGS
  1433. (void)dispname;
  1434. (void)data;
  1435. #endif
  1436. if(Curl_cert_hostcheck(match_pattern, hostname)) {
  1437. infof(data, " subjectAltName: host \"%s\" matched cert's \"%s\"\n",
  1438. dispname, match_pattern);
  1439. return TRUE;
  1440. }
  1441. return FALSE;
  1442. }
  1443. #endif
  1444. /* Quote from RFC2818 section 3.1 "Server Identity"
  1445. If a subjectAltName extension of type dNSName is present, that MUST
  1446. be used as the identity. Otherwise, the (most specific) Common Name
  1447. field in the Subject field of the certificate MUST be used. Although
  1448. the use of the Common Name is existing practice, it is deprecated and
  1449. Certification Authorities are encouraged to use the dNSName instead.
  1450. Matching is performed using the matching rules specified by
  1451. [RFC2459]. If more than one identity of a given type is present in
  1452. the certificate (e.g., more than one dNSName name, a match in any one
  1453. of the set is considered acceptable.) Names may contain the wildcard
  1454. character * which is considered to match any single domain name
  1455. component or component fragment. E.g., *.a.com matches foo.a.com but
  1456. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  1457. In some cases, the URI is specified as an IP address rather than a
  1458. hostname. In this case, the iPAddress subjectAltName must be present
  1459. in the certificate and must exactly match the IP in the URI.
  1460. */
  1461. static CURLcode verifyhost(struct Curl_easy *data, struct connectdata *conn,
  1462. X509 *server_cert)
  1463. {
  1464. bool matched = FALSE;
  1465. int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
  1466. size_t addrlen = 0;
  1467. STACK_OF(GENERAL_NAME) *altnames;
  1468. #ifdef ENABLE_IPV6
  1469. struct in6_addr addr;
  1470. #else
  1471. struct in_addr addr;
  1472. #endif
  1473. CURLcode result = CURLE_OK;
  1474. bool dNSName = FALSE; /* if a dNSName field exists in the cert */
  1475. bool iPAddress = FALSE; /* if a iPAddress field exists in the cert */
  1476. const char * const hostname = SSL_HOST_NAME();
  1477. const char * const dispname = SSL_HOST_DISPNAME();
  1478. #ifdef ENABLE_IPV6
  1479. if(conn->bits.ipv6_ip &&
  1480. Curl_inet_pton(AF_INET6, hostname, &addr)) {
  1481. target = GEN_IPADD;
  1482. addrlen = sizeof(struct in6_addr);
  1483. }
  1484. else
  1485. #endif
  1486. if(Curl_inet_pton(AF_INET, hostname, &addr)) {
  1487. target = GEN_IPADD;
  1488. addrlen = sizeof(struct in_addr);
  1489. }
  1490. /* get a "list" of alternative names */
  1491. altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
  1492. if(altnames) {
  1493. #ifdef OPENSSL_IS_BORINGSSL
  1494. size_t numalts;
  1495. size_t i;
  1496. #else
  1497. int numalts;
  1498. int i;
  1499. #endif
  1500. bool dnsmatched = FALSE;
  1501. bool ipmatched = FALSE;
  1502. /* get amount of alternatives, RFC2459 claims there MUST be at least
  1503. one, but we don't depend on it... */
  1504. numalts = sk_GENERAL_NAME_num(altnames);
  1505. /* loop through all alternatives - until a dnsmatch */
  1506. for(i = 0; (i < numalts) && !dnsmatched; i++) {
  1507. /* get a handle to alternative name number i */
  1508. const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
  1509. if(check->type == GEN_DNS)
  1510. dNSName = TRUE;
  1511. else if(check->type == GEN_IPADD)
  1512. iPAddress = TRUE;
  1513. /* only check alternatives of the same type the target is */
  1514. if(check->type == target) {
  1515. /* get data and length */
  1516. const char *altptr = (char *)ASN1_STRING_get0_data(check->d.ia5);
  1517. size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
  1518. switch(target) {
  1519. case GEN_DNS: /* name/pattern comparison */
  1520. /* The OpenSSL man page explicitly says: "In general it cannot be
  1521. assumed that the data returned by ASN1_STRING_data() is null
  1522. terminated or does not contain embedded nulls." But also that
  1523. "The actual format of the data will depend on the actual string
  1524. type itself: for example for an IA5String the data will be ASCII"
  1525. It has been however verified that in 0.9.6 and 0.9.7, IA5String
  1526. is always null-terminated.
  1527. */
  1528. if((altlen == strlen(altptr)) &&
  1529. /* if this isn't true, there was an embedded zero in the name
  1530. string and we cannot match it. */
  1531. subj_alt_hostcheck(data, altptr, hostname, dispname)) {
  1532. dnsmatched = TRUE;
  1533. }
  1534. break;
  1535. case GEN_IPADD: /* IP address comparison */
  1536. /* compare alternative IP address if the data chunk is the same size
  1537. our server IP address is */
  1538. if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
  1539. ipmatched = TRUE;
  1540. infof(data,
  1541. " subjectAltName: host \"%s\" matched cert's IP address!\n",
  1542. dispname);
  1543. }
  1544. break;
  1545. }
  1546. }
  1547. }
  1548. GENERAL_NAMES_free(altnames);
  1549. if(dnsmatched || ipmatched)
  1550. matched = TRUE;
  1551. }
  1552. if(matched)
  1553. /* an alternative name matched */
  1554. ;
  1555. else if(dNSName || iPAddress) {
  1556. infof(data, " subjectAltName does not match %s\n", dispname);
  1557. failf(data, "SSL: no alternative certificate subject name matches "
  1558. "target host name '%s'", dispname);
  1559. result = CURLE_PEER_FAILED_VERIFICATION;
  1560. }
  1561. else {
  1562. /* we have to look to the last occurrence of a commonName in the
  1563. distinguished one to get the most significant one. */
  1564. int j, i = -1;
  1565. /* The following is done because of a bug in 0.9.6b */
  1566. unsigned char *nulstr = (unsigned char *)"";
  1567. unsigned char *peer_CN = nulstr;
  1568. X509_NAME *name = X509_get_subject_name(server_cert);
  1569. if(name)
  1570. while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0)
  1571. i = j;
  1572. /* we have the name entry and we will now convert this to a string
  1573. that we can use for comparison. Doing this we support BMPstring,
  1574. UTF8 etc. */
  1575. if(i >= 0) {
  1576. ASN1_STRING *tmp =
  1577. X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
  1578. /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
  1579. is already UTF-8 encoded. We check for this case and copy the raw
  1580. string manually to avoid the problem. This code can be made
  1581. conditional in the future when OpenSSL has been fixed. */
  1582. if(tmp) {
  1583. if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
  1584. j = ASN1_STRING_length(tmp);
  1585. if(j >= 0) {
  1586. peer_CN = OPENSSL_malloc(j + 1);
  1587. if(peer_CN) {
  1588. memcpy(peer_CN, ASN1_STRING_get0_data(tmp), j);
  1589. peer_CN[j] = '\0';
  1590. }
  1591. }
  1592. }
  1593. else /* not a UTF8 name */
  1594. j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
  1595. if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != j)) {
  1596. /* there was a terminating zero before the end of string, this
  1597. cannot match and we return failure! */
  1598. failf(data, "SSL: illegal cert name field");
  1599. result = CURLE_PEER_FAILED_VERIFICATION;
  1600. }
  1601. }
  1602. }
  1603. if(peer_CN == nulstr)
  1604. peer_CN = NULL;
  1605. else {
  1606. /* convert peer_CN from UTF8 */
  1607. CURLcode rc = Curl_convert_from_utf8(data, (char *)peer_CN,
  1608. strlen((char *)peer_CN));
  1609. /* Curl_convert_from_utf8 calls failf if unsuccessful */
  1610. if(rc) {
  1611. OPENSSL_free(peer_CN);
  1612. return rc;
  1613. }
  1614. }
  1615. if(result)
  1616. /* error already detected, pass through */
  1617. ;
  1618. else if(!peer_CN) {
  1619. failf(data,
  1620. "SSL: unable to obtain common name from peer certificate");
  1621. result = CURLE_PEER_FAILED_VERIFICATION;
  1622. }
  1623. else if(!Curl_cert_hostcheck((const char *)peer_CN, hostname)) {
  1624. failf(data, "SSL: certificate subject name '%s' does not match "
  1625. "target host name '%s'", peer_CN, dispname);
  1626. result = CURLE_PEER_FAILED_VERIFICATION;
  1627. }
  1628. else {
  1629. infof(data, " common name: %s (matched)\n", peer_CN);
  1630. }
  1631. if(peer_CN)
  1632. OPENSSL_free(peer_CN);
  1633. }
  1634. return result;
  1635. }
  1636. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
  1637. !defined(OPENSSL_NO_OCSP)
  1638. static CURLcode verifystatus(struct Curl_easy *data,
  1639. struct ssl_connect_data *connssl)
  1640. {
  1641. int i, ocsp_status;
  1642. unsigned char *status;
  1643. const unsigned char *p;
  1644. CURLcode result = CURLE_OK;
  1645. OCSP_RESPONSE *rsp = NULL;
  1646. OCSP_BASICRESP *br = NULL;
  1647. X509_STORE *st = NULL;
  1648. STACK_OF(X509) *ch = NULL;
  1649. struct ssl_backend_data *backend = connssl->backend;
  1650. X509 *cert;
  1651. OCSP_CERTID *id = NULL;
  1652. int cert_status, crl_reason;
  1653. ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
  1654. int ret;
  1655. long len = SSL_get_tlsext_status_ocsp_resp(backend->handle, &status);
  1656. if(!status) {
  1657. failf(data, "No OCSP response received");
  1658. result = CURLE_SSL_INVALIDCERTSTATUS;
  1659. goto end;
  1660. }
  1661. p = status;
  1662. rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
  1663. if(!rsp) {
  1664. failf(data, "Invalid OCSP response");
  1665. result = CURLE_SSL_INVALIDCERTSTATUS;
  1666. goto end;
  1667. }
  1668. ocsp_status = OCSP_response_status(rsp);
  1669. if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
  1670. failf(data, "Invalid OCSP response status: %s (%d)",
  1671. OCSP_response_status_str(ocsp_status), ocsp_status);
  1672. result = CURLE_SSL_INVALIDCERTSTATUS;
  1673. goto end;
  1674. }
  1675. br = OCSP_response_get1_basic(rsp);
  1676. if(!br) {
  1677. failf(data, "Invalid OCSP response");
  1678. result = CURLE_SSL_INVALIDCERTSTATUS;
  1679. goto end;
  1680. }
  1681. ch = SSL_get_peer_cert_chain(backend->handle);
  1682. st = SSL_CTX_get_cert_store(backend->ctx);
  1683. #if ((OPENSSL_VERSION_NUMBER <= 0x1000201fL) /* Fixed after 1.0.2a */ || \
  1684. (defined(LIBRESSL_VERSION_NUMBER) && \
  1685. LIBRESSL_VERSION_NUMBER <= 0x2040200fL))
  1686. /* The authorized responder cert in the OCSP response MUST be signed by the
  1687. peer cert's issuer (see RFC6960 section 4.2.2.2). If that's a root cert,
  1688. no problem, but if it's an intermediate cert OpenSSL has a bug where it
  1689. expects this issuer to be present in the chain embedded in the OCSP
  1690. response. So we add it if necessary. */
  1691. /* First make sure the peer cert chain includes both a peer and an issuer,
  1692. and the OCSP response contains a responder cert. */
  1693. if(sk_X509_num(ch) >= 2 && sk_X509_num(br->certs) >= 1) {
  1694. X509 *responder = sk_X509_value(br->certs, sk_X509_num(br->certs) - 1);
  1695. /* Find issuer of responder cert and add it to the OCSP response chain */
  1696. for(i = 0; i < sk_X509_num(ch); i++) {
  1697. X509 *issuer = sk_X509_value(ch, i);
  1698. if(X509_check_issued(issuer, responder) == X509_V_OK) {
  1699. if(!OCSP_basic_add1_cert(br, issuer)) {
  1700. failf(data, "Could not add issuer cert to OCSP response");
  1701. result = CURLE_SSL_INVALIDCERTSTATUS;
  1702. goto end;
  1703. }
  1704. }
  1705. }
  1706. }
  1707. #endif
  1708. if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
  1709. failf(data, "OCSP response verification failed");
  1710. result = CURLE_SSL_INVALIDCERTSTATUS;
  1711. goto end;
  1712. }
  1713. /* Compute the certificate's ID */
  1714. cert = SSL_get_peer_certificate(backend->handle);
  1715. if(!cert) {
  1716. failf(data, "Error getting peer certificate");
  1717. result = CURLE_SSL_INVALIDCERTSTATUS;
  1718. goto end;
  1719. }
  1720. for(i = 0; i < sk_X509_num(ch); i++) {
  1721. X509 *issuer = sk_X509_value(ch, i);
  1722. if(X509_check_issued(issuer, cert) == X509_V_OK) {
  1723. id = OCSP_cert_to_id(EVP_sha1(), cert, issuer);
  1724. break;
  1725. }
  1726. }
  1727. X509_free(cert);
  1728. if(!id) {
  1729. failf(data, "Error computing OCSP ID");
  1730. result = CURLE_SSL_INVALIDCERTSTATUS;
  1731. goto end;
  1732. }
  1733. /* Find the single OCSP response corresponding to the certificate ID */
  1734. ret = OCSP_resp_find_status(br, id, &cert_status, &crl_reason, &rev,
  1735. &thisupd, &nextupd);
  1736. OCSP_CERTID_free(id);
  1737. if(ret != 1) {
  1738. failf(data, "Could not find certificate ID in OCSP response");
  1739. result = CURLE_SSL_INVALIDCERTSTATUS;
  1740. goto end;
  1741. }
  1742. /* Validate the corresponding single OCSP response */
  1743. if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
  1744. failf(data, "OCSP response has expired");
  1745. result = CURLE_SSL_INVALIDCERTSTATUS;
  1746. goto end;
  1747. }
  1748. infof(data, "SSL certificate status: %s (%d)\n",
  1749. OCSP_cert_status_str(cert_status), cert_status);
  1750. switch(cert_status) {
  1751. case V_OCSP_CERTSTATUS_GOOD:
  1752. break;
  1753. case V_OCSP_CERTSTATUS_REVOKED:
  1754. result = CURLE_SSL_INVALIDCERTSTATUS;
  1755. failf(data, "SSL certificate revocation reason: %s (%d)",
  1756. OCSP_crl_reason_str(crl_reason), crl_reason);
  1757. goto end;
  1758. case V_OCSP_CERTSTATUS_UNKNOWN:
  1759. default:
  1760. result = CURLE_SSL_INVALIDCERTSTATUS;
  1761. goto end;
  1762. }
  1763. end:
  1764. if(br)
  1765. OCSP_BASICRESP_free(br);
  1766. OCSP_RESPONSE_free(rsp);
  1767. return result;
  1768. }
  1769. #endif
  1770. #endif /* USE_OPENSSL */
  1771. /* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
  1772. and thus this cannot be done there. */
  1773. #ifdef SSL_CTRL_SET_MSG_CALLBACK
  1774. static const char *ssl_msg_type(int ssl_ver, int msg)
  1775. {
  1776. #ifdef SSL2_VERSION_MAJOR
  1777. if(ssl_ver == SSL2_VERSION_MAJOR) {
  1778. switch(msg) {
  1779. case SSL2_MT_ERROR:
  1780. return "Error";
  1781. case SSL2_MT_CLIENT_HELLO:
  1782. return "Client hello";
  1783. case SSL2_MT_CLIENT_MASTER_KEY:
  1784. return "Client key";
  1785. case SSL2_MT_CLIENT_FINISHED:
  1786. return "Client finished";
  1787. case SSL2_MT_SERVER_HELLO:
  1788. return "Server hello";
  1789. case SSL2_MT_SERVER_VERIFY:
  1790. return "Server verify";
  1791. case SSL2_MT_SERVER_FINISHED:
  1792. return "Server finished";
  1793. case SSL2_MT_REQUEST_CERTIFICATE:
  1794. return "Request CERT";
  1795. case SSL2_MT_CLIENT_CERTIFICATE:
  1796. return "Client CERT";
  1797. }
  1798. }
  1799. else
  1800. #endif
  1801. if(ssl_ver == SSL3_VERSION_MAJOR) {
  1802. switch(msg) {
  1803. case SSL3_MT_HELLO_REQUEST:
  1804. return "Hello request";
  1805. case SSL3_MT_CLIENT_HELLO:
  1806. return "Client hello";
  1807. case SSL3_MT_SERVER_HELLO:
  1808. return "Server hello";
  1809. #ifdef SSL3_MT_NEWSESSION_TICKET
  1810. case SSL3_MT_NEWSESSION_TICKET:
  1811. return "Newsession Ticket";
  1812. #endif
  1813. case SSL3_MT_CERTIFICATE:
  1814. return "Certificate";
  1815. case SSL3_MT_SERVER_KEY_EXCHANGE:
  1816. return "Server key exchange";
  1817. case SSL3_MT_CLIENT_KEY_EXCHANGE:
  1818. return "Client key exchange";
  1819. case SSL3_MT_CERTIFICATE_REQUEST:
  1820. return "Request CERT";
  1821. case SSL3_MT_SERVER_DONE:
  1822. return "Server finished";
  1823. case SSL3_MT_CERTIFICATE_VERIFY:
  1824. return "CERT verify";
  1825. case SSL3_MT_FINISHED:
  1826. return "Finished";
  1827. #ifdef SSL3_MT_CERTIFICATE_STATUS
  1828. case SSL3_MT_CERTIFICATE_STATUS:
  1829. return "Certificate Status";
  1830. #endif
  1831. #ifdef SSL3_MT_ENCRYPTED_EXTENSIONS
  1832. case SSL3_MT_ENCRYPTED_EXTENSIONS:
  1833. return "Encrypted Extensions";
  1834. #endif
  1835. #ifdef SSL3_MT_END_OF_EARLY_DATA
  1836. case SSL3_MT_END_OF_EARLY_DATA:
  1837. return "End of early data";
  1838. #endif
  1839. #ifdef SSL3_MT_KEY_UPDATE
  1840. case SSL3_MT_KEY_UPDATE:
  1841. return "Key update";
  1842. #endif
  1843. #ifdef SSL3_MT_NEXT_PROTO
  1844. case SSL3_MT_NEXT_PROTO:
  1845. return "Next protocol";
  1846. #endif
  1847. #ifdef SSL3_MT_MESSAGE_HASH
  1848. case SSL3_MT_MESSAGE_HASH:
  1849. return "Message hash";
  1850. #endif
  1851. }
  1852. }
  1853. return "Unknown";
  1854. }
  1855. static const char *tls_rt_type(int type)
  1856. {
  1857. switch(type) {
  1858. #ifdef SSL3_RT_HEADER
  1859. case SSL3_RT_HEADER:
  1860. return "TLS header";
  1861. #endif
  1862. case SSL3_RT_CHANGE_CIPHER_SPEC:
  1863. return "TLS change cipher";
  1864. case SSL3_RT_ALERT:
  1865. return "TLS alert";
  1866. case SSL3_RT_HANDSHAKE:
  1867. return "TLS handshake";
  1868. case SSL3_RT_APPLICATION_DATA:
  1869. return "TLS app data";
  1870. default:
  1871. return "TLS Unknown";
  1872. }
  1873. }
  1874. /*
  1875. * Our callback from the SSL/TLS layers.
  1876. */
  1877. static void ossl_trace(int direction, int ssl_ver, int content_type,
  1878. const void *buf, size_t len, SSL *ssl,
  1879. void *userp)
  1880. {
  1881. char unknown[32];
  1882. const char *verstr = NULL;
  1883. struct connectdata *conn = userp;
  1884. struct ssl_connect_data *connssl = &conn->ssl[0];
  1885. struct ssl_backend_data *backend = connssl->backend;
  1886. struct Curl_easy *data = backend->logger;
  1887. if(!conn || !data || !data->set.fdebug ||
  1888. (direction != 0 && direction != 1))
  1889. return;
  1890. switch(ssl_ver) {
  1891. #ifdef SSL2_VERSION /* removed in recent versions */
  1892. case SSL2_VERSION:
  1893. verstr = "SSLv2";
  1894. break;
  1895. #endif
  1896. #ifdef SSL3_VERSION
  1897. case SSL3_VERSION:
  1898. verstr = "SSLv3";
  1899. break;
  1900. #endif
  1901. case TLS1_VERSION:
  1902. verstr = "TLSv1.0";
  1903. break;
  1904. #ifdef TLS1_1_VERSION
  1905. case TLS1_1_VERSION:
  1906. verstr = "TLSv1.1";
  1907. break;
  1908. #endif
  1909. #ifdef TLS1_2_VERSION
  1910. case TLS1_2_VERSION:
  1911. verstr = "TLSv1.2";
  1912. break;
  1913. #endif
  1914. #ifdef TLS1_3_VERSION
  1915. case TLS1_3_VERSION:
  1916. verstr = "TLSv1.3";
  1917. break;
  1918. #endif
  1919. case 0:
  1920. break;
  1921. default:
  1922. msnprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
  1923. verstr = unknown;
  1924. break;
  1925. }
  1926. /* Log progress for interesting records only (like Handshake or Alert), skip
  1927. * all raw record headers (content_type == SSL3_RT_HEADER or ssl_ver == 0).
  1928. * For TLS 1.3, skip notification of the decrypted inner Content Type.
  1929. */
  1930. if(ssl_ver
  1931. #ifdef SSL3_RT_INNER_CONTENT_TYPE
  1932. && content_type != SSL3_RT_INNER_CONTENT_TYPE
  1933. #endif
  1934. ) {
  1935. const char *msg_name, *tls_rt_name;
  1936. char ssl_buf[1024];
  1937. int msg_type, txt_len;
  1938. /* the info given when the version is zero is not that useful for us */
  1939. ssl_ver >>= 8; /* check the upper 8 bits only below */
  1940. /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
  1941. * always pass-up content-type as 0. But the interesting message-type
  1942. * is at 'buf[0]'.
  1943. */
  1944. if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
  1945. tls_rt_name = tls_rt_type(content_type);
  1946. else
  1947. tls_rt_name = "";
  1948. if(content_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  1949. msg_type = *(char *)buf;
  1950. msg_name = "Change cipher spec";
  1951. }
  1952. else if(content_type == SSL3_RT_ALERT) {
  1953. msg_type = (((char *)buf)[0] << 8) + ((char *)buf)[1];
  1954. msg_name = SSL_alert_desc_string_long(msg_type);
  1955. }
  1956. else {
  1957. msg_type = *(char *)buf;
  1958. msg_name = ssl_msg_type(ssl_ver, msg_type);
  1959. }
  1960. txt_len = msnprintf(ssl_buf, sizeof(ssl_buf), "%s (%s), %s, %s (%d):\n",
  1961. verstr, direction?"OUT":"IN",
  1962. tls_rt_name, msg_name, msg_type);
  1963. if(0 <= txt_len && (unsigned)txt_len < sizeof(ssl_buf)) {
  1964. Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len);
  1965. }
  1966. }
  1967. Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
  1968. CURLINFO_SSL_DATA_IN, (char *)buf, len);
  1969. (void) ssl;
  1970. }
  1971. #endif
  1972. #ifdef USE_OPENSSL
  1973. /* ====================================================== */
  1974. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
  1975. # define use_sni(x) sni = (x)
  1976. #else
  1977. # define use_sni(x) Curl_nop_stmt
  1978. #endif
  1979. /* Check for OpenSSL 1.0.2 which has ALPN support. */
  1980. #undef HAS_ALPN
  1981. #if OPENSSL_VERSION_NUMBER >= 0x10002000L \
  1982. && !defined(OPENSSL_NO_TLSEXT)
  1983. # define HAS_ALPN 1
  1984. #endif
  1985. /* Check for OpenSSL 1.0.1 which has NPN support. */
  1986. #undef HAS_NPN
  1987. #if OPENSSL_VERSION_NUMBER >= 0x10001000L \
  1988. && !defined(OPENSSL_NO_TLSEXT) \
  1989. && !defined(OPENSSL_NO_NEXTPROTONEG)
  1990. # define HAS_NPN 1
  1991. #endif
  1992. #ifdef HAS_NPN
  1993. /*
  1994. * in is a list of length prefixed strings. this function has to select
  1995. * the protocol we want to use from the list and write its string into out.
  1996. */
  1997. static int
  1998. select_next_protocol(unsigned char **out, unsigned char *outlen,
  1999. const unsigned char *in, unsigned int inlen,
  2000. const char *key, unsigned int keylen)
  2001. {
  2002. unsigned int i;
  2003. for(i = 0; i + keylen <= inlen; i += in[i] + 1) {
  2004. if(memcmp(&in[i + 1], key, keylen) == 0) {
  2005. *out = (unsigned char *) &in[i + 1];
  2006. *outlen = in[i];
  2007. return 0;
  2008. }
  2009. }
  2010. return -1;
  2011. }
  2012. static int
  2013. select_next_proto_cb(SSL *ssl,
  2014. unsigned char **out, unsigned char *outlen,
  2015. const unsigned char *in, unsigned int inlen,
  2016. void *arg)
  2017. {
  2018. struct Curl_easy *data = (struct Curl_easy *)arg;
  2019. struct connectdata *conn = data->conn;
  2020. (void)ssl;
  2021. #ifdef USE_HTTP2
  2022. if(data->state.httpwant >= CURL_HTTP_VERSION_2 &&
  2023. !select_next_protocol(out, outlen, in, inlen, ALPN_H2, ALPN_H2_LENGTH)) {
  2024. infof(data, "NPN, negotiated HTTP2 (%s)\n", ALPN_H2);
  2025. conn->negnpn = CURL_HTTP_VERSION_2;
  2026. return SSL_TLSEXT_ERR_OK;
  2027. }
  2028. #endif
  2029. if(!select_next_protocol(out, outlen, in, inlen, ALPN_HTTP_1_1,
  2030. ALPN_HTTP_1_1_LENGTH)) {
  2031. infof(data, "NPN, negotiated HTTP1.1\n");
  2032. conn->negnpn = CURL_HTTP_VERSION_1_1;
  2033. return SSL_TLSEXT_ERR_OK;
  2034. }
  2035. infof(data, "NPN, no overlap, use HTTP1.1\n");
  2036. *out = (unsigned char *)ALPN_HTTP_1_1;
  2037. *outlen = ALPN_HTTP_1_1_LENGTH;
  2038. conn->negnpn = CURL_HTTP_VERSION_1_1;
  2039. return SSL_TLSEXT_ERR_OK;
  2040. }
  2041. #endif /* HAS_NPN */
  2042. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* 1.1.0 */
  2043. static CURLcode
  2044. set_ssl_version_min_max(SSL_CTX *ctx, struct connectdata *conn)
  2045. {
  2046. /* first, TLS min version... */
  2047. long curl_ssl_version_min = SSL_CONN_CONFIG(version);
  2048. long curl_ssl_version_max;
  2049. /* convert cURL min SSL version option to OpenSSL constant */
  2050. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  2051. uint16_t ossl_ssl_version_min = 0;
  2052. uint16_t ossl_ssl_version_max = 0;
  2053. #else
  2054. long ossl_ssl_version_min = 0;
  2055. long ossl_ssl_version_max = 0;
  2056. #endif
  2057. switch(curl_ssl_version_min) {
  2058. case CURL_SSLVERSION_TLSv1: /* TLS 1.x */
  2059. case CURL_SSLVERSION_TLSv1_0:
  2060. ossl_ssl_version_min = TLS1_VERSION;
  2061. break;
  2062. case CURL_SSLVERSION_TLSv1_1:
  2063. ossl_ssl_version_min = TLS1_1_VERSION;
  2064. break;
  2065. case CURL_SSLVERSION_TLSv1_2:
  2066. ossl_ssl_version_min = TLS1_2_VERSION;
  2067. break;
  2068. #ifdef TLS1_3_VERSION
  2069. case CURL_SSLVERSION_TLSv1_3:
  2070. ossl_ssl_version_min = TLS1_3_VERSION;
  2071. break;
  2072. #endif
  2073. }
  2074. /* CURL_SSLVERSION_DEFAULT means that no option was selected.
  2075. We don't want to pass 0 to SSL_CTX_set_min_proto_version as
  2076. it would enable all versions down to the lowest supported by
  2077. the library.
  2078. So we skip this, and stay with the OS default
  2079. */
  2080. if(curl_ssl_version_min != CURL_SSLVERSION_DEFAULT) {
  2081. if(!SSL_CTX_set_min_proto_version(ctx, ossl_ssl_version_min)) {
  2082. return CURLE_SSL_CONNECT_ERROR;
  2083. }
  2084. }
  2085. /* ... then, TLS max version */
  2086. curl_ssl_version_max = SSL_CONN_CONFIG(version_max);
  2087. /* convert cURL max SSL version option to OpenSSL constant */
  2088. switch(curl_ssl_version_max) {
  2089. case CURL_SSLVERSION_MAX_TLSv1_0:
  2090. ossl_ssl_version_max = TLS1_VERSION;
  2091. break;
  2092. case CURL_SSLVERSION_MAX_TLSv1_1:
  2093. ossl_ssl_version_max = TLS1_1_VERSION;
  2094. break;
  2095. case CURL_SSLVERSION_MAX_TLSv1_2:
  2096. ossl_ssl_version_max = TLS1_2_VERSION;
  2097. break;
  2098. #ifdef TLS1_3_VERSION
  2099. case CURL_SSLVERSION_MAX_TLSv1_3:
  2100. ossl_ssl_version_max = TLS1_3_VERSION;
  2101. break;
  2102. #endif
  2103. case CURL_SSLVERSION_MAX_NONE: /* none selected */
  2104. case CURL_SSLVERSION_MAX_DEFAULT: /* max selected */
  2105. default:
  2106. /* SSL_CTX_set_max_proto_version states that:
  2107. setting the maximum to 0 will enable
  2108. protocol versions up to the highest version
  2109. supported by the library */
  2110. ossl_ssl_version_max = 0;
  2111. break;
  2112. }
  2113. if(!SSL_CTX_set_max_proto_version(ctx, ossl_ssl_version_max)) {
  2114. return CURLE_SSL_CONNECT_ERROR;
  2115. }
  2116. return CURLE_OK;
  2117. }
  2118. #endif
  2119. #ifdef OPENSSL_IS_BORINGSSL
  2120. typedef uint32_t ctx_option_t;
  2121. #else
  2122. typedef long ctx_option_t;
  2123. #endif
  2124. #if (OPENSSL_VERSION_NUMBER < 0x10100000L) /* 1.1.0 */
  2125. static CURLcode
  2126. set_ssl_version_min_max_legacy(ctx_option_t *ctx_options,
  2127. struct Curl_easy *data,
  2128. struct connectdata *conn, int sockindex)
  2129. {
  2130. long ssl_version = SSL_CONN_CONFIG(version);
  2131. long ssl_version_max = SSL_CONN_CONFIG(version_max);
  2132. (void) data; /* In case it's unused. */
  2133. switch(ssl_version) {
  2134. case CURL_SSLVERSION_TLSv1_3:
  2135. #ifdef TLS1_3_VERSION
  2136. {
  2137. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  2138. SSL_CTX_set_max_proto_version(backend->ctx, TLS1_3_VERSION);
  2139. *ctx_options |= SSL_OP_NO_TLSv1_2;
  2140. }
  2141. #else
  2142. (void)sockindex;
  2143. (void)ctx_options;
  2144. failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
  2145. return CURLE_NOT_BUILT_IN;
  2146. #endif
  2147. /* FALLTHROUGH */
  2148. case CURL_SSLVERSION_TLSv1_2:
  2149. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  2150. *ctx_options |= SSL_OP_NO_TLSv1_1;
  2151. #else
  2152. failf(data, OSSL_PACKAGE " was built without TLS 1.2 support");
  2153. return CURLE_NOT_BUILT_IN;
  2154. #endif
  2155. /* FALLTHROUGH */
  2156. case CURL_SSLVERSION_TLSv1_1:
  2157. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  2158. *ctx_options |= SSL_OP_NO_TLSv1;
  2159. #else
  2160. failf(data, OSSL_PACKAGE " was built without TLS 1.1 support");
  2161. return CURLE_NOT_BUILT_IN;
  2162. #endif
  2163. /* FALLTHROUGH */
  2164. case CURL_SSLVERSION_TLSv1_0:
  2165. case CURL_SSLVERSION_TLSv1:
  2166. break;
  2167. }
  2168. switch(ssl_version_max) {
  2169. case CURL_SSLVERSION_MAX_TLSv1_0:
  2170. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  2171. *ctx_options |= SSL_OP_NO_TLSv1_1;
  2172. #endif
  2173. /* FALLTHROUGH */
  2174. case CURL_SSLVERSION_MAX_TLSv1_1:
  2175. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  2176. *ctx_options |= SSL_OP_NO_TLSv1_2;
  2177. #endif
  2178. /* FALLTHROUGH */
  2179. case CURL_SSLVERSION_MAX_TLSv1_2:
  2180. #ifdef TLS1_3_VERSION
  2181. *ctx_options |= SSL_OP_NO_TLSv1_3;
  2182. #endif
  2183. break;
  2184. case CURL_SSLVERSION_MAX_TLSv1_3:
  2185. #ifdef TLS1_3_VERSION
  2186. break;
  2187. #else
  2188. failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
  2189. return CURLE_NOT_BUILT_IN;
  2190. #endif
  2191. }
  2192. return CURLE_OK;
  2193. }
  2194. #endif
  2195. /* The "new session" callback must return zero if the session can be removed
  2196. * or non-zero if the session has been put into the session cache.
  2197. */
  2198. static int ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid)
  2199. {
  2200. int res = 0;
  2201. struct connectdata *conn;
  2202. struct Curl_easy *data;
  2203. int sockindex;
  2204. curl_socket_t *sockindex_ptr;
  2205. int data_idx = ossl_get_ssl_data_index();
  2206. int connectdata_idx = ossl_get_ssl_conn_index();
  2207. int sockindex_idx = ossl_get_ssl_sockindex_index();
  2208. int proxy_idx = ossl_get_proxy_index();
  2209. bool isproxy;
  2210. if(data_idx < 0 || connectdata_idx < 0 || sockindex_idx < 0 || proxy_idx < 0)
  2211. return 0;
  2212. conn = (struct connectdata*) SSL_get_ex_data(ssl, connectdata_idx);
  2213. if(!conn)
  2214. return 0;
  2215. data = (struct Curl_easy *) SSL_get_ex_data(ssl, data_idx);
  2216. /* The sockindex has been stored as a pointer to an array element */
  2217. sockindex_ptr = (curl_socket_t*) SSL_get_ex_data(ssl, sockindex_idx);
  2218. sockindex = (int)(sockindex_ptr - conn->sock);
  2219. isproxy = SSL_get_ex_data(ssl, proxy_idx) ? TRUE : FALSE;
  2220. if(SSL_SET_OPTION(primary.sessionid)) {
  2221. bool incache;
  2222. void *old_ssl_sessionid = NULL;
  2223. Curl_ssl_sessionid_lock(data);
  2224. if(isproxy)
  2225. incache = FALSE;
  2226. else
  2227. incache = !(Curl_ssl_getsessionid(data, conn, isproxy,
  2228. &old_ssl_sessionid, NULL, sockindex));
  2229. if(incache) {
  2230. if(old_ssl_sessionid != ssl_sessionid) {
  2231. infof(data, "old SSL session ID is stale, removing\n");
  2232. Curl_ssl_delsessionid(data, old_ssl_sessionid);
  2233. incache = FALSE;
  2234. }
  2235. }
  2236. if(!incache) {
  2237. if(!Curl_ssl_addsessionid(data, conn, isproxy, ssl_sessionid,
  2238. 0 /* unknown size */, sockindex)) {
  2239. /* the session has been put into the session cache */
  2240. res = 1;
  2241. }
  2242. else
  2243. failf(data, "failed to store ssl session");
  2244. }
  2245. Curl_ssl_sessionid_unlock(data);
  2246. }
  2247. return res;
  2248. }
  2249. static CURLcode load_cacert_from_memory(SSL_CTX *ctx,
  2250. const struct curl_blob *ca_info_blob)
  2251. {
  2252. /* these need freed at the end */
  2253. BIO *cbio = NULL;
  2254. STACK_OF(X509_INFO) *inf = NULL;
  2255. /* everything else is just a reference */
  2256. int i, count = 0;
  2257. X509_STORE *cts = NULL;
  2258. X509_INFO *itmp = NULL;
  2259. if(ca_info_blob->len > (size_t)INT_MAX)
  2260. return CURLE_SSL_CACERT_BADFILE;
  2261. cts = SSL_CTX_get_cert_store(ctx);
  2262. if(!cts)
  2263. return CURLE_OUT_OF_MEMORY;
  2264. cbio = BIO_new_mem_buf(ca_info_blob->data, (int)ca_info_blob->len);
  2265. if(!cbio)
  2266. return CURLE_OUT_OF_MEMORY;
  2267. inf = PEM_X509_INFO_read_bio(cbio, NULL, NULL, NULL);
  2268. if(!inf) {
  2269. BIO_free(cbio);
  2270. return CURLE_SSL_CACERT_BADFILE;
  2271. }
  2272. /* add each entry from PEM file to x509_store */
  2273. for(i = 0; i < (int)sk_X509_INFO_num(inf); ++i) {
  2274. itmp = sk_X509_INFO_value(inf, i);
  2275. if(itmp->x509) {
  2276. if(X509_STORE_add_cert(cts, itmp->x509)) {
  2277. ++count;
  2278. }
  2279. else {
  2280. /* set count to 0 to return an error */
  2281. count = 0;
  2282. break;
  2283. }
  2284. }
  2285. if(itmp->crl) {
  2286. if(X509_STORE_add_crl(cts, itmp->crl)) {
  2287. ++count;
  2288. }
  2289. else {
  2290. /* set count to 0 to return an error */
  2291. count = 0;
  2292. break;
  2293. }
  2294. }
  2295. }
  2296. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  2297. BIO_free(cbio);
  2298. /* if we didn't end up importing anything, treat that as an error */
  2299. return (count > 0 ? CURLE_OK : CURLE_SSL_CACERT_BADFILE);
  2300. }
  2301. static CURLcode ossl_connect_step1(struct Curl_easy *data,
  2302. struct connectdata *conn, int sockindex)
  2303. {
  2304. CURLcode result = CURLE_OK;
  2305. char *ciphers;
  2306. SSL_METHOD_QUAL SSL_METHOD *req_method = NULL;
  2307. X509_LOOKUP *lookup = NULL;
  2308. curl_socket_t sockfd = conn->sock[sockindex];
  2309. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  2310. ctx_option_t ctx_options = 0;
  2311. void *ssl_sessionid = NULL;
  2312. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
  2313. bool sni;
  2314. const char * const hostname = SSL_HOST_NAME();
  2315. #ifdef ENABLE_IPV6
  2316. struct in6_addr addr;
  2317. #else
  2318. struct in_addr addr;
  2319. #endif
  2320. #endif
  2321. const long int ssl_version = SSL_CONN_CONFIG(version);
  2322. #ifdef USE_OPENSSL_SRP
  2323. const enum CURL_TLSAUTH ssl_authtype = SSL_SET_OPTION(authtype);
  2324. #endif
  2325. char * const ssl_cert = SSL_SET_OPTION(primary.clientcert);
  2326. const struct curl_blob *ssl_cert_blob = SSL_SET_OPTION(primary.cert_blob);
  2327. const struct curl_blob *ca_info_blob = SSL_CONN_CONFIG(ca_info_blob);
  2328. const char * const ssl_cert_type = SSL_SET_OPTION(cert_type);
  2329. const char * const ssl_cafile =
  2330. /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
  2331. (ca_info_blob ? NULL : SSL_CONN_CONFIG(CAfile));
  2332. const char * const ssl_capath = SSL_CONN_CONFIG(CApath);
  2333. const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
  2334. const char * const ssl_crlfile = SSL_SET_OPTION(CRLfile);
  2335. char error_buffer[256];
  2336. struct ssl_backend_data *backend = connssl->backend;
  2337. bool imported_native_ca = false;
  2338. DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
  2339. /* Make funny stuff to get random input */
  2340. result = ossl_seed(data);
  2341. if(result)
  2342. return result;
  2343. SSL_SET_OPTION_LVALUE(certverifyresult) = !X509_V_OK;
  2344. /* check to see if we've been told to use an explicit SSL/TLS version */
  2345. switch(ssl_version) {
  2346. case CURL_SSLVERSION_DEFAULT:
  2347. case CURL_SSLVERSION_TLSv1:
  2348. case CURL_SSLVERSION_TLSv1_0:
  2349. case CURL_SSLVERSION_TLSv1_1:
  2350. case CURL_SSLVERSION_TLSv1_2:
  2351. case CURL_SSLVERSION_TLSv1_3:
  2352. /* it will be handled later with the context options */
  2353. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  2354. req_method = TLS_client_method();
  2355. #else
  2356. req_method = SSLv23_client_method();
  2357. #endif
  2358. use_sni(TRUE);
  2359. break;
  2360. case CURL_SSLVERSION_SSLv2:
  2361. failf(data, "No SSLv2 support");
  2362. return CURLE_NOT_BUILT_IN;
  2363. case CURL_SSLVERSION_SSLv3:
  2364. failf(data, "No SSLv3 support");
  2365. return CURLE_NOT_BUILT_IN;
  2366. default:
  2367. failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
  2368. return CURLE_SSL_CONNECT_ERROR;
  2369. }
  2370. if(backend->ctx)
  2371. SSL_CTX_free(backend->ctx);
  2372. backend->ctx = SSL_CTX_new(req_method);
  2373. if(!backend->ctx) {
  2374. failf(data, "SSL: couldn't create a context: %s",
  2375. ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer)));
  2376. return CURLE_OUT_OF_MEMORY;
  2377. }
  2378. #ifdef SSL_MODE_RELEASE_BUFFERS
  2379. SSL_CTX_set_mode(backend->ctx, SSL_MODE_RELEASE_BUFFERS);
  2380. #endif
  2381. #ifdef SSL_CTRL_SET_MSG_CALLBACK
  2382. if(data->set.fdebug && data->set.verbose) {
  2383. /* the SSL trace callback is only used for verbose logging */
  2384. SSL_CTX_set_msg_callback(backend->ctx, ossl_trace);
  2385. SSL_CTX_set_msg_callback_arg(backend->ctx, conn);
  2386. set_logger(conn, data);
  2387. }
  2388. #endif
  2389. /* OpenSSL contains code to work-around lots of bugs and flaws in various
  2390. SSL-implementations. SSL_CTX_set_options() is used to enabled those
  2391. work-arounds. The man page for this option states that SSL_OP_ALL enables
  2392. all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
  2393. enable the bug workaround options if compatibility with somewhat broken
  2394. implementations is desired."
  2395. The "-no_ticket" option was introduced in Openssl0.9.8j. It's a flag to
  2396. disable "rfc4507bis session ticket support". rfc4507bis was later turned
  2397. into the proper RFC5077 it seems: https://tools.ietf.org/html/rfc5077
  2398. The enabled extension concerns the session management. I wonder how often
  2399. libcurl stops a connection and then resumes a TLS session. also, sending
  2400. the session data is some overhead. .I suggest that you just use your
  2401. proposed patch (which explicitly disables TICKET).
  2402. If someone writes an application with libcurl and openssl who wants to
  2403. enable the feature, one can do this in the SSL callback.
  2404. SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
  2405. interoperability with web server Netscape Enterprise Server 2.0.1 which
  2406. was released back in 1996.
  2407. Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
  2408. become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
  2409. CVE-2010-4180 when using previous OpenSSL versions we no longer enable
  2410. this option regardless of OpenSSL version and SSL_OP_ALL definition.
  2411. OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability
  2412. (https://www.openssl.org/~bodo/tls-cbc.txt). In 0.9.6e they added a bit to
  2413. SSL_OP_ALL that _disables_ that work-around despite the fact that
  2414. SSL_OP_ALL is documented to do "rather harmless" workarounds. In order to
  2415. keep the secure work-around, the SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit
  2416. must not be set.
  2417. */
  2418. ctx_options = SSL_OP_ALL;
  2419. #ifdef SSL_OP_NO_TICKET
  2420. ctx_options |= SSL_OP_NO_TICKET;
  2421. #endif
  2422. #ifdef SSL_OP_NO_COMPRESSION
  2423. ctx_options |= SSL_OP_NO_COMPRESSION;
  2424. #endif
  2425. #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
  2426. /* mitigate CVE-2010-4180 */
  2427. ctx_options &= ~SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
  2428. #endif
  2429. #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
  2430. /* unless the user explicitly ask to allow the protocol vulnerability we
  2431. use the work-around */
  2432. if(!SSL_SET_OPTION(enable_beast))
  2433. ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
  2434. #endif
  2435. switch(ssl_version) {
  2436. case CURL_SSLVERSION_SSLv2:
  2437. case CURL_SSLVERSION_SSLv3:
  2438. return CURLE_NOT_BUILT_IN;
  2439. /* "--tlsv<x.y>" options mean TLS >= version <x.y> */
  2440. case CURL_SSLVERSION_DEFAULT:
  2441. case CURL_SSLVERSION_TLSv1: /* TLS >= version 1.0 */
  2442. case CURL_SSLVERSION_TLSv1_0: /* TLS >= version 1.0 */
  2443. case CURL_SSLVERSION_TLSv1_1: /* TLS >= version 1.1 */
  2444. case CURL_SSLVERSION_TLSv1_2: /* TLS >= version 1.2 */
  2445. case CURL_SSLVERSION_TLSv1_3: /* TLS >= version 1.3 */
  2446. /* asking for any TLS version as the minimum, means no SSL versions
  2447. allowed */
  2448. ctx_options |= SSL_OP_NO_SSLv2;
  2449. ctx_options |= SSL_OP_NO_SSLv3;
  2450. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* 1.1.0 */
  2451. result = set_ssl_version_min_max(backend->ctx, conn);
  2452. #else
  2453. result = set_ssl_version_min_max_legacy(&ctx_options, data, conn,
  2454. sockindex);
  2455. #endif
  2456. if(result != CURLE_OK)
  2457. return result;
  2458. break;
  2459. default:
  2460. failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
  2461. return CURLE_SSL_CONNECT_ERROR;
  2462. }
  2463. SSL_CTX_set_options(backend->ctx, ctx_options);
  2464. #ifdef HAS_NPN
  2465. if(conn->bits.tls_enable_npn)
  2466. SSL_CTX_set_next_proto_select_cb(backend->ctx, select_next_proto_cb, data);
  2467. #endif
  2468. #ifdef HAS_ALPN
  2469. if(conn->bits.tls_enable_alpn) {
  2470. int cur = 0;
  2471. unsigned char protocols[128];
  2472. #ifdef USE_HTTP2
  2473. if(data->state.httpwant >= CURL_HTTP_VERSION_2
  2474. #ifndef CURL_DISABLE_PROXY
  2475. && (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)
  2476. #endif
  2477. ) {
  2478. protocols[cur++] = ALPN_H2_LENGTH;
  2479. memcpy(&protocols[cur], ALPN_H2, ALPN_H2_LENGTH);
  2480. cur += ALPN_H2_LENGTH;
  2481. infof(data, "ALPN, offering %s\n", ALPN_H2);
  2482. }
  2483. #endif
  2484. protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
  2485. memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
  2486. cur += ALPN_HTTP_1_1_LENGTH;
  2487. infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
  2488. /* expects length prefixed preference ordered list of protocols in wire
  2489. * format
  2490. */
  2491. if(SSL_CTX_set_alpn_protos(backend->ctx, protocols, cur)) {
  2492. failf(data, "Error setting ALPN");
  2493. return CURLE_SSL_CONNECT_ERROR;
  2494. }
  2495. }
  2496. #endif
  2497. if(ssl_cert || ssl_cert_blob || ssl_cert_type) {
  2498. if(!result &&
  2499. !cert_stuff(data, backend->ctx,
  2500. ssl_cert, ssl_cert_blob, ssl_cert_type,
  2501. SSL_SET_OPTION(key), SSL_SET_OPTION(key_blob),
  2502. SSL_SET_OPTION(key_type), SSL_SET_OPTION(key_passwd)))
  2503. result = CURLE_SSL_CERTPROBLEM;
  2504. if(result)
  2505. /* failf() is already done in cert_stuff() */
  2506. return result;
  2507. }
  2508. ciphers = SSL_CONN_CONFIG(cipher_list);
  2509. if(!ciphers)
  2510. ciphers = (char *)DEFAULT_CIPHER_SELECTION;
  2511. if(ciphers) {
  2512. if(!SSL_CTX_set_cipher_list(backend->ctx, ciphers)) {
  2513. failf(data, "failed setting cipher list: %s", ciphers);
  2514. return CURLE_SSL_CIPHER;
  2515. }
  2516. infof(data, "Cipher selection: %s\n", ciphers);
  2517. }
  2518. #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
  2519. {
  2520. char *ciphers13 = SSL_CONN_CONFIG(cipher_list13);
  2521. if(ciphers13) {
  2522. if(!SSL_CTX_set_ciphersuites(backend->ctx, ciphers13)) {
  2523. failf(data, "failed setting TLS 1.3 cipher suite: %s", ciphers13);
  2524. return CURLE_SSL_CIPHER;
  2525. }
  2526. infof(data, "TLS 1.3 cipher selection: %s\n", ciphers13);
  2527. }
  2528. }
  2529. #endif
  2530. #ifdef HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH
  2531. /* OpenSSL 1.1.1 requires clients to opt-in for PHA */
  2532. SSL_CTX_set_post_handshake_auth(backend->ctx, 1);
  2533. #endif
  2534. #ifdef HAVE_SSL_CTX_SET_EC_CURVES
  2535. {
  2536. char *curves = SSL_CONN_CONFIG(curves);
  2537. if(curves) {
  2538. if(!SSL_CTX_set1_curves_list(backend->ctx, curves)) {
  2539. failf(data, "failed setting curves list: '%s'", curves);
  2540. return CURLE_SSL_CIPHER;
  2541. }
  2542. }
  2543. }
  2544. #endif
  2545. #ifdef USE_OPENSSL_SRP
  2546. if(ssl_authtype == CURL_TLSAUTH_SRP) {
  2547. char * const ssl_username = SSL_SET_OPTION(username);
  2548. infof(data, "Using TLS-SRP username: %s\n", ssl_username);
  2549. if(!SSL_CTX_set_srp_username(backend->ctx, ssl_username)) {
  2550. failf(data, "Unable to set SRP user name");
  2551. return CURLE_BAD_FUNCTION_ARGUMENT;
  2552. }
  2553. if(!SSL_CTX_set_srp_password(backend->ctx, SSL_SET_OPTION(password))) {
  2554. failf(data, "failed setting SRP password");
  2555. return CURLE_BAD_FUNCTION_ARGUMENT;
  2556. }
  2557. if(!SSL_CONN_CONFIG(cipher_list)) {
  2558. infof(data, "Setting cipher list SRP\n");
  2559. if(!SSL_CTX_set_cipher_list(backend->ctx, "SRP")) {
  2560. failf(data, "failed setting SRP cipher list");
  2561. return CURLE_SSL_CIPHER;
  2562. }
  2563. }
  2564. }
  2565. #endif
  2566. #if defined(USE_WIN32_CRYPTO)
  2567. /* Import certificates from the Windows root certificate store if requested.
  2568. https://stackoverflow.com/questions/9507184/
  2569. https://github.com/d3x0r/SACK/blob/master/src/netlib/ssl_layer.c#L1037
  2570. https://tools.ietf.org/html/rfc5280 */
  2571. if((SSL_CONN_CONFIG(verifypeer) || SSL_CONN_CONFIG(verifyhost)) &&
  2572. (SSL_SET_OPTION(native_ca_store))) {
  2573. X509_STORE *store = SSL_CTX_get_cert_store(backend->ctx);
  2574. HCERTSTORE hStore = CertOpenSystemStore(0, TEXT("ROOT"));
  2575. if(hStore) {
  2576. PCCERT_CONTEXT pContext = NULL;
  2577. /* The array of enhanced key usage OIDs will vary per certificate and is
  2578. declared outside of the loop so that rather than malloc/free each
  2579. iteration we can grow it with realloc, when necessary. */
  2580. CERT_ENHKEY_USAGE *enhkey_usage = NULL;
  2581. DWORD enhkey_usage_size = 0;
  2582. /* This loop makes a best effort to import all valid certificates from
  2583. the MS root store. If a certificate cannot be imported it is skipped.
  2584. 'result' is used to store only hard-fail conditions (such as out of
  2585. memory) that cause an early break. */
  2586. result = CURLE_OK;
  2587. for(;;) {
  2588. X509 *x509;
  2589. FILETIME now;
  2590. BYTE key_usage[2];
  2591. DWORD req_size;
  2592. const unsigned char *encoded_cert;
  2593. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  2594. char cert_name[256];
  2595. #endif
  2596. pContext = CertEnumCertificatesInStore(hStore, pContext);
  2597. if(!pContext)
  2598. break;
  2599. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  2600. if(!CertGetNameStringA(pContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0,
  2601. NULL, cert_name, sizeof(cert_name))) {
  2602. strcpy(cert_name, "Unknown");
  2603. }
  2604. infof(data, "SSL: Checking cert \"%s\"\n", cert_name);
  2605. #endif
  2606. encoded_cert = (const unsigned char *)pContext->pbCertEncoded;
  2607. if(!encoded_cert)
  2608. continue;
  2609. GetSystemTimeAsFileTime(&now);
  2610. if(CompareFileTime(&pContext->pCertInfo->NotBefore, &now) > 0 ||
  2611. CompareFileTime(&now, &pContext->pCertInfo->NotAfter) > 0)
  2612. continue;
  2613. /* If key usage exists check for signing attribute */
  2614. if(CertGetIntendedKeyUsage(pContext->dwCertEncodingType,
  2615. pContext->pCertInfo,
  2616. key_usage, sizeof(key_usage))) {
  2617. if(!(key_usage[0] & CERT_KEY_CERT_SIGN_KEY_USAGE))
  2618. continue;
  2619. }
  2620. else if(GetLastError())
  2621. continue;
  2622. /* If enhanced key usage exists check for server auth attribute.
  2623. *
  2624. * Note "In a Microsoft environment, a certificate might also have EKU
  2625. * extended properties that specify valid uses for the certificate."
  2626. * The call below checks both, and behavior varies depending on what is
  2627. * found. For more details see CertGetEnhancedKeyUsage doc.
  2628. */
  2629. if(CertGetEnhancedKeyUsage(pContext, 0, NULL, &req_size)) {
  2630. if(req_size && req_size > enhkey_usage_size) {
  2631. void *tmp = realloc(enhkey_usage, req_size);
  2632. if(!tmp) {
  2633. failf(data, "SSL: Out of memory allocating for OID list");
  2634. result = CURLE_OUT_OF_MEMORY;
  2635. break;
  2636. }
  2637. enhkey_usage = (CERT_ENHKEY_USAGE *)tmp;
  2638. enhkey_usage_size = req_size;
  2639. }
  2640. if(CertGetEnhancedKeyUsage(pContext, 0, enhkey_usage, &req_size)) {
  2641. if(!enhkey_usage->cUsageIdentifier) {
  2642. /* "If GetLastError returns CRYPT_E_NOT_FOUND, the certificate is
  2643. good for all uses. If it returns zero, the certificate has no
  2644. valid uses." */
  2645. if((HRESULT)GetLastError() != CRYPT_E_NOT_FOUND)
  2646. continue;
  2647. }
  2648. else {
  2649. DWORD i;
  2650. bool found = false;
  2651. for(i = 0; i < enhkey_usage->cUsageIdentifier; ++i) {
  2652. if(!strcmp("1.3.6.1.5.5.7.3.1" /* OID server auth */,
  2653. enhkey_usage->rgpszUsageIdentifier[i])) {
  2654. found = true;
  2655. break;
  2656. }
  2657. }
  2658. if(!found)
  2659. continue;
  2660. }
  2661. }
  2662. else
  2663. continue;
  2664. }
  2665. else
  2666. continue;
  2667. x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
  2668. if(!x509)
  2669. continue;
  2670. /* Try to import the certificate. This may fail for legitimate reasons
  2671. such as duplicate certificate, which is allowed by MS but not
  2672. OpenSSL. */
  2673. if(X509_STORE_add_cert(store, x509) == 1) {
  2674. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  2675. infof(data, "SSL: Imported cert \"%s\"\n", cert_name);
  2676. #endif
  2677. imported_native_ca = true;
  2678. }
  2679. X509_free(x509);
  2680. }
  2681. free(enhkey_usage);
  2682. CertFreeCertificateContext(pContext);
  2683. CertCloseStore(hStore, 0);
  2684. if(result)
  2685. return result;
  2686. }
  2687. if(imported_native_ca)
  2688. infof(data, "successfully imported windows ca store\n");
  2689. else
  2690. infof(data, "error importing windows ca store, continuing anyway\n");
  2691. }
  2692. #endif
  2693. if(ca_info_blob) {
  2694. result = load_cacert_from_memory(backend->ctx, ca_info_blob);
  2695. if(result) {
  2696. if(result == CURLE_OUT_OF_MEMORY ||
  2697. (verifypeer && !imported_native_ca)) {
  2698. failf(data, "error importing CA certificate blob");
  2699. return result;
  2700. }
  2701. /* Only warning if no certificate verification is required. */
  2702. infof(data, "error importing CA certificate blob, continuing anyway\n");
  2703. }
  2704. }
  2705. #if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3)
  2706. /* OpenSSL 3.0.0 has deprecated SSL_CTX_load_verify_locations */
  2707. {
  2708. if(ssl_cafile) {
  2709. if(!SSL_CTX_load_verify_file(backend->ctx, ssl_cafile)) {
  2710. if(verifypeer && !imported_native_ca) {
  2711. /* Fail if we insist on successfully verifying the server. */
  2712. failf(data, "error setting certificate file: %s", ssl_cafile);
  2713. return CURLE_SSL_CACERT_BADFILE;
  2714. }
  2715. /* Continue with a warning if no certificate verif is required. */
  2716. infof(data, "error setting certificate file, continuing anyway\n");
  2717. }
  2718. infof(data, " CAfile: %s\n", ssl_cafile);
  2719. }
  2720. if(ssl_capath) {
  2721. if(!SSL_CTX_load_verify_dir(backend->ctx, ssl_capath)) {
  2722. if(verifypeer && !imported_native_ca) {
  2723. /* Fail if we insist on successfully verifying the server. */
  2724. failf(data, "error setting certificate path: %s", ssl_capath);
  2725. return CURLE_SSL_CACERT_BADFILE;
  2726. }
  2727. /* Continue with a warning if no certificate verif is required. */
  2728. infof(data, "error setting certificate path, continuing anyway\n");
  2729. }
  2730. infof(data, " CApath: %s\n", ssl_capath);
  2731. }
  2732. }
  2733. #else
  2734. if(ssl_cafile || ssl_capath) {
  2735. /* tell SSL where to find CA certificates that are used to verify
  2736. the servers certificate. */
  2737. if(!SSL_CTX_load_verify_locations(backend->ctx, ssl_cafile, ssl_capath)) {
  2738. if(verifypeer && !imported_native_ca) {
  2739. /* Fail if we insist on successfully verifying the server. */
  2740. failf(data, "error setting certificate verify locations:"
  2741. " CAfile: %s CApath: %s",
  2742. ssl_cafile ? ssl_cafile : "none",
  2743. ssl_capath ? ssl_capath : "none");
  2744. return CURLE_SSL_CACERT_BADFILE;
  2745. }
  2746. /* Just continue with a warning if no strict certificate verification
  2747. is required. */
  2748. infof(data, "error setting certificate verify locations,"
  2749. " continuing anyway:\n");
  2750. }
  2751. else {
  2752. /* Everything is fine. */
  2753. infof(data, "successfully set certificate verify locations:\n");
  2754. }
  2755. infof(data, " CAfile: %s\n", ssl_cafile ? ssl_cafile : "none");
  2756. infof(data, " CApath: %s\n", ssl_capath ? ssl_capath : "none");
  2757. }
  2758. #endif
  2759. #ifdef CURL_CA_FALLBACK
  2760. if(verifypeer &&
  2761. !ca_info_blob && !ssl_cafile && !ssl_capath && !imported_native_ca) {
  2762. /* verifying the peer without any CA certificates won't
  2763. work so use openssl's built in default as fallback */
  2764. SSL_CTX_set_default_verify_paths(backend->ctx);
  2765. }
  2766. #endif
  2767. if(ssl_crlfile) {
  2768. /* tell SSL where to find CRL file that is used to check certificate
  2769. * revocation */
  2770. lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(backend->ctx),
  2771. X509_LOOKUP_file());
  2772. if(!lookup ||
  2773. (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
  2774. failf(data, "error loading CRL file: %s", ssl_crlfile);
  2775. return CURLE_SSL_CRL_BADFILE;
  2776. }
  2777. /* Everything is fine. */
  2778. infof(data, "successfully load CRL file:\n");
  2779. X509_STORE_set_flags(SSL_CTX_get_cert_store(backend->ctx),
  2780. X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
  2781. infof(data, " CRLfile: %s\n", ssl_crlfile);
  2782. }
  2783. if(verifypeer) {
  2784. /* Try building a chain using issuers in the trusted store first to avoid
  2785. problems with server-sent legacy intermediates. Newer versions of
  2786. OpenSSL do alternate chain checking by default but we do not know how to
  2787. determine that in a reliable manner.
  2788. https://rt.openssl.org/Ticket/Display.html?id=3621&user=guest&pass=guest
  2789. */
  2790. #if defined(X509_V_FLAG_TRUSTED_FIRST)
  2791. X509_STORE_set_flags(SSL_CTX_get_cert_store(backend->ctx),
  2792. X509_V_FLAG_TRUSTED_FIRST);
  2793. #endif
  2794. #ifdef X509_V_FLAG_PARTIAL_CHAIN
  2795. if(!SSL_SET_OPTION(no_partialchain) && !ssl_crlfile) {
  2796. /* Have intermediate certificates in the trust store be treated as
  2797. trust-anchors, in the same way as self-signed root CA certificates
  2798. are. This allows users to verify servers using the intermediate cert
  2799. only, instead of needing the whole chain.
  2800. Due to OpenSSL bug https://github.com/openssl/openssl/issues/5081 we
  2801. cannot do partial chains with CRL check.
  2802. */
  2803. X509_STORE_set_flags(SSL_CTX_get_cert_store(backend->ctx),
  2804. X509_V_FLAG_PARTIAL_CHAIN);
  2805. }
  2806. #endif
  2807. }
  2808. /* SSL always tries to verify the peer, this only says whether it should
  2809. * fail to connect if the verification fails, or if it should continue
  2810. * anyway. In the latter case the result of the verification is checked with
  2811. * SSL_get_verify_result() below. */
  2812. SSL_CTX_set_verify(backend->ctx,
  2813. verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
  2814. /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */
  2815. #ifdef HAVE_KEYLOG_CALLBACK
  2816. if(Curl_tls_keylog_enabled()) {
  2817. SSL_CTX_set_keylog_callback(backend->ctx, ossl_keylog_callback);
  2818. }
  2819. #endif
  2820. /* Enable the session cache because it's a prerequisite for the "new session"
  2821. * callback. Use the "external storage" mode to avoid that OpenSSL creates
  2822. * an internal session cache.
  2823. */
  2824. SSL_CTX_set_session_cache_mode(backend->ctx,
  2825. SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL);
  2826. SSL_CTX_sess_set_new_cb(backend->ctx, ossl_new_session_cb);
  2827. /* give application a chance to interfere with SSL set up. */
  2828. if(data->set.ssl.fsslctx) {
  2829. Curl_set_in_callback(data, true);
  2830. result = (*data->set.ssl.fsslctx)(data, backend->ctx,
  2831. data->set.ssl.fsslctxp);
  2832. Curl_set_in_callback(data, false);
  2833. if(result) {
  2834. failf(data, "error signaled by ssl ctx callback");
  2835. return result;
  2836. }
  2837. }
  2838. /* Lets make an SSL structure */
  2839. if(backend->handle)
  2840. SSL_free(backend->handle);
  2841. backend->handle = SSL_new(backend->ctx);
  2842. if(!backend->handle) {
  2843. failf(data, "SSL: couldn't create a context (handle)!");
  2844. return CURLE_OUT_OF_MEMORY;
  2845. }
  2846. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
  2847. !defined(OPENSSL_NO_OCSP)
  2848. if(SSL_CONN_CONFIG(verifystatus))
  2849. SSL_set_tlsext_status_type(backend->handle, TLSEXT_STATUSTYPE_ocsp);
  2850. #endif
  2851. #if defined(OPENSSL_IS_BORINGSSL) && defined(ALLOW_RENEG)
  2852. SSL_set_renegotiate_mode(backend->handle, ssl_renegotiate_freely);
  2853. #endif
  2854. SSL_set_connect_state(backend->handle);
  2855. backend->server_cert = 0x0;
  2856. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
  2857. if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) &&
  2858. #ifdef ENABLE_IPV6
  2859. (0 == Curl_inet_pton(AF_INET6, hostname, &addr)) &&
  2860. #endif
  2861. sni) {
  2862. size_t nlen = strlen(hostname);
  2863. if((long)nlen >= data->set.buffer_size)
  2864. /* this is seriously messed up */
  2865. return CURLE_SSL_CONNECT_ERROR;
  2866. /* RFC 6066 section 3 says the SNI field is case insensitive, but browsers
  2867. send the data lowercase and subsequently there are now numerous servers
  2868. out there that don't work unless the name is lowercased */
  2869. Curl_strntolower(data->state.buffer, hostname, nlen);
  2870. data->state.buffer[nlen] = 0;
  2871. if(!SSL_set_tlsext_host_name(backend->handle, data->state.buffer))
  2872. infof(data, "WARNING: failed to configure server name indication (SNI) "
  2873. "TLS extension\n");
  2874. }
  2875. #endif
  2876. ossl_associate_connection(data, conn, sockindex);
  2877. Curl_ssl_sessionid_lock(data);
  2878. if(!Curl_ssl_getsessionid(data, conn, SSL_IS_PROXY() ? TRUE : FALSE,
  2879. &ssl_sessionid, NULL, sockindex)) {
  2880. /* we got a session id, use it! */
  2881. if(!SSL_set_session(backend->handle, ssl_sessionid)) {
  2882. Curl_ssl_sessionid_unlock(data);
  2883. failf(data, "SSL: SSL_set_session failed: %s",
  2884. ossl_strerror(ERR_get_error(), error_buffer,
  2885. sizeof(error_buffer)));
  2886. return CURLE_SSL_CONNECT_ERROR;
  2887. }
  2888. /* Informational message */
  2889. infof(data, "SSL re-using session ID\n");
  2890. }
  2891. Curl_ssl_sessionid_unlock(data);
  2892. #ifndef CURL_DISABLE_PROXY
  2893. if(conn->proxy_ssl[sockindex].use) {
  2894. BIO *const bio = BIO_new(BIO_f_ssl());
  2895. SSL *handle = conn->proxy_ssl[sockindex].backend->handle;
  2896. DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
  2897. DEBUGASSERT(handle != NULL);
  2898. DEBUGASSERT(bio != NULL);
  2899. BIO_set_ssl(bio, handle, FALSE);
  2900. SSL_set_bio(backend->handle, bio, bio);
  2901. }
  2902. else
  2903. #endif
  2904. if(!SSL_set_fd(backend->handle, (int)sockfd)) {
  2905. /* pass the raw socket into the SSL layers */
  2906. failf(data, "SSL: SSL_set_fd failed: %s",
  2907. ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)));
  2908. return CURLE_SSL_CONNECT_ERROR;
  2909. }
  2910. connssl->connecting_state = ssl_connect_2;
  2911. return CURLE_OK;
  2912. }
  2913. static CURLcode ossl_connect_step2(struct Curl_easy *data,
  2914. struct connectdata *conn, int sockindex)
  2915. {
  2916. int err;
  2917. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  2918. struct ssl_backend_data *backend = connssl->backend;
  2919. DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
  2920. || ssl_connect_2_reading == connssl->connecting_state
  2921. || ssl_connect_2_writing == connssl->connecting_state);
  2922. ERR_clear_error();
  2923. err = SSL_connect(backend->handle);
  2924. #ifndef HAVE_KEYLOG_CALLBACK
  2925. if(Curl_tls_keylog_enabled()) {
  2926. /* If key logging is enabled, wait for the handshake to complete and then
  2927. * proceed with logging secrets (for TLS 1.2 or older).
  2928. */
  2929. ossl_log_tls12_secret(backend->handle, &backend->keylog_done);
  2930. }
  2931. #endif
  2932. /* 1 is fine
  2933. 0 is "not successful but was shut down controlled"
  2934. <0 is "handshake was not successful, because a fatal error occurred" */
  2935. if(1 != err) {
  2936. int detail = SSL_get_error(backend->handle, err);
  2937. if(SSL_ERROR_WANT_READ == detail) {
  2938. connssl->connecting_state = ssl_connect_2_reading;
  2939. return CURLE_OK;
  2940. }
  2941. if(SSL_ERROR_WANT_WRITE == detail) {
  2942. connssl->connecting_state = ssl_connect_2_writing;
  2943. return CURLE_OK;
  2944. }
  2945. #ifdef SSL_ERROR_WANT_ASYNC
  2946. if(SSL_ERROR_WANT_ASYNC == detail) {
  2947. connssl->connecting_state = ssl_connect_2;
  2948. return CURLE_OK;
  2949. }
  2950. #endif
  2951. else {
  2952. /* untreated error */
  2953. unsigned long errdetail;
  2954. char error_buffer[256]="";
  2955. CURLcode result;
  2956. long lerr;
  2957. int lib;
  2958. int reason;
  2959. /* the connection failed, we're not waiting for anything else. */
  2960. connssl->connecting_state = ssl_connect_2;
  2961. /* Get the earliest error code from the thread's error queue and removes
  2962. the entry. */
  2963. errdetail = ERR_get_error();
  2964. /* Extract which lib and reason */
  2965. lib = ERR_GET_LIB(errdetail);
  2966. reason = ERR_GET_REASON(errdetail);
  2967. if((lib == ERR_LIB_SSL) &&
  2968. ((reason == SSL_R_CERTIFICATE_VERIFY_FAILED) ||
  2969. (reason == SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED))) {
  2970. result = CURLE_PEER_FAILED_VERIFICATION;
  2971. lerr = SSL_get_verify_result(backend->handle);
  2972. if(lerr != X509_V_OK) {
  2973. SSL_SET_OPTION_LVALUE(certverifyresult) = lerr;
  2974. msnprintf(error_buffer, sizeof(error_buffer),
  2975. "SSL certificate problem: %s",
  2976. X509_verify_cert_error_string(lerr));
  2977. }
  2978. else
  2979. /* strcpy() is fine here as long as the string fits within
  2980. error_buffer */
  2981. strcpy(error_buffer, "SSL certificate verification failed");
  2982. }
  2983. #if (OPENSSL_VERSION_NUMBER >= 0x10101000L && \
  2984. !defined(LIBRESSL_VERSION_NUMBER) && \
  2985. !defined(OPENSSL_IS_BORINGSSL))
  2986. /* SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED is only available on
  2987. OpenSSL version above v1.1.1, not Libre SSL nor BoringSSL */
  2988. else if((lib == ERR_LIB_SSL) &&
  2989. (reason == SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED)) {
  2990. /* If client certificate is required, communicate the
  2991. error to client */
  2992. result = CURLE_SSL_CLIENTCERT;
  2993. ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
  2994. }
  2995. #endif
  2996. else {
  2997. result = CURLE_SSL_CONNECT_ERROR;
  2998. ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
  2999. }
  3000. /* detail is already set to the SSL error above */
  3001. /* If we e.g. use SSLv2 request-method and the server doesn't like us
  3002. * (RST connection etc.), OpenSSL gives no explanation whatsoever and
  3003. * the SO_ERROR is also lost.
  3004. */
  3005. if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
  3006. const char * const hostname = SSL_HOST_NAME();
  3007. const long int port = SSL_HOST_PORT();
  3008. char extramsg[80]="";
  3009. int sockerr = SOCKERRNO;
  3010. if(sockerr && detail == SSL_ERROR_SYSCALL)
  3011. Curl_strerror(sockerr, extramsg, sizeof(extramsg));
  3012. failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%ld ",
  3013. extramsg[0] ? extramsg : SSL_ERROR_to_str(detail),
  3014. hostname, port);
  3015. return result;
  3016. }
  3017. /* Could be a CERT problem */
  3018. failf(data, "%s", error_buffer);
  3019. return result;
  3020. }
  3021. }
  3022. else {
  3023. /* we have been connected fine, we're not waiting for anything else. */
  3024. connssl->connecting_state = ssl_connect_3;
  3025. /* Informational message */
  3026. infof(data, "SSL connection using %s / %s\n",
  3027. SSL_get_version(backend->handle),
  3028. SSL_get_cipher(backend->handle));
  3029. #ifdef HAS_ALPN
  3030. /* Sets data and len to negotiated protocol, len is 0 if no protocol was
  3031. * negotiated
  3032. */
  3033. if(conn->bits.tls_enable_alpn) {
  3034. const unsigned char *neg_protocol;
  3035. unsigned int len;
  3036. SSL_get0_alpn_selected(backend->handle, &neg_protocol, &len);
  3037. if(len) {
  3038. infof(data, "ALPN, server accepted to use %.*s\n", len, neg_protocol);
  3039. #ifdef USE_HTTP2
  3040. if(len == ALPN_H2_LENGTH &&
  3041. !memcmp(ALPN_H2, neg_protocol, len)) {
  3042. conn->negnpn = CURL_HTTP_VERSION_2;
  3043. }
  3044. else
  3045. #endif
  3046. if(len == ALPN_HTTP_1_1_LENGTH &&
  3047. !memcmp(ALPN_HTTP_1_1, neg_protocol, ALPN_HTTP_1_1_LENGTH)) {
  3048. conn->negnpn = CURL_HTTP_VERSION_1_1;
  3049. }
  3050. }
  3051. else
  3052. infof(data, "ALPN, server did not agree to a protocol\n");
  3053. Curl_multiuse_state(data, conn->negnpn == CURL_HTTP_VERSION_2 ?
  3054. BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE);
  3055. }
  3056. #endif
  3057. return CURLE_OK;
  3058. }
  3059. }
  3060. static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
  3061. {
  3062. int i, ilen;
  3063. ilen = (int)len;
  3064. if(ilen < 0)
  3065. return 1; /* buffer too big */
  3066. i = i2t_ASN1_OBJECT(buf, ilen, a);
  3067. if(i >= ilen)
  3068. return 1; /* buffer too small */
  3069. return 0;
  3070. }
  3071. #define push_certinfo(_label, _num) \
  3072. do { \
  3073. long info_len = BIO_get_mem_data(mem, &ptr); \
  3074. Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \
  3075. if(1 != BIO_reset(mem)) \
  3076. break; \
  3077. } while(0)
  3078. static void pubkey_show(struct Curl_easy *data,
  3079. BIO *mem,
  3080. int num,
  3081. const char *type,
  3082. const char *name,
  3083. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  3084. const
  3085. #endif
  3086. BIGNUM *bn)
  3087. {
  3088. char *ptr;
  3089. char namebuf[32];
  3090. msnprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
  3091. if(bn)
  3092. BN_print(mem, bn);
  3093. push_certinfo(namebuf, num);
  3094. }
  3095. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  3096. #define print_pubkey_BN(_type, _name, _num) \
  3097. pubkey_show(data, mem, _num, #_type, #_name, _name)
  3098. #else
  3099. #define print_pubkey_BN(_type, _name, _num) \
  3100. do { \
  3101. if(_type->_name) { \
  3102. pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \
  3103. } \
  3104. } while(0)
  3105. #endif
  3106. static void X509V3_ext(struct Curl_easy *data,
  3107. int certnum,
  3108. CONST_EXTS STACK_OF(X509_EXTENSION) *exts)
  3109. {
  3110. int i;
  3111. if((int)sk_X509_EXTENSION_num(exts) <= 0)
  3112. /* no extensions, bail out */
  3113. return;
  3114. for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
  3115. ASN1_OBJECT *obj;
  3116. X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
  3117. BUF_MEM *biomem;
  3118. char namebuf[128];
  3119. BIO *bio_out = BIO_new(BIO_s_mem());
  3120. if(!bio_out)
  3121. return;
  3122. obj = X509_EXTENSION_get_object(ext);
  3123. asn1_object_dump(obj, namebuf, sizeof(namebuf));
  3124. if(!X509V3_EXT_print(bio_out, ext, 0, 0))
  3125. ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext));
  3126. BIO_get_mem_ptr(bio_out, &biomem);
  3127. Curl_ssl_push_certinfo_len(data, certnum, namebuf, biomem->data,
  3128. biomem->length);
  3129. BIO_free(bio_out);
  3130. }
  3131. }
  3132. #ifdef OPENSSL_IS_BORINGSSL
  3133. typedef size_t numcert_t;
  3134. #else
  3135. typedef int numcert_t;
  3136. #endif
  3137. #if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3)
  3138. #define OSSL3_CONST const
  3139. #else
  3140. #define OSSL3_CONST
  3141. #endif
  3142. static CURLcode get_cert_chain(struct Curl_easy *data,
  3143. struct ssl_connect_data *connssl)
  3144. {
  3145. CURLcode result;
  3146. STACK_OF(X509) *sk;
  3147. int i;
  3148. numcert_t numcerts;
  3149. BIO *mem;
  3150. struct ssl_backend_data *backend = connssl->backend;
  3151. sk = SSL_get_peer_cert_chain(backend->handle);
  3152. if(!sk) {
  3153. return CURLE_OUT_OF_MEMORY;
  3154. }
  3155. numcerts = sk_X509_num(sk);
  3156. result = Curl_ssl_init_certinfo(data, (int)numcerts);
  3157. if(result) {
  3158. return result;
  3159. }
  3160. mem = BIO_new(BIO_s_mem());
  3161. for(i = 0; i < (int)numcerts; i++) {
  3162. ASN1_INTEGER *num;
  3163. X509 *x = sk_X509_value(sk, i);
  3164. EVP_PKEY *pubkey = NULL;
  3165. int j;
  3166. char *ptr;
  3167. const ASN1_BIT_STRING *psig = NULL;
  3168. X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
  3169. push_certinfo("Subject", i);
  3170. X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
  3171. push_certinfo("Issuer", i);
  3172. BIO_printf(mem, "%lx", X509_get_version(x));
  3173. push_certinfo("Version", i);
  3174. num = X509_get_serialNumber(x);
  3175. if(num->type == V_ASN1_NEG_INTEGER)
  3176. BIO_puts(mem, "-");
  3177. for(j = 0; j < num->length; j++)
  3178. BIO_printf(mem, "%02x", num->data[j]);
  3179. push_certinfo("Serial Number", i);
  3180. #if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS)
  3181. {
  3182. const X509_ALGOR *sigalg = NULL;
  3183. X509_PUBKEY *xpubkey = NULL;
  3184. ASN1_OBJECT *pubkeyoid = NULL;
  3185. X509_get0_signature(&psig, &sigalg, x);
  3186. if(sigalg) {
  3187. i2a_ASN1_OBJECT(mem, sigalg->algorithm);
  3188. push_certinfo("Signature Algorithm", i);
  3189. }
  3190. xpubkey = X509_get_X509_PUBKEY(x);
  3191. if(xpubkey) {
  3192. X509_PUBKEY_get0_param(&pubkeyoid, NULL, NULL, NULL, xpubkey);
  3193. if(pubkeyoid) {
  3194. i2a_ASN1_OBJECT(mem, pubkeyoid);
  3195. push_certinfo("Public Key Algorithm", i);
  3196. }
  3197. }
  3198. X509V3_ext(data, i, X509_get0_extensions(x));
  3199. }
  3200. #else
  3201. {
  3202. /* before OpenSSL 1.0.2 */
  3203. X509_CINF *cinf = x->cert_info;
  3204. i2a_ASN1_OBJECT(mem, cinf->signature->algorithm);
  3205. push_certinfo("Signature Algorithm", i);
  3206. i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm);
  3207. push_certinfo("Public Key Algorithm", i);
  3208. X509V3_ext(data, i, cinf->extensions);
  3209. psig = x->signature;
  3210. }
  3211. #endif
  3212. ASN1_TIME_print(mem, X509_get0_notBefore(x));
  3213. push_certinfo("Start date", i);
  3214. ASN1_TIME_print(mem, X509_get0_notAfter(x));
  3215. push_certinfo("Expire date", i);
  3216. pubkey = X509_get_pubkey(x);
  3217. if(!pubkey)
  3218. infof(data, " Unable to load public key\n");
  3219. else {
  3220. int pktype;
  3221. #ifdef HAVE_OPAQUE_EVP_PKEY
  3222. pktype = EVP_PKEY_id(pubkey);
  3223. #else
  3224. pktype = pubkey->type;
  3225. #endif
  3226. switch(pktype) {
  3227. case EVP_PKEY_RSA:
  3228. {
  3229. OSSL3_CONST RSA *rsa;
  3230. #ifdef HAVE_OPAQUE_EVP_PKEY
  3231. rsa = EVP_PKEY_get0_RSA(pubkey);
  3232. #else
  3233. rsa = pubkey->pkey.rsa;
  3234. #endif
  3235. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  3236. {
  3237. const BIGNUM *n;
  3238. const BIGNUM *e;
  3239. RSA_get0_key(rsa, &n, &e, NULL);
  3240. BIO_printf(mem, "%d", BN_num_bits(n));
  3241. push_certinfo("RSA Public Key", i);
  3242. print_pubkey_BN(rsa, n, i);
  3243. print_pubkey_BN(rsa, e, i);
  3244. }
  3245. #else
  3246. BIO_printf(mem, "%d", BN_num_bits(rsa->n));
  3247. push_certinfo("RSA Public Key", i);
  3248. print_pubkey_BN(rsa, n, i);
  3249. print_pubkey_BN(rsa, e, i);
  3250. #endif
  3251. break;
  3252. }
  3253. case EVP_PKEY_DSA:
  3254. {
  3255. #ifndef OPENSSL_NO_DSA
  3256. OSSL3_CONST DSA *dsa;
  3257. #ifdef HAVE_OPAQUE_EVP_PKEY
  3258. dsa = EVP_PKEY_get0_DSA(pubkey);
  3259. #else
  3260. dsa = pubkey->pkey.dsa;
  3261. #endif
  3262. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  3263. {
  3264. const BIGNUM *p;
  3265. const BIGNUM *q;
  3266. const BIGNUM *g;
  3267. const BIGNUM *pub_key;
  3268. DSA_get0_pqg(dsa, &p, &q, &g);
  3269. DSA_get0_key(dsa, &pub_key, NULL);
  3270. print_pubkey_BN(dsa, p, i);
  3271. print_pubkey_BN(dsa, q, i);
  3272. print_pubkey_BN(dsa, g, i);
  3273. print_pubkey_BN(dsa, pub_key, i);
  3274. }
  3275. #else
  3276. print_pubkey_BN(dsa, p, i);
  3277. print_pubkey_BN(dsa, q, i);
  3278. print_pubkey_BN(dsa, g, i);
  3279. print_pubkey_BN(dsa, pub_key, i);
  3280. #endif
  3281. #endif /* !OPENSSL_NO_DSA */
  3282. break;
  3283. }
  3284. case EVP_PKEY_DH:
  3285. {
  3286. OSSL3_CONST DH *dh;
  3287. #ifdef HAVE_OPAQUE_EVP_PKEY
  3288. dh = EVP_PKEY_get0_DH(pubkey);
  3289. #else
  3290. dh = pubkey->pkey.dh;
  3291. #endif
  3292. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  3293. {
  3294. const BIGNUM *p;
  3295. const BIGNUM *q;
  3296. const BIGNUM *g;
  3297. const BIGNUM *pub_key;
  3298. DH_get0_pqg(dh, &p, &q, &g);
  3299. DH_get0_key(dh, &pub_key, NULL);
  3300. print_pubkey_BN(dh, p, i);
  3301. print_pubkey_BN(dh, q, i);
  3302. print_pubkey_BN(dh, g, i);
  3303. print_pubkey_BN(dh, pub_key, i);
  3304. }
  3305. #else
  3306. print_pubkey_BN(dh, p, i);
  3307. print_pubkey_BN(dh, g, i);
  3308. print_pubkey_BN(dh, pub_key, i);
  3309. #endif
  3310. break;
  3311. }
  3312. }
  3313. EVP_PKEY_free(pubkey);
  3314. }
  3315. if(psig) {
  3316. for(j = 0; j < psig->length; j++)
  3317. BIO_printf(mem, "%02x:", psig->data[j]);
  3318. push_certinfo("Signature", i);
  3319. }
  3320. PEM_write_bio_X509(mem, x);
  3321. push_certinfo("Cert", i);
  3322. }
  3323. BIO_free(mem);
  3324. return CURLE_OK;
  3325. }
  3326. /*
  3327. * Heavily modified from:
  3328. * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
  3329. */
  3330. static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
  3331. const char *pinnedpubkey)
  3332. {
  3333. /* Scratch */
  3334. int len1 = 0, len2 = 0;
  3335. unsigned char *buff1 = NULL, *temp = NULL;
  3336. /* Result is returned to caller */
  3337. CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  3338. /* if a path wasn't specified, don't pin */
  3339. if(!pinnedpubkey)
  3340. return CURLE_OK;
  3341. if(!cert)
  3342. return result;
  3343. do {
  3344. /* Begin Gyrations to get the subjectPublicKeyInfo */
  3345. /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */
  3346. /* https://groups.google.com/group/mailing.openssl.users/browse_thread
  3347. /thread/d61858dae102c6c7 */
  3348. len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
  3349. if(len1 < 1)
  3350. break; /* failed */
  3351. buff1 = temp = malloc(len1);
  3352. if(!buff1)
  3353. break; /* failed */
  3354. /* https://www.openssl.org/docs/crypto/d2i_X509.html */
  3355. len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
  3356. /*
  3357. * These checks are verifying we got back the same values as when we
  3358. * sized the buffer. It's pretty weak since they should always be the
  3359. * same. But it gives us something to test.
  3360. */
  3361. if((len1 != len2) || !temp || ((temp - buff1) != len1))
  3362. break; /* failed */
  3363. /* End Gyrations */
  3364. /* The one good exit point */
  3365. result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
  3366. } while(0);
  3367. if(buff1)
  3368. free(buff1);
  3369. return result;
  3370. }
  3371. /*
  3372. * Get the server cert, verify it and show it etc, only call failf() if the
  3373. * 'strict' argument is TRUE as otherwise all this is for informational
  3374. * purposes only!
  3375. *
  3376. * We check certificates to authenticate the server; otherwise we risk
  3377. * man-in-the-middle attack.
  3378. */
  3379. static CURLcode servercert(struct Curl_easy *data,
  3380. struct connectdata *conn,
  3381. struct ssl_connect_data *connssl,
  3382. bool strict)
  3383. {
  3384. CURLcode result = CURLE_OK;
  3385. int rc;
  3386. long lerr;
  3387. X509 *issuer;
  3388. BIO *fp = NULL;
  3389. char error_buffer[256]="";
  3390. char buffer[2048];
  3391. const char *ptr;
  3392. BIO *mem = BIO_new(BIO_s_mem());
  3393. struct ssl_backend_data *backend = connssl->backend;
  3394. if(data->set.ssl.certinfo)
  3395. /* we've been asked to gather certificate info! */
  3396. (void)get_cert_chain(data, connssl);
  3397. backend->server_cert = SSL_get_peer_certificate(backend->handle);
  3398. if(!backend->server_cert) {
  3399. BIO_free(mem);
  3400. if(!strict)
  3401. return CURLE_OK;
  3402. failf(data, "SSL: couldn't get peer certificate!");
  3403. return CURLE_PEER_FAILED_VERIFICATION;
  3404. }
  3405. infof(data, "%s certificate:\n", SSL_IS_PROXY() ? "Proxy" : "Server");
  3406. rc = x509_name_oneline(X509_get_subject_name(backend->server_cert),
  3407. buffer, sizeof(buffer));
  3408. infof(data, " subject: %s\n", rc?"[NONE]":buffer);
  3409. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  3410. {
  3411. long len;
  3412. ASN1_TIME_print(mem, X509_get0_notBefore(backend->server_cert));
  3413. len = BIO_get_mem_data(mem, (char **) &ptr);
  3414. infof(data, " start date: %.*s\n", len, ptr);
  3415. (void)BIO_reset(mem);
  3416. ASN1_TIME_print(mem, X509_get0_notAfter(backend->server_cert));
  3417. len = BIO_get_mem_data(mem, (char **) &ptr);
  3418. infof(data, " expire date: %.*s\n", len, ptr);
  3419. (void)BIO_reset(mem);
  3420. }
  3421. #endif
  3422. BIO_free(mem);
  3423. if(SSL_CONN_CONFIG(verifyhost)) {
  3424. result = verifyhost(data, conn, backend->server_cert);
  3425. if(result) {
  3426. X509_free(backend->server_cert);
  3427. backend->server_cert = NULL;
  3428. return result;
  3429. }
  3430. }
  3431. rc = x509_name_oneline(X509_get_issuer_name(backend->server_cert),
  3432. buffer, sizeof(buffer));
  3433. if(rc) {
  3434. if(strict)
  3435. failf(data, "SSL: couldn't get X509-issuer name!");
  3436. result = CURLE_PEER_FAILED_VERIFICATION;
  3437. }
  3438. else {
  3439. infof(data, " issuer: %s\n", buffer);
  3440. /* We could do all sorts of certificate verification stuff here before
  3441. deallocating the certificate. */
  3442. /* e.g. match issuer name with provided issuer certificate */
  3443. if(SSL_SET_OPTION(issuercert) || SSL_SET_OPTION(issuercert_blob)) {
  3444. if(SSL_SET_OPTION(issuercert_blob))
  3445. fp = BIO_new_mem_buf(SSL_SET_OPTION(issuercert_blob)->data,
  3446. (int)SSL_SET_OPTION(issuercert_blob)->len);
  3447. else {
  3448. fp = BIO_new(BIO_s_file());
  3449. if(!fp) {
  3450. failf(data,
  3451. "BIO_new return NULL, " OSSL_PACKAGE
  3452. " error %s",
  3453. ossl_strerror(ERR_get_error(), error_buffer,
  3454. sizeof(error_buffer)) );
  3455. X509_free(backend->server_cert);
  3456. backend->server_cert = NULL;
  3457. return CURLE_OUT_OF_MEMORY;
  3458. }
  3459. if(BIO_read_filename(fp, SSL_SET_OPTION(issuercert)) <= 0) {
  3460. if(strict)
  3461. failf(data, "SSL: Unable to open issuer cert (%s)",
  3462. SSL_SET_OPTION(issuercert));
  3463. BIO_free(fp);
  3464. X509_free(backend->server_cert);
  3465. backend->server_cert = NULL;
  3466. return CURLE_SSL_ISSUER_ERROR;
  3467. }
  3468. }
  3469. issuer = PEM_read_bio_X509(fp, NULL, ZERO_NULL, NULL);
  3470. if(!issuer) {
  3471. if(strict)
  3472. failf(data, "SSL: Unable to read issuer cert (%s)",
  3473. SSL_SET_OPTION(issuercert));
  3474. BIO_free(fp);
  3475. X509_free(issuer);
  3476. X509_free(backend->server_cert);
  3477. backend->server_cert = NULL;
  3478. return CURLE_SSL_ISSUER_ERROR;
  3479. }
  3480. if(X509_check_issued(issuer, backend->server_cert) != X509_V_OK) {
  3481. if(strict)
  3482. failf(data, "SSL: Certificate issuer check failed (%s)",
  3483. SSL_SET_OPTION(issuercert));
  3484. BIO_free(fp);
  3485. X509_free(issuer);
  3486. X509_free(backend->server_cert);
  3487. backend->server_cert = NULL;
  3488. return CURLE_SSL_ISSUER_ERROR;
  3489. }
  3490. infof(data, " SSL certificate issuer check ok (%s)\n",
  3491. SSL_SET_OPTION(issuercert));
  3492. BIO_free(fp);
  3493. X509_free(issuer);
  3494. }
  3495. lerr = SSL_get_verify_result(backend->handle);
  3496. SSL_SET_OPTION_LVALUE(certverifyresult) = lerr;
  3497. if(lerr != X509_V_OK) {
  3498. if(SSL_CONN_CONFIG(verifypeer)) {
  3499. /* We probably never reach this, because SSL_connect() will fail
  3500. and we return earlier if verifypeer is set? */
  3501. if(strict)
  3502. failf(data, "SSL certificate verify result: %s (%ld)",
  3503. X509_verify_cert_error_string(lerr), lerr);
  3504. result = CURLE_PEER_FAILED_VERIFICATION;
  3505. }
  3506. else
  3507. infof(data, " SSL certificate verify result: %s (%ld),"
  3508. " continuing anyway.\n",
  3509. X509_verify_cert_error_string(lerr), lerr);
  3510. }
  3511. else
  3512. infof(data, " SSL certificate verify ok.\n");
  3513. }
  3514. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
  3515. !defined(OPENSSL_NO_OCSP)
  3516. if(SSL_CONN_CONFIG(verifystatus)) {
  3517. result = verifystatus(data, connssl);
  3518. if(result) {
  3519. X509_free(backend->server_cert);
  3520. backend->server_cert = NULL;
  3521. return result;
  3522. }
  3523. }
  3524. #endif
  3525. if(!strict)
  3526. /* when not strict, we don't bother about the verify cert problems */
  3527. result = CURLE_OK;
  3528. ptr = SSL_PINNED_PUB_KEY();
  3529. if(!result && ptr) {
  3530. result = pkp_pin_peer_pubkey(data, backend->server_cert, ptr);
  3531. if(result)
  3532. failf(data, "SSL: public key does not match pinned public key!");
  3533. }
  3534. X509_free(backend->server_cert);
  3535. backend->server_cert = NULL;
  3536. connssl->connecting_state = ssl_connect_done;
  3537. return result;
  3538. }
  3539. static CURLcode ossl_connect_step3(struct Curl_easy *data,
  3540. struct connectdata *conn, int sockindex)
  3541. {
  3542. CURLcode result = CURLE_OK;
  3543. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  3544. DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
  3545. /*
  3546. * We check certificates to authenticate the server; otherwise we risk
  3547. * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
  3548. * verify the peer ignore faults and failures from the server cert
  3549. * operations.
  3550. */
  3551. result = servercert(data, conn, connssl, (SSL_CONN_CONFIG(verifypeer) ||
  3552. SSL_CONN_CONFIG(verifyhost)));
  3553. if(!result)
  3554. connssl->connecting_state = ssl_connect_done;
  3555. return result;
  3556. }
  3557. static Curl_recv ossl_recv;
  3558. static Curl_send ossl_send;
  3559. static CURLcode ossl_connect_common(struct Curl_easy *data,
  3560. struct connectdata *conn,
  3561. int sockindex,
  3562. bool nonblocking,
  3563. bool *done)
  3564. {
  3565. CURLcode result;
  3566. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  3567. curl_socket_t sockfd = conn->sock[sockindex];
  3568. int what;
  3569. /* check if the connection has already been established */
  3570. if(ssl_connection_complete == connssl->state) {
  3571. *done = TRUE;
  3572. return CURLE_OK;
  3573. }
  3574. if(ssl_connect_1 == connssl->connecting_state) {
  3575. /* Find out how much more time we're allowed */
  3576. const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
  3577. if(timeout_ms < 0) {
  3578. /* no need to continue if time already is up */
  3579. failf(data, "SSL connection timeout");
  3580. return CURLE_OPERATION_TIMEDOUT;
  3581. }
  3582. result = ossl_connect_step1(data, conn, sockindex);
  3583. if(result)
  3584. return result;
  3585. }
  3586. while(ssl_connect_2 == connssl->connecting_state ||
  3587. ssl_connect_2_reading == connssl->connecting_state ||
  3588. ssl_connect_2_writing == connssl->connecting_state) {
  3589. /* check allowed time left */
  3590. const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
  3591. if(timeout_ms < 0) {
  3592. /* no need to continue if time already is up */
  3593. failf(data, "SSL connection timeout");
  3594. return CURLE_OPERATION_TIMEDOUT;
  3595. }
  3596. /* if ssl is expecting something, check if it's available. */
  3597. if(connssl->connecting_state == ssl_connect_2_reading ||
  3598. connssl->connecting_state == ssl_connect_2_writing) {
  3599. curl_socket_t writefd = ssl_connect_2_writing ==
  3600. connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
  3601. curl_socket_t readfd = ssl_connect_2_reading ==
  3602. connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
  3603. what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
  3604. nonblocking?0:timeout_ms);
  3605. if(what < 0) {
  3606. /* fatal error */
  3607. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  3608. return CURLE_SSL_CONNECT_ERROR;
  3609. }
  3610. if(0 == what) {
  3611. if(nonblocking) {
  3612. *done = FALSE;
  3613. return CURLE_OK;
  3614. }
  3615. /* timeout */
  3616. failf(data, "SSL connection timeout");
  3617. return CURLE_OPERATION_TIMEDOUT;
  3618. }
  3619. /* socket is readable or writable */
  3620. }
  3621. /* Run transaction, and return to the caller if it failed or if this
  3622. * connection is done nonblocking and this loop would execute again. This
  3623. * permits the owner of a multi handle to abort a connection attempt
  3624. * before step2 has completed while ensuring that a client using select()
  3625. * or epoll() will always have a valid fdset to wait on.
  3626. */
  3627. result = ossl_connect_step2(data, conn, sockindex);
  3628. if(result || (nonblocking &&
  3629. (ssl_connect_2 == connssl->connecting_state ||
  3630. ssl_connect_2_reading == connssl->connecting_state ||
  3631. ssl_connect_2_writing == connssl->connecting_state)))
  3632. return result;
  3633. } /* repeat step2 until all transactions are done. */
  3634. if(ssl_connect_3 == connssl->connecting_state) {
  3635. result = ossl_connect_step3(data, conn, sockindex);
  3636. if(result)
  3637. return result;
  3638. }
  3639. if(ssl_connect_done == connssl->connecting_state) {
  3640. connssl->state = ssl_connection_complete;
  3641. conn->recv[sockindex] = ossl_recv;
  3642. conn->send[sockindex] = ossl_send;
  3643. *done = TRUE;
  3644. }
  3645. else
  3646. *done = FALSE;
  3647. /* Reset our connect state machine */
  3648. connssl->connecting_state = ssl_connect_1;
  3649. return CURLE_OK;
  3650. }
  3651. static CURLcode ossl_connect_nonblocking(struct Curl_easy *data,
  3652. struct connectdata *conn,
  3653. int sockindex,
  3654. bool *done)
  3655. {
  3656. return ossl_connect_common(data, conn, sockindex, TRUE, done);
  3657. }
  3658. static CURLcode ossl_connect(struct Curl_easy *data, struct connectdata *conn,
  3659. int sockindex)
  3660. {
  3661. CURLcode result;
  3662. bool done = FALSE;
  3663. result = ossl_connect_common(data, conn, sockindex, FALSE, &done);
  3664. if(result)
  3665. return result;
  3666. DEBUGASSERT(done);
  3667. return CURLE_OK;
  3668. }
  3669. static bool ossl_data_pending(const struct connectdata *conn,
  3670. int connindex)
  3671. {
  3672. const struct ssl_connect_data *connssl = &conn->ssl[connindex];
  3673. if(connssl->backend->handle && SSL_pending(connssl->backend->handle))
  3674. return TRUE;
  3675. #ifndef CURL_DISABLE_PROXY
  3676. {
  3677. const struct ssl_connect_data *proxyssl = &conn->proxy_ssl[connindex];
  3678. if(proxyssl->backend->handle && SSL_pending(proxyssl->backend->handle))
  3679. return TRUE;
  3680. }
  3681. #endif
  3682. return FALSE;
  3683. }
  3684. static size_t ossl_version(char *buffer, size_t size);
  3685. static ssize_t ossl_send(struct Curl_easy *data,
  3686. int sockindex,
  3687. const void *mem,
  3688. size_t len,
  3689. CURLcode *curlcode)
  3690. {
  3691. /* SSL_write() is said to return 'int' while write() and send() returns
  3692. 'size_t' */
  3693. int err;
  3694. char error_buffer[256];
  3695. unsigned long sslerror;
  3696. int memlen;
  3697. int rc;
  3698. struct connectdata *conn = data->conn;
  3699. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  3700. struct ssl_backend_data *backend = connssl->backend;
  3701. ERR_clear_error();
  3702. memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
  3703. set_logger(conn, data);
  3704. rc = SSL_write(backend->handle, mem, memlen);
  3705. if(rc <= 0) {
  3706. err = SSL_get_error(backend->handle, rc);
  3707. switch(err) {
  3708. case SSL_ERROR_WANT_READ:
  3709. case SSL_ERROR_WANT_WRITE:
  3710. /* The operation did not complete; the same TLS/SSL I/O function
  3711. should be called again later. This is basically an EWOULDBLOCK
  3712. equivalent. */
  3713. *curlcode = CURLE_AGAIN;
  3714. return -1;
  3715. case SSL_ERROR_SYSCALL:
  3716. {
  3717. int sockerr = SOCKERRNO;
  3718. sslerror = ERR_get_error();
  3719. if(sslerror)
  3720. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
  3721. else if(sockerr)
  3722. Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
  3723. else {
  3724. strncpy(error_buffer, SSL_ERROR_to_str(err), sizeof(error_buffer));
  3725. error_buffer[sizeof(error_buffer) - 1] = '\0';
  3726. }
  3727. failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d",
  3728. error_buffer, sockerr);
  3729. *curlcode = CURLE_SEND_ERROR;
  3730. return -1;
  3731. }
  3732. case SSL_ERROR_SSL:
  3733. /* A failure in the SSL library occurred, usually a protocol error.
  3734. The OpenSSL error queue contains more information on the error. */
  3735. sslerror = ERR_get_error();
  3736. if(ERR_GET_LIB(sslerror) == ERR_LIB_SSL &&
  3737. ERR_GET_REASON(sslerror) == SSL_R_BIO_NOT_SET &&
  3738. conn->ssl[sockindex].state == ssl_connection_complete
  3739. #ifndef CURL_DISABLE_PROXY
  3740. && conn->proxy_ssl[sockindex].state == ssl_connection_complete
  3741. #endif
  3742. ) {
  3743. char ver[120];
  3744. ossl_version(ver, 120);
  3745. failf(data, "Error: %s does not support double SSL tunneling.", ver);
  3746. }
  3747. else
  3748. failf(data, "SSL_write() error: %s",
  3749. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
  3750. *curlcode = CURLE_SEND_ERROR;
  3751. return -1;
  3752. }
  3753. /* a true error */
  3754. failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d",
  3755. SSL_ERROR_to_str(err), SOCKERRNO);
  3756. *curlcode = CURLE_SEND_ERROR;
  3757. return -1;
  3758. }
  3759. *curlcode = CURLE_OK;
  3760. return (ssize_t)rc; /* number of bytes */
  3761. }
  3762. static ssize_t ossl_recv(struct Curl_easy *data, /* transfer */
  3763. int num, /* socketindex */
  3764. char *buf, /* store read data here */
  3765. size_t buffersize, /* max amount to read */
  3766. CURLcode *curlcode)
  3767. {
  3768. char error_buffer[256];
  3769. unsigned long sslerror;
  3770. ssize_t nread;
  3771. int buffsize;
  3772. struct connectdata *conn = data->conn;
  3773. struct ssl_connect_data *connssl = &conn->ssl[num];
  3774. struct ssl_backend_data *backend = connssl->backend;
  3775. ERR_clear_error();
  3776. buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
  3777. set_logger(conn, data);
  3778. nread = (ssize_t)SSL_read(backend->handle, buf, buffsize);
  3779. if(nread <= 0) {
  3780. /* failed SSL_read */
  3781. int err = SSL_get_error(backend->handle, (int)nread);
  3782. switch(err) {
  3783. case SSL_ERROR_NONE: /* this is not an error */
  3784. break;
  3785. case SSL_ERROR_ZERO_RETURN: /* no more data */
  3786. /* close_notify alert */
  3787. if(num == FIRSTSOCKET)
  3788. /* mark the connection for close if it is indeed the control
  3789. connection */
  3790. connclose(conn, "TLS close_notify");
  3791. break;
  3792. case SSL_ERROR_WANT_READ:
  3793. case SSL_ERROR_WANT_WRITE:
  3794. /* there's data pending, re-invoke SSL_read() */
  3795. *curlcode = CURLE_AGAIN;
  3796. return -1;
  3797. default:
  3798. /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
  3799. value/errno" */
  3800. /* https://www.openssl.org/docs/crypto/ERR_get_error.html */
  3801. sslerror = ERR_get_error();
  3802. if((nread < 0) || sslerror) {
  3803. /* If the return code was negative or there actually is an error in the
  3804. queue */
  3805. int sockerr = SOCKERRNO;
  3806. if(sslerror)
  3807. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
  3808. else if(sockerr && err == SSL_ERROR_SYSCALL)
  3809. Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
  3810. else {
  3811. strncpy(error_buffer, SSL_ERROR_to_str(err), sizeof(error_buffer));
  3812. error_buffer[sizeof(error_buffer) - 1] = '\0';
  3813. }
  3814. failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d",
  3815. error_buffer, sockerr);
  3816. *curlcode = CURLE_RECV_ERROR;
  3817. return -1;
  3818. }
  3819. /* For debug builds be a little stricter and error on any
  3820. SSL_ERROR_SYSCALL. For example a server may have closed the connection
  3821. abruptly without a close_notify alert. For compatibility with older
  3822. peers we don't do this by default. #4624
  3823. We can use this to gauge how many users may be affected, and
  3824. if it goes ok eventually transition to allow in dev and release with
  3825. the newest OpenSSL: #if (OPENSSL_VERSION_NUMBER >= 0x10101000L) */
  3826. #ifdef DEBUGBUILD
  3827. if(err == SSL_ERROR_SYSCALL) {
  3828. int sockerr = SOCKERRNO;
  3829. if(sockerr)
  3830. Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
  3831. else {
  3832. msnprintf(error_buffer, sizeof(error_buffer),
  3833. "Connection closed abruptly");
  3834. }
  3835. failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d"
  3836. " (Fatal because this is a curl debug build)",
  3837. error_buffer, sockerr);
  3838. *curlcode = CURLE_RECV_ERROR;
  3839. return -1;
  3840. }
  3841. #endif
  3842. }
  3843. }
  3844. return nread;
  3845. }
  3846. static size_t ossl_version(char *buffer, size_t size)
  3847. {
  3848. #ifdef LIBRESSL_VERSION_NUMBER
  3849. #if LIBRESSL_VERSION_NUMBER < 0x2070100fL
  3850. return msnprintf(buffer, size, "%s/%lx.%lx.%lx",
  3851. OSSL_PACKAGE,
  3852. (LIBRESSL_VERSION_NUMBER>>28)&0xf,
  3853. (LIBRESSL_VERSION_NUMBER>>20)&0xff,
  3854. (LIBRESSL_VERSION_NUMBER>>12)&0xff);
  3855. #else /* OpenSSL_version() first appeared in LibreSSL 2.7.1 */
  3856. char *p;
  3857. int count;
  3858. const char *ver = OpenSSL_version(OPENSSL_VERSION);
  3859. const char expected[] = OSSL_PACKAGE " "; /* ie "LibreSSL " */
  3860. if(Curl_strncasecompare(ver, expected, sizeof(expected) - 1)) {
  3861. ver += sizeof(expected) - 1;
  3862. }
  3863. count = msnprintf(buffer, size, "%s/%s", OSSL_PACKAGE, ver);
  3864. for(p = buffer; *p; ++p) {
  3865. if(ISSPACE(*p))
  3866. *p = '_';
  3867. }
  3868. return count;
  3869. #endif
  3870. #elif defined(OPENSSL_IS_BORINGSSL)
  3871. return msnprintf(buffer, size, OSSL_PACKAGE);
  3872. #elif defined(HAVE_OPENSSL_VERSION) && defined(OPENSSL_VERSION_STRING)
  3873. return msnprintf(buffer, size, "%s/%s",
  3874. OSSL_PACKAGE, OpenSSL_version(OPENSSL_VERSION_STRING));
  3875. #else
  3876. /* not LibreSSL, BoringSSL and not using OpenSSL_version */
  3877. char sub[3];
  3878. unsigned long ssleay_value;
  3879. sub[2]='\0';
  3880. sub[1]='\0';
  3881. ssleay_value = OpenSSL_version_num();
  3882. if(ssleay_value < 0x906000) {
  3883. ssleay_value = SSLEAY_VERSION_NUMBER;
  3884. sub[0]='\0';
  3885. }
  3886. else {
  3887. if(ssleay_value&0xff0) {
  3888. int minor_ver = (ssleay_value >> 4) & 0xff;
  3889. if(minor_ver > 26) {
  3890. /* handle extended version introduced for 0.9.8za */
  3891. sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1);
  3892. sub[0] = 'z';
  3893. }
  3894. else {
  3895. sub[0] = (char) (minor_ver + 'a' - 1);
  3896. }
  3897. }
  3898. else
  3899. sub[0]='\0';
  3900. }
  3901. return msnprintf(buffer, size, "%s/%lx.%lx.%lx%s"
  3902. #ifdef OPENSSL_FIPS
  3903. "-fips"
  3904. #endif
  3905. ,
  3906. OSSL_PACKAGE,
  3907. (ssleay_value>>28)&0xf,
  3908. (ssleay_value>>20)&0xff,
  3909. (ssleay_value>>12)&0xff,
  3910. sub);
  3911. #endif /* OPENSSL_IS_BORINGSSL */
  3912. }
  3913. /* can be called with data == NULL */
  3914. static CURLcode ossl_random(struct Curl_easy *data,
  3915. unsigned char *entropy, size_t length)
  3916. {
  3917. int rc;
  3918. if(data) {
  3919. if(ossl_seed(data)) /* Initiate the seed if not already done */
  3920. return CURLE_FAILED_INIT; /* couldn't seed for some reason */
  3921. }
  3922. else {
  3923. if(!rand_enough())
  3924. return CURLE_FAILED_INIT;
  3925. }
  3926. /* RAND_bytes() returns 1 on success, 0 otherwise. */
  3927. rc = RAND_bytes(entropy, curlx_uztosi(length));
  3928. return (rc == 1 ? CURLE_OK : CURLE_FAILED_INIT);
  3929. }
  3930. #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
  3931. static CURLcode ossl_sha256sum(const unsigned char *tmp, /* input */
  3932. size_t tmplen,
  3933. unsigned char *sha256sum /* output */,
  3934. size_t unused)
  3935. {
  3936. EVP_MD_CTX *mdctx;
  3937. unsigned int len = 0;
  3938. (void) unused;
  3939. mdctx = EVP_MD_CTX_create();
  3940. if(!mdctx)
  3941. return CURLE_OUT_OF_MEMORY;
  3942. EVP_DigestInit(mdctx, EVP_sha256());
  3943. EVP_DigestUpdate(mdctx, tmp, tmplen);
  3944. EVP_DigestFinal_ex(mdctx, sha256sum, &len);
  3945. EVP_MD_CTX_destroy(mdctx);
  3946. return CURLE_OK;
  3947. }
  3948. #endif
  3949. static bool ossl_cert_status_request(void)
  3950. {
  3951. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
  3952. !defined(OPENSSL_NO_OCSP)
  3953. return TRUE;
  3954. #else
  3955. return FALSE;
  3956. #endif
  3957. }
  3958. static void *ossl_get_internals(struct ssl_connect_data *connssl,
  3959. CURLINFO info)
  3960. {
  3961. /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */
  3962. struct ssl_backend_data *backend = connssl->backend;
  3963. return info == CURLINFO_TLS_SESSION ?
  3964. (void *)backend->ctx : (void *)backend->handle;
  3965. }
  3966. static void ossl_associate_connection(struct Curl_easy *data,
  3967. struct connectdata *conn,
  3968. int sockindex)
  3969. {
  3970. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  3971. struct ssl_backend_data *backend = connssl->backend;
  3972. /* If we don't have SSL context, do nothing. */
  3973. if(!backend->handle)
  3974. return;
  3975. if(SSL_SET_OPTION(primary.sessionid)) {
  3976. int data_idx = ossl_get_ssl_data_index();
  3977. int connectdata_idx = ossl_get_ssl_conn_index();
  3978. int sockindex_idx = ossl_get_ssl_sockindex_index();
  3979. int proxy_idx = ossl_get_proxy_index();
  3980. if(data_idx >= 0 && connectdata_idx >= 0 && sockindex_idx >= 0 &&
  3981. proxy_idx >= 0) {
  3982. /* Store the data needed for the "new session" callback.
  3983. * The sockindex is stored as a pointer to an array element. */
  3984. SSL_set_ex_data(backend->handle, data_idx, data);
  3985. SSL_set_ex_data(backend->handle, connectdata_idx, conn);
  3986. SSL_set_ex_data(backend->handle, sockindex_idx, conn->sock + sockindex);
  3987. #ifndef CURL_DISABLE_PROXY
  3988. SSL_set_ex_data(backend->handle, proxy_idx, SSL_IS_PROXY() ? (void *) 1:
  3989. NULL);
  3990. #else
  3991. SSL_set_ex_data(backend->handle, proxy_idx, NULL);
  3992. #endif
  3993. }
  3994. }
  3995. }
  3996. /*
  3997. * Starting with TLS 1.3, the ossl_new_session_cb callback gets called after
  3998. * the handshake. If the transfer that sets up the callback gets killed before
  3999. * this callback arrives, we must make sure to properly clear the data to
  4000. * avoid UAF problems. A future optimization could be to instead store another
  4001. * transfer that might still be using the same connection.
  4002. */
  4003. static void ossl_disassociate_connection(struct Curl_easy *data,
  4004. int sockindex)
  4005. {
  4006. struct connectdata *conn = data->conn;
  4007. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  4008. struct ssl_backend_data *backend = connssl->backend;
  4009. /* If we don't have SSL context, do nothing. */
  4010. if(!backend->handle)
  4011. return;
  4012. if(SSL_SET_OPTION(primary.sessionid)) {
  4013. bool isproxy = FALSE;
  4014. bool incache;
  4015. void *old_ssl_sessionid = NULL;
  4016. int data_idx = ossl_get_ssl_data_index();
  4017. int connectdata_idx = ossl_get_ssl_conn_index();
  4018. int sockindex_idx = ossl_get_ssl_sockindex_index();
  4019. int proxy_idx = ossl_get_proxy_index();
  4020. if(data_idx >= 0 && connectdata_idx >= 0 && sockindex_idx >= 0 &&
  4021. proxy_idx >= 0) {
  4022. /* Invalidate the session cache entry, if any */
  4023. isproxy = SSL_get_ex_data(backend->handle, proxy_idx) ? TRUE : FALSE;
  4024. /* Disable references to data in "new session" callback to avoid
  4025. * accessing a stale pointer. */
  4026. SSL_set_ex_data(backend->handle, data_idx, NULL);
  4027. SSL_set_ex_data(backend->handle, connectdata_idx, NULL);
  4028. SSL_set_ex_data(backend->handle, sockindex_idx, NULL);
  4029. SSL_set_ex_data(backend->handle, proxy_idx, NULL);
  4030. }
  4031. Curl_ssl_sessionid_lock(data);
  4032. incache = !(Curl_ssl_getsessionid(data, conn, isproxy,
  4033. &old_ssl_sessionid, NULL, sockindex));
  4034. if(incache)
  4035. Curl_ssl_delsessionid(data, old_ssl_sessionid);
  4036. Curl_ssl_sessionid_unlock(data);
  4037. }
  4038. }
  4039. const struct Curl_ssl Curl_ssl_openssl = {
  4040. { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */
  4041. SSLSUPP_CA_PATH |
  4042. SSLSUPP_CAINFO_BLOB |
  4043. SSLSUPP_CERTINFO |
  4044. SSLSUPP_PINNEDPUBKEY |
  4045. SSLSUPP_SSL_CTX |
  4046. #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
  4047. SSLSUPP_TLS13_CIPHERSUITES |
  4048. #endif
  4049. SSLSUPP_HTTPS_PROXY,
  4050. sizeof(struct ssl_backend_data),
  4051. ossl_init, /* init */
  4052. ossl_cleanup, /* cleanup */
  4053. ossl_version, /* version */
  4054. ossl_check_cxn, /* check_cxn */
  4055. ossl_shutdown, /* shutdown */
  4056. ossl_data_pending, /* data_pending */
  4057. ossl_random, /* random */
  4058. ossl_cert_status_request, /* cert_status_request */
  4059. ossl_connect, /* connect */
  4060. ossl_connect_nonblocking, /* connect_nonblocking */
  4061. Curl_ssl_getsock, /* getsock */
  4062. ossl_get_internals, /* get_internals */
  4063. ossl_close, /* close_one */
  4064. ossl_close_all, /* close_all */
  4065. ossl_session_free, /* session_free */
  4066. ossl_set_engine, /* set_engine */
  4067. ossl_set_engine_default, /* set_engine_default */
  4068. ossl_engines_list, /* engines_list */
  4069. Curl_none_false_start, /* false_start */
  4070. #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
  4071. ossl_sha256sum, /* sha256sum */
  4072. #else
  4073. NULL, /* sha256sum */
  4074. #endif
  4075. ossl_associate_connection, /* associate_connection */
  4076. ossl_disassociate_connection /* disassociate_connection */
  4077. };
  4078. #endif /* USE_OPENSSL */