openssl.c 142 KB

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