2
0

openssl.c 142 KB

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