2
0

openssl.c 157 KB

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