openssl.c 177 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <[email protected]>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * 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. #ifdef 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 "../curlx/inet_pton.h"
  47. #include "openssl.h"
  48. #include "../connect.h"
  49. #include "../slist.h"
  50. #include "../select.h"
  51. #include "../curlx/wait.h"
  52. #include "vtls.h"
  53. #include "vtls_int.h"
  54. #include "vtls_scache.h"
  55. #include "../vauth/vauth.h"
  56. #include "keylog.h"
  57. #include "hostcheck.h"
  58. #include "../transfer.h"
  59. #include "../multiif.h"
  60. #include "../curlx/strerr.h"
  61. #include "../curlx/strparse.h"
  62. #include "../strdup.h"
  63. #include "apple.h"
  64. #include <openssl/ssl.h>
  65. #include <openssl/rand.h>
  66. #include <openssl/x509v3.h>
  67. #ifndef OPENSSL_NO_DSA
  68. #include <openssl/dsa.h>
  69. #endif
  70. #include <openssl/dh.h>
  71. #include <openssl/err.h>
  72. #include <openssl/md5.h>
  73. #include <openssl/conf.h>
  74. #include <openssl/bn.h>
  75. #include <openssl/rsa.h>
  76. #include <openssl/bio.h>
  77. #include <openssl/buffer.h>
  78. #include <openssl/pkcs12.h>
  79. #include <openssl/tls1.h>
  80. #include <openssl/evp.h>
  81. #ifdef HAVE_SSL_SET1_ECH_CONFIG_LIST
  82. #define USE_ECH_OPENSSL
  83. #endif
  84. #if defined(USE_ECH_OPENSSL) && !defined(HAVE_BORINGSSL_LIKE)
  85. #include <openssl/ech.h>
  86. #endif
  87. #ifndef OPENSSL_NO_OCSP
  88. #include <openssl/ocsp.h>
  89. #endif
  90. #if !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_UI_CONSOLE)
  91. #define USE_OPENSSL_ENGINE
  92. #include <openssl/engine.h>
  93. #endif
  94. #ifdef LIBRESSL_VERSION_NUMBER
  95. /* As of LibreSSL 2.0.0-4.0.0: OPENSSL_VERSION_NUMBER == 0x20000000L */
  96. # if LIBRESSL_VERSION_NUMBER < 0x2090100fL /* 2019-04-13 */
  97. # error "LibreSSL 2.9.1 or later required"
  98. # endif
  99. #elif OPENSSL_VERSION_NUMBER < 0x1000201fL /* 2015-03-19 */
  100. # error "OpenSSL 1.0.2a or later required"
  101. #endif
  102. #if defined(HAVE_OPENSSL3) && !defined(OPENSSL_NO_UI_CONSOLE)
  103. #include <openssl/provider.h>
  104. #include <openssl/store.h>
  105. /* this is used in the following conditions to make them easier to read */
  106. #define OPENSSL_HAS_PROVIDERS
  107. static void ossl_provider_cleanup(struct Curl_easy *data);
  108. #endif
  109. /* AWS-LC fixed a bug with large buffers in v1.61.0 which also introduced
  110. * X509_V_ERR_EC_KEY_EXPLICIT_PARAMS. */
  111. #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
  112. !defined(LIBRESSL_VERSION_NUMBER) && !defined(OPENSSL_IS_BORINGSSL) && \
  113. (!defined(OPENSSL_IS_AWSLC) || defined(X509_V_ERR_EC_KEY_EXPLICIT_PARAMS))
  114. #define HAVE_SSL_CTX_SET_DEFAULT_READ_BUFFER_LEN 1
  115. #endif
  116. #include "../curlx/warnless.h"
  117. /* The last #include files should be: */
  118. #include "../curl_memory.h"
  119. #include "../memdebug.h"
  120. #if defined(USE_OPENSSL_ENGINE) || defined(OPENSSL_HAS_PROVIDERS)
  121. #include <openssl/ui.h>
  122. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  123. #define OSSL_UI_METHOD_CAST(x) (x)
  124. #else
  125. #define OSSL_UI_METHOD_CAST(x) CURL_UNCONST(x)
  126. #endif
  127. #endif
  128. #if OPENSSL_VERSION_NUMBER >= 0x10100000L /* OpenSSL 1.1.0+ and LibreSSL */
  129. #define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */
  130. #define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */
  131. #define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */
  132. #define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1
  133. #else
  134. /* For OpenSSL before 1.1.0 */
  135. #define ASN1_STRING_get0_data(x) ASN1_STRING_data(x)
  136. #define X509_get0_notBefore(x) X509_get_notBefore(x)
  137. #define X509_get0_notAfter(x) X509_get_notAfter(x)
  138. #define OpenSSL_version_num() SSLeay()
  139. #endif
  140. #if OPENSSL_VERSION_NUMBER >= 0x10002003L && \
  141. OPENSSL_VERSION_NUMBER <= 0x10002FFFL && \
  142. !defined(OPENSSL_NO_COMP)
  143. #define HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1
  144. #endif
  145. #ifdef HAVE_OPENSSL3
  146. #define HAVE_EVP_PKEY_GET_PARAMS 1
  147. #endif
  148. #ifdef HAVE_EVP_PKEY_GET_PARAMS
  149. #include <openssl/core_names.h>
  150. #define DECLARE_PKEY_PARAM_BIGNUM(name) BIGNUM *name = NULL
  151. #define FREE_PKEY_PARAM_BIGNUM(name) BN_clear_free(name)
  152. #else
  153. #define DECLARE_PKEY_PARAM_BIGNUM(name) const BIGNUM *name
  154. #define FREE_PKEY_PARAM_BIGNUM(name)
  155. #endif
  156. /* Whether SSL_CTX_set_ciphersuites is available.
  157. * OpenSSL: supported since 1.1.1 (commit a53b5be6a05)
  158. * BoringSSL: no
  159. * LibreSSL: supported since 3.4.1 (released 2021-10-14)
  160. */
  161. #if ((OPENSSL_VERSION_NUMBER >= 0x10101000L && \
  162. !defined(LIBRESSL_VERSION_NUMBER)) || \
  163. (defined(LIBRESSL_VERSION_NUMBER) && \
  164. LIBRESSL_VERSION_NUMBER >= 0x3040100fL)) && \
  165. !defined(OPENSSL_IS_BORINGSSL)
  166. # define HAVE_SSL_CTX_SET_CIPHERSUITES
  167. # ifndef OPENSSL_IS_AWSLC
  168. # define HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH
  169. # endif
  170. #endif
  171. /* Whether SSL_CTX_set1_sigalgs_list is available
  172. * OpenSSL: supported since 1.0.2 (commit 0b362de5f575)
  173. * BoringSSL: supported since 0.20240913.0 (commit 826ce15)
  174. * LibreSSL: no
  175. */
  176. #if OPENSSL_VERSION_NUMBER >= 0x10002000L && !defined(LIBRESSL_VERSION_NUMBER)
  177. #define HAVE_SSL_CTX_SET1_SIGALGS
  178. #endif
  179. #ifdef LIBRESSL_VERSION_NUMBER
  180. #define OSSL_PACKAGE "LibreSSL"
  181. #elif defined(OPENSSL_IS_BORINGSSL)
  182. #define OSSL_PACKAGE "BoringSSL"
  183. #elif defined(OPENSSL_IS_AWSLC)
  184. #define OSSL_PACKAGE "AWS-LC"
  185. #elif defined(USE_NGTCP2) && defined(USE_NGHTTP3) && \
  186. !defined(OPENSSL_QUIC_API2)
  187. #define OSSL_PACKAGE "quictls"
  188. #else
  189. #define OSSL_PACKAGE "OpenSSL"
  190. #endif
  191. #ifdef HAVE_BORINGSSL_LIKE
  192. typedef size_t numcert_t;
  193. typedef uint32_t sslerr_t;
  194. #else
  195. typedef int numcert_t;
  196. typedef unsigned long sslerr_t;
  197. #endif
  198. #define ossl_valsize_t numcert_t
  199. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  200. /* up2date versions of OpenSSL maintain reasonably secure defaults without
  201. * breaking compatibility, so it is better not to override the defaults in curl
  202. */
  203. #define DEFAULT_CIPHER_SELECTION NULL
  204. #else
  205. /* not the case with old versions of OpenSSL */
  206. #define DEFAULT_CIPHER_SELECTION \
  207. "ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH"
  208. #endif
  209. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  210. #define HAVE_RANDOM_INIT_BY_DEFAULT 1
  211. #endif
  212. /*
  213. * Whether the OpenSSL version has the API needed to support sharing an
  214. * X509_STORE between connections. The API is:
  215. * * `X509_STORE_up_ref` -- Introduced: OpenSSL 1.1.0.
  216. */
  217. #if OPENSSL_VERSION_NUMBER >= 0x10100000L /* OpenSSL >= 1.1.0 */
  218. #define HAVE_SSL_X509_STORE_SHARE
  219. #endif
  220. #if (OPENSSL_VERSION_NUMBER > 0x10100000L) /* OpenSSL > 1.1.0 */
  221. #define HAVE_SSL_X509_GET_SIGNATURE_NID
  222. #endif
  223. /* FIXME: On LCC <= 1.23, OpenSSL 2.0.0 may be found but does not seem to
  224. * have X509_STORE_up_ref or X509_get_signature_nid. */
  225. #if defined(__LCC__) && defined(__EDG__) && (__LCC__ <= 123)
  226. #undef HAVE_SSL_X509_STORE_SHARE
  227. #undef HAVE_SSL_X509_GET_SIGNATURE_NID
  228. #endif
  229. static CURLcode ossl_certchain(struct Curl_easy *data, SSL *ssl);
  230. static CURLcode push_certinfo(struct Curl_easy *data,
  231. BIO *mem, const char *label, int num)
  232. WARN_UNUSED_RESULT;
  233. static CURLcode push_certinfo(struct Curl_easy *data,
  234. BIO *mem, const char *label, int num)
  235. {
  236. char *ptr;
  237. long len = BIO_get_mem_data(mem, &ptr);
  238. CURLcode result = Curl_ssl_push_certinfo_len(data, num, label, ptr, len);
  239. (void)BIO_reset(mem);
  240. return result;
  241. }
  242. static CURLcode pubkey_show(struct Curl_easy *data,
  243. BIO *mem,
  244. int num,
  245. const char *type,
  246. const char *name,
  247. const BIGNUM *bn)
  248. {
  249. char namebuf[32];
  250. curl_msnprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
  251. if(bn)
  252. BN_print(mem, bn);
  253. return push_certinfo(data, mem, namebuf, num);
  254. }
  255. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  256. #define print_pubkey_BN(_type, _name, _num) \
  257. pubkey_show(data, mem, _num, #_type, #_name, _name)
  258. #else
  259. #define print_pubkey_BN(_type, _name, _num) \
  260. do { \
  261. if(_type->_name) { \
  262. pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \
  263. } \
  264. } while(0)
  265. #endif
  266. static int asn1_object_dump(const ASN1_OBJECT *a, char *buf, size_t len)
  267. {
  268. int i;
  269. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  270. i = i2t_ASN1_OBJECT(buf, (int)len, a);
  271. #else
  272. i = i2t_ASN1_OBJECT(buf, (int)len, CURL_UNCONST(a));
  273. #endif
  274. return (i >= (int)len); /* buffer too small */
  275. }
  276. static CURLcode X509V3_ext(struct Curl_easy *data,
  277. int certnum,
  278. const STACK_OF(X509_EXTENSION) *extsarg)
  279. {
  280. int i;
  281. CURLcode result = CURLE_OK;
  282. #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
  283. const STACK_OF(X509_EXTENSION) *exts = extsarg;
  284. #else
  285. STACK_OF(X509_EXTENSION) *exts = CURL_UNCONST(extsarg);
  286. #endif
  287. if((int)sk_X509_EXTENSION_num(exts) <= 0)
  288. /* no extensions, bail out */
  289. return result;
  290. for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
  291. ASN1_OBJECT *obj;
  292. X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, (ossl_valsize_t)i);
  293. BUF_MEM *biomem;
  294. char namebuf[128];
  295. BIO *bio_out = BIO_new(BIO_s_mem());
  296. if(!bio_out)
  297. return result;
  298. obj = X509_EXTENSION_get_object(ext);
  299. if(asn1_object_dump(obj, namebuf, sizeof(namebuf)))
  300. /* make sure the name is null-terminated */
  301. namebuf [ sizeof(namebuf) - 1] = 0;
  302. if(!X509V3_EXT_print(bio_out, ext, 0, 0))
  303. ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext));
  304. BIO_get_mem_ptr(bio_out, &biomem);
  305. result = Curl_ssl_push_certinfo_len(data, certnum, namebuf, biomem->data,
  306. biomem->length);
  307. BIO_free(bio_out);
  308. if(result)
  309. break;
  310. }
  311. return result;
  312. }
  313. #define MAX_ALLOWED_CERT_AMOUNT 100
  314. static CURLcode ossl_certchain(struct Curl_easy *data, SSL *ssl)
  315. {
  316. CURLcode result;
  317. STACK_OF(X509) *sk;
  318. int i;
  319. numcert_t numcerts;
  320. BIO *mem;
  321. DEBUGASSERT(ssl);
  322. sk = SSL_get_peer_cert_chain(ssl);
  323. if(!sk)
  324. return CURLE_SSL_CONNECT_ERROR;
  325. numcerts = sk_X509_num(sk);
  326. if(numcerts > MAX_ALLOWED_CERT_AMOUNT) {
  327. failf(data, "%d certificates is more than allowed (%u)", (int)numcerts,
  328. MAX_ALLOWED_CERT_AMOUNT);
  329. return CURLE_SSL_CONNECT_ERROR;
  330. }
  331. result = Curl_ssl_init_certinfo(data, (int)numcerts);
  332. if(result)
  333. return result;
  334. mem = BIO_new(BIO_s_mem());
  335. if(!mem)
  336. result = CURLE_OUT_OF_MEMORY;
  337. for(i = 0; !result && (i < (int)numcerts); i++) {
  338. ASN1_INTEGER *num;
  339. X509 *x = sk_X509_value(sk, (ossl_valsize_t)i);
  340. EVP_PKEY *pubkey = NULL;
  341. int j;
  342. const ASN1_BIT_STRING *psig = NULL;
  343. X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
  344. result = push_certinfo(data, mem, "Subject", i);
  345. if(result)
  346. break;
  347. X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
  348. result = push_certinfo(data, mem, "Issuer", i);
  349. if(result)
  350. break;
  351. BIO_printf(mem, "%lx", X509_get_version(x));
  352. result = push_certinfo(data, mem, "Version", i);
  353. if(result)
  354. break;
  355. num = X509_get_serialNumber(x);
  356. if(num->type == V_ASN1_NEG_INTEGER)
  357. BIO_puts(mem, "-");
  358. for(j = 0; j < num->length; j++)
  359. BIO_printf(mem, "%02x", num->data[j]);
  360. result = push_certinfo(data, mem, "Serial Number", i);
  361. if(result)
  362. break;
  363. #ifdef HAVE_X509_GET0_EXTENSIONS
  364. {
  365. const X509_ALGOR *sigalg = NULL;
  366. X509_PUBKEY *xpubkey = NULL;
  367. ASN1_OBJECT *pubkeyoid = NULL;
  368. X509_get0_signature(&psig, &sigalg, x);
  369. if(sigalg) {
  370. const ASN1_OBJECT *sigalgoid = NULL;
  371. X509_ALGOR_get0(&sigalgoid, NULL, NULL, sigalg);
  372. i2a_ASN1_OBJECT(mem, sigalgoid);
  373. result = push_certinfo(data, mem, "Signature Algorithm", i);
  374. if(result)
  375. break;
  376. }
  377. xpubkey = X509_get_X509_PUBKEY(x);
  378. if(xpubkey) {
  379. X509_PUBKEY_get0_param(&pubkeyoid, NULL, NULL, NULL, xpubkey);
  380. if(pubkeyoid) {
  381. i2a_ASN1_OBJECT(mem, pubkeyoid);
  382. result = push_certinfo(data, mem, "Public Key Algorithm", i);
  383. if(result)
  384. break;
  385. }
  386. }
  387. result = X509V3_ext(data, i, X509_get0_extensions(x));
  388. if(result)
  389. break;
  390. }
  391. #else
  392. {
  393. /* before OpenSSL 1.0.2 */
  394. X509_CINF *cinf = x->cert_info;
  395. i2a_ASN1_OBJECT(mem, cinf->signature->algorithm);
  396. result = push_certinfo(data, mem, "Signature Algorithm", i);
  397. if(!result) {
  398. i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm);
  399. result = push_certinfo(data, mem, "Public Key Algorithm", i);
  400. }
  401. if(!result)
  402. result = X509V3_ext(data, i, cinf->extensions);
  403. if(result)
  404. break;
  405. psig = x->signature;
  406. }
  407. #endif
  408. ASN1_TIME_print(mem, X509_get0_notBefore(x));
  409. result = push_certinfo(data, mem, "Start date", i);
  410. if(result)
  411. break;
  412. ASN1_TIME_print(mem, X509_get0_notAfter(x));
  413. result = push_certinfo(data, mem, "Expire date", i);
  414. if(result)
  415. break;
  416. pubkey = X509_get_pubkey(x);
  417. if(!pubkey)
  418. infof(data, " Unable to load public key");
  419. else {
  420. int pktype;
  421. #ifdef HAVE_OPAQUE_EVP_PKEY
  422. pktype = EVP_PKEY_id(pubkey);
  423. #else
  424. pktype = pubkey->type;
  425. #endif
  426. switch(pktype) {
  427. case EVP_PKEY_RSA: {
  428. #ifndef HAVE_EVP_PKEY_GET_PARAMS
  429. RSA *rsa;
  430. #ifdef HAVE_OPAQUE_EVP_PKEY
  431. rsa = EVP_PKEY_get0_RSA(pubkey);
  432. #else
  433. rsa = pubkey->pkey.rsa;
  434. #endif /* HAVE_OPAQUE_EVP_PKEY */
  435. #endif /* !HAVE_EVP_PKEY_GET_PARAMS */
  436. {
  437. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  438. DECLARE_PKEY_PARAM_BIGNUM(n);
  439. DECLARE_PKEY_PARAM_BIGNUM(e);
  440. #ifdef HAVE_EVP_PKEY_GET_PARAMS
  441. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_RSA_N, &n);
  442. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_RSA_E, &e);
  443. #else
  444. RSA_get0_key(rsa, &n, &e, NULL);
  445. #endif /* HAVE_EVP_PKEY_GET_PARAMS */
  446. BIO_printf(mem, "%d", n ? BN_num_bits(n) : 0);
  447. #else
  448. BIO_printf(mem, "%d", rsa->n ? BN_num_bits(rsa->n) : 0);
  449. #endif /* HAVE_OPAQUE_RSA_DSA_DH */
  450. result = push_certinfo(data, mem, "RSA Public Key", i);
  451. if(result)
  452. break;
  453. print_pubkey_BN(rsa, n, i);
  454. print_pubkey_BN(rsa, e, i);
  455. FREE_PKEY_PARAM_BIGNUM(n);
  456. FREE_PKEY_PARAM_BIGNUM(e);
  457. }
  458. break;
  459. }
  460. case EVP_PKEY_DSA:
  461. {
  462. #ifndef OPENSSL_NO_DSA
  463. #ifndef HAVE_EVP_PKEY_GET_PARAMS
  464. DSA *dsa;
  465. #ifdef HAVE_OPAQUE_EVP_PKEY
  466. dsa = EVP_PKEY_get0_DSA(pubkey);
  467. #else
  468. dsa = pubkey->pkey.dsa;
  469. #endif /* HAVE_OPAQUE_EVP_PKEY */
  470. #endif /* !HAVE_EVP_PKEY_GET_PARAMS */
  471. {
  472. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  473. DECLARE_PKEY_PARAM_BIGNUM(p);
  474. DECLARE_PKEY_PARAM_BIGNUM(q);
  475. DECLARE_PKEY_PARAM_BIGNUM(g);
  476. DECLARE_PKEY_PARAM_BIGNUM(pub_key);
  477. #ifdef HAVE_EVP_PKEY_GET_PARAMS
  478. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_P, &p);
  479. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_Q, &q);
  480. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_G, &g);
  481. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_PUB_KEY, &pub_key);
  482. #else
  483. DSA_get0_pqg(dsa, &p, &q, &g);
  484. DSA_get0_key(dsa, &pub_key, NULL);
  485. #endif /* HAVE_EVP_PKEY_GET_PARAMS */
  486. #endif /* HAVE_OPAQUE_RSA_DSA_DH */
  487. print_pubkey_BN(dsa, p, i);
  488. print_pubkey_BN(dsa, q, i);
  489. print_pubkey_BN(dsa, g, i);
  490. print_pubkey_BN(dsa, pub_key, i);
  491. FREE_PKEY_PARAM_BIGNUM(p);
  492. FREE_PKEY_PARAM_BIGNUM(q);
  493. FREE_PKEY_PARAM_BIGNUM(g);
  494. FREE_PKEY_PARAM_BIGNUM(pub_key);
  495. }
  496. #endif /* !OPENSSL_NO_DSA */
  497. break;
  498. }
  499. case EVP_PKEY_DH: {
  500. #ifndef HAVE_EVP_PKEY_GET_PARAMS
  501. DH *dh;
  502. #ifdef HAVE_OPAQUE_EVP_PKEY
  503. dh = EVP_PKEY_get0_DH(pubkey);
  504. #else
  505. dh = pubkey->pkey.dh;
  506. #endif /* HAVE_OPAQUE_EVP_PKEY */
  507. #endif /* !HAVE_EVP_PKEY_GET_PARAMS */
  508. {
  509. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  510. DECLARE_PKEY_PARAM_BIGNUM(p);
  511. DECLARE_PKEY_PARAM_BIGNUM(q);
  512. DECLARE_PKEY_PARAM_BIGNUM(g);
  513. DECLARE_PKEY_PARAM_BIGNUM(pub_key);
  514. #ifdef HAVE_EVP_PKEY_GET_PARAMS
  515. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_P, &p);
  516. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_Q, &q);
  517. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_G, &g);
  518. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_PUB_KEY, &pub_key);
  519. #else
  520. DH_get0_pqg(dh, &p, &q, &g);
  521. DH_get0_key(dh, &pub_key, NULL);
  522. #endif /* HAVE_EVP_PKEY_GET_PARAMS */
  523. print_pubkey_BN(dh, p, i);
  524. print_pubkey_BN(dh, q, i);
  525. print_pubkey_BN(dh, g, i);
  526. #else
  527. print_pubkey_BN(dh, p, i);
  528. print_pubkey_BN(dh, g, i);
  529. #endif /* HAVE_OPAQUE_RSA_DSA_DH */
  530. print_pubkey_BN(dh, pub_key, i);
  531. FREE_PKEY_PARAM_BIGNUM(p);
  532. FREE_PKEY_PARAM_BIGNUM(q);
  533. FREE_PKEY_PARAM_BIGNUM(g);
  534. FREE_PKEY_PARAM_BIGNUM(pub_key);
  535. }
  536. break;
  537. }
  538. }
  539. EVP_PKEY_free(pubkey);
  540. }
  541. if(!result && psig) {
  542. for(j = 0; j < psig->length; j++)
  543. BIO_printf(mem, "%02x:", psig->data[j]);
  544. result = push_certinfo(data, mem, "Signature", i);
  545. }
  546. if(!result) {
  547. PEM_write_bio_X509(mem, x);
  548. result = push_certinfo(data, mem, "Cert", i);
  549. }
  550. }
  551. BIO_free(mem);
  552. if(result)
  553. /* cleanup all leftovers */
  554. Curl_ssl_free_certinfo(data);
  555. return result;
  556. }
  557. #endif /* quiche or OpenSSL */
  558. #ifdef USE_OPENSSL
  559. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  560. #define BIO_set_init(x,v) ((x)->init=(v))
  561. #define BIO_get_data(x) ((x)->ptr)
  562. #define BIO_set_data(x,v) ((x)->ptr=(v))
  563. #define BIO_get_shutdown(x) ((x)->shutdown)
  564. #define BIO_set_shutdown(x,v) ((x)->shutdown=(v))
  565. #endif /* HAVE_PRE_1_1_API */
  566. static int ossl_bio_cf_create(BIO *bio)
  567. {
  568. BIO_set_shutdown(bio, 1);
  569. BIO_set_init(bio, 1);
  570. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  571. bio->num = -1;
  572. #endif
  573. BIO_set_data(bio, NULL);
  574. return 1;
  575. }
  576. static int ossl_bio_cf_destroy(BIO *bio)
  577. {
  578. if(!bio)
  579. return 0;
  580. return 1;
  581. }
  582. static long ossl_bio_cf_ctrl(BIO *bio, int cmd, long num, void *ptr)
  583. {
  584. struct Curl_cfilter *cf = BIO_get_data(bio);
  585. long ret = 1;
  586. (void)cf;
  587. (void)ptr;
  588. switch(cmd) {
  589. case BIO_CTRL_GET_CLOSE:
  590. ret = (long)BIO_get_shutdown(bio);
  591. break;
  592. case BIO_CTRL_SET_CLOSE:
  593. BIO_set_shutdown(bio, (int)num);
  594. break;
  595. case BIO_CTRL_FLUSH:
  596. /* we do no delayed writes, but if we ever would, this
  597. * needs to trigger it. */
  598. ret = 1;
  599. break;
  600. case BIO_CTRL_DUP:
  601. ret = 1;
  602. break;
  603. case BIO_CTRL_EOF: {
  604. /* EOF has been reached on input? */
  605. struct ssl_connect_data *connssl = cf->ctx;
  606. return connssl->peer_closed;
  607. }
  608. default:
  609. ret = 0;
  610. break;
  611. }
  612. return ret;
  613. }
  614. static int ossl_bio_cf_out_write(BIO *bio, const char *buf, int blen)
  615. {
  616. struct Curl_cfilter *cf = BIO_get_data(bio);
  617. struct ssl_connect_data *connssl = cf->ctx;
  618. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  619. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  620. size_t nwritten;
  621. CURLcode result;
  622. DEBUGASSERT(data);
  623. if(blen < 0)
  624. return 0;
  625. result = Curl_conn_cf_send(cf->next, data, buf, (size_t)blen, FALSE,
  626. &nwritten);
  627. CURL_TRC_CF(data, cf, "ossl_bio_cf_out_write(len=%d) -> %d, %zu",
  628. blen, result, nwritten);
  629. BIO_clear_retry_flags(bio);
  630. octx->io_result = result;
  631. if(result) {
  632. if(CURLE_AGAIN == result)
  633. BIO_set_retry_write(bio);
  634. return -1;
  635. }
  636. return (int)nwritten;
  637. }
  638. static int ossl_bio_cf_in_read(BIO *bio, char *buf, int blen)
  639. {
  640. struct Curl_cfilter *cf = BIO_get_data(bio);
  641. struct ssl_connect_data *connssl = cf->ctx;
  642. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  643. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  644. size_t nread;
  645. CURLcode result, r2;
  646. DEBUGASSERT(data);
  647. /* OpenSSL catches this case, so should we. */
  648. if(!buf)
  649. return 0;
  650. if(blen < 0)
  651. return 0;
  652. result = Curl_conn_cf_recv(cf->next, data, buf, (size_t)blen, &nread);
  653. CURL_TRC_CF(data, cf, "ossl_bio_cf_in_read(len=%d) -> %d, %zu",
  654. blen, result, nread);
  655. BIO_clear_retry_flags(bio);
  656. octx->io_result = result;
  657. if(result) {
  658. if(CURLE_AGAIN == result)
  659. BIO_set_retry_read(bio);
  660. }
  661. else {
  662. /* feeding data to OpenSSL means SSL_read() might succeed */
  663. connssl->input_pending = TRUE;
  664. if(nread == 0)
  665. connssl->peer_closed = TRUE;
  666. }
  667. /* Before returning server replies to the SSL instance, we need
  668. * to have setup the x509 store or verification will fail. */
  669. if(!octx->x509_store_setup) {
  670. r2 = Curl_ssl_setup_x509_store(cf, data, octx);
  671. if(r2) {
  672. BIO_clear_retry_flags(bio);
  673. octx->io_result = r2;
  674. return -1;
  675. }
  676. octx->x509_store_setup = TRUE;
  677. }
  678. return result ? -1 : (int)nread;
  679. }
  680. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  681. static BIO_METHOD ossl_bio_cf_meth_1_0 = {
  682. BIO_TYPE_MEM,
  683. "OpenSSL CF BIO",
  684. ossl_bio_cf_out_write,
  685. ossl_bio_cf_in_read,
  686. NULL, /* puts is never called */
  687. NULL, /* gets is never called */
  688. ossl_bio_cf_ctrl,
  689. ossl_bio_cf_create,
  690. ossl_bio_cf_destroy,
  691. NULL
  692. };
  693. static BIO_METHOD *ossl_bio_cf_method_create(void)
  694. {
  695. return &ossl_bio_cf_meth_1_0;
  696. }
  697. #define ossl_bio_cf_method_free(m) Curl_nop_stmt
  698. #else
  699. static BIO_METHOD *ossl_bio_cf_method_create(void)
  700. {
  701. BIO_METHOD *m = BIO_meth_new(BIO_TYPE_MEM, "OpenSSL CF BIO");
  702. if(m) {
  703. BIO_meth_set_write(m, &ossl_bio_cf_out_write);
  704. BIO_meth_set_read(m, &ossl_bio_cf_in_read);
  705. BIO_meth_set_ctrl(m, &ossl_bio_cf_ctrl);
  706. BIO_meth_set_create(m, &ossl_bio_cf_create);
  707. BIO_meth_set_destroy(m, &ossl_bio_cf_destroy);
  708. }
  709. return m;
  710. }
  711. static void ossl_bio_cf_method_free(BIO_METHOD *m)
  712. {
  713. if(m)
  714. BIO_meth_free(m);
  715. }
  716. #endif
  717. #ifdef HAVE_KEYLOG_CALLBACK
  718. static void ossl_keylog_callback(const SSL *ssl, const char *line)
  719. {
  720. (void)ssl;
  721. Curl_tls_keylog_write_line(line);
  722. }
  723. #else
  724. /*
  725. * ossl_log_tls12_secret is called by libcurl to make the CLIENT_RANDOMs if the
  726. * OpenSSL being used does not have native support for doing that.
  727. */
  728. static void
  729. ossl_log_tls12_secret(const SSL *ssl, bool *keylog_done)
  730. {
  731. const SSL_SESSION *session;
  732. unsigned char client_random[SSL3_RANDOM_SIZE];
  733. unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
  734. int master_key_length = 0;
  735. ERR_set_mark();
  736. session = SSL_get_session(ssl);
  737. if(!session || *keylog_done) {
  738. ERR_pop_to_mark();
  739. return;
  740. }
  741. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  742. /* ssl->s3 is not checked in OpenSSL 1.1.0-pre6, but let's assume that
  743. * we have a valid SSL context if we have a non-NULL session. */
  744. SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE);
  745. master_key_length = (int)
  746. SSL_SESSION_get_master_key(session, master_key, SSL_MAX_MASTER_KEY_LENGTH);
  747. #else
  748. if(ssl->s3 && session->master_key_length > 0) {
  749. master_key_length = session->master_key_length;
  750. memcpy(master_key, session->master_key, session->master_key_length);
  751. memcpy(client_random, ssl->s3->client_random, SSL3_RANDOM_SIZE);
  752. }
  753. #endif
  754. ERR_pop_to_mark();
  755. /* The handshake has not progressed sufficiently yet, or this is a TLS 1.3
  756. * session (when curl was built with older OpenSSL headers and running with
  757. * newer OpenSSL runtime libraries). */
  758. if(master_key_length <= 0)
  759. return;
  760. *keylog_done = TRUE;
  761. Curl_tls_keylog_write("CLIENT_RANDOM", client_random,
  762. master_key, master_key_length);
  763. }
  764. #endif /* !HAVE_KEYLOG_CALLBACK */
  765. static const char *SSL_ERROR_to_str(int err)
  766. {
  767. switch(err) {
  768. case SSL_ERROR_NONE:
  769. return "SSL_ERROR_NONE";
  770. case SSL_ERROR_SSL:
  771. return "SSL_ERROR_SSL";
  772. case SSL_ERROR_WANT_READ:
  773. return "SSL_ERROR_WANT_READ";
  774. case SSL_ERROR_WANT_WRITE:
  775. return "SSL_ERROR_WANT_WRITE";
  776. case SSL_ERROR_WANT_X509_LOOKUP:
  777. return "SSL_ERROR_WANT_X509_LOOKUP";
  778. case SSL_ERROR_SYSCALL:
  779. return "SSL_ERROR_SYSCALL";
  780. case SSL_ERROR_ZERO_RETURN:
  781. return "SSL_ERROR_ZERO_RETURN";
  782. case SSL_ERROR_WANT_CONNECT:
  783. return "SSL_ERROR_WANT_CONNECT";
  784. case SSL_ERROR_WANT_ACCEPT:
  785. return "SSL_ERROR_WANT_ACCEPT";
  786. #ifdef SSL_ERROR_WANT_ASYNC /* OpenSSL 1.1.0+, LibreSSL 3.6.0+ */
  787. case SSL_ERROR_WANT_ASYNC:
  788. return "SSL_ERROR_WANT_ASYNC";
  789. #endif
  790. #ifdef SSL_ERROR_WANT_ASYNC_JOB /* OpenSSL 1.1.0+, LibreSSL 3.6.0+ */
  791. case SSL_ERROR_WANT_ASYNC_JOB:
  792. return "SSL_ERROR_WANT_ASYNC_JOB";
  793. #endif
  794. #ifdef SSL_ERROR_WANT_CLIENT_HELLO_CB /* OpenSSL 1.1.1, LibreSSL 3.6.0+ */
  795. case SSL_ERROR_WANT_CLIENT_HELLO_CB:
  796. return "SSL_ERROR_WANT_CLIENT_HELLO_CB";
  797. #endif
  798. default:
  799. return "SSL_ERROR unknown";
  800. }
  801. }
  802. /* Return error string for last OpenSSL error
  803. */
  804. static char *ossl_strerror(unsigned long error, char *buf, size_t size)
  805. {
  806. size_t len;
  807. DEBUGASSERT(size);
  808. *buf = '\0';
  809. len = Curl_ossl_version(buf, size);
  810. DEBUGASSERT(len < (size - 2));
  811. if(len < (size - 2)) {
  812. buf += len;
  813. size -= (len + 2);
  814. *buf++ = ':';
  815. *buf++ = ' ';
  816. *buf = '\0';
  817. }
  818. #ifdef HAVE_BORINGSSL_LIKE
  819. ERR_error_string_n((uint32_t)error, buf, size);
  820. #else
  821. ERR_error_string_n(error, buf, size);
  822. #endif
  823. if(!*buf) {
  824. const char *msg = error ? "Unknown error" : "No error";
  825. if(strlen(msg) < size)
  826. strcpy(buf, msg);
  827. }
  828. return buf;
  829. }
  830. static int passwd_callback(char *buf, int num, int encrypting,
  831. void *password)
  832. {
  833. DEBUGASSERT(encrypting == 0);
  834. if(!encrypting && num >= 0 && password) {
  835. int klen = curlx_uztosi(strlen((char *)password));
  836. if(num > klen) {
  837. memcpy(buf, password, klen + 1);
  838. return klen;
  839. }
  840. }
  841. return 0;
  842. }
  843. /*
  844. * rand_enough() returns TRUE if we have seeded the random engine properly.
  845. */
  846. static bool rand_enough(void)
  847. {
  848. return RAND_status() != 0;
  849. }
  850. static CURLcode ossl_seed(struct Curl_easy *data)
  851. {
  852. /* This might get called before it has been added to a multi handle */
  853. if(data->multi && data->multi->ssl_seeded)
  854. return CURLE_OK;
  855. if(rand_enough()) {
  856. /* OpenSSL 1.1.0+ should return here */
  857. if(data->multi)
  858. data->multi->ssl_seeded = TRUE;
  859. return CURLE_OK;
  860. }
  861. #ifdef HAVE_RANDOM_INIT_BY_DEFAULT
  862. /* with OpenSSL 1.1.0+, a failed RAND_status is a showstopper */
  863. failf(data, "Insufficient randomness");
  864. return CURLE_SSL_CONNECT_ERROR;
  865. #else
  866. /* fallback to a custom seeding of the PRNG using a hash based on a current
  867. time */
  868. do {
  869. unsigned char randb[64];
  870. size_t len = sizeof(randb);
  871. size_t i, i_max;
  872. for(i = 0, i_max = len / sizeof(struct curltime); i < i_max; ++i) {
  873. struct curltime tv = curlx_now();
  874. curlx_wait_ms(1);
  875. tv.tv_sec *= (time_t)i + 1;
  876. tv.tv_usec *= (int)i + 2;
  877. tv.tv_sec ^= ((curlx_now().tv_sec + (time_t)curlx_now().tv_usec) *
  878. (time_t)(i + 3)) << 8;
  879. tv.tv_usec ^= (int) ((curlx_now().tv_sec + (time_t)curlx_now().tv_usec) *
  880. (time_t)(i + 4)) << 16;
  881. memcpy(&randb[i * sizeof(struct curltime)], &tv,
  882. sizeof(struct curltime));
  883. }
  884. RAND_add(randb, (int)len, (double)len/2);
  885. } while(!rand_enough());
  886. /*
  887. * Number of bytes to read from the random number seed file. This must be
  888. * a finite value (because some entropy "files" like /dev/urandom have
  889. * an infinite length), but must be large enough to provide enough
  890. * entropy to properly seed OpenSSL's PRNG.
  891. */
  892. # define RAND_LOAD_LENGTH 1024
  893. {
  894. /* generates a default path for the random seed file */
  895. char fname[256];
  896. fname[0] = 0; /* blank it first */
  897. RAND_file_name(fname, sizeof(fname));
  898. if(fname[0]) {
  899. /* we got a filename to try */
  900. RAND_load_file(fname, RAND_LOAD_LENGTH);
  901. if(rand_enough())
  902. return CURLE_OK;
  903. }
  904. }
  905. infof(data, "libcurl is now using a weak random seed");
  906. return rand_enough() ? CURLE_OK :
  907. CURLE_SSL_CONNECT_ERROR; /* confusing error code */
  908. #endif
  909. }
  910. #ifndef SSL_FILETYPE_ENGINE
  911. #define SSL_FILETYPE_ENGINE 42
  912. #endif
  913. #ifndef SSL_FILETYPE_PKCS12
  914. #define SSL_FILETYPE_PKCS12 43
  915. #endif
  916. #ifndef SSL_FILETYPE_PROVIDER
  917. #define SSL_FILETYPE_PROVIDER 44
  918. #endif
  919. static int ossl_do_file_type(const char *type)
  920. {
  921. if(!type || !type[0])
  922. return SSL_FILETYPE_PEM;
  923. if(curl_strequal(type, "PEM"))
  924. return SSL_FILETYPE_PEM;
  925. if(curl_strequal(type, "DER"))
  926. return SSL_FILETYPE_ASN1;
  927. if(curl_strequal(type, "PROV"))
  928. return SSL_FILETYPE_PROVIDER;
  929. if(curl_strequal(type, "ENG"))
  930. return SSL_FILETYPE_ENGINE;
  931. if(curl_strequal(type, "P12"))
  932. return SSL_FILETYPE_PKCS12;
  933. return -1;
  934. }
  935. #if defined(USE_OPENSSL_ENGINE) || defined(OPENSSL_HAS_PROVIDERS)
  936. /*
  937. * Supply default password to the engine user interface conversation.
  938. * The password is passed by OpenSSL engine from ENGINE_load_private_key()
  939. * last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
  940. */
  941. static int ssl_ui_reader(UI *ui, UI_STRING *uis)
  942. {
  943. const char *password;
  944. switch(UI_get_string_type(uis)) {
  945. case UIT_PROMPT:
  946. case UIT_VERIFY:
  947. password = (const char *)UI_get0_user_data(ui);
  948. if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
  949. UI_set_result(ui, uis, password);
  950. return 1;
  951. }
  952. FALLTHROUGH();
  953. default:
  954. break;
  955. }
  956. return (UI_method_get_reader(UI_OpenSSL()))(ui, uis);
  957. }
  958. /*
  959. * Suppress interactive request for a default password if available.
  960. */
  961. static int ssl_ui_writer(UI *ui, UI_STRING *uis)
  962. {
  963. switch(UI_get_string_type(uis)) {
  964. case UIT_PROMPT:
  965. case UIT_VERIFY:
  966. if(UI_get0_user_data(ui) &&
  967. (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
  968. return 1;
  969. }
  970. FALLTHROUGH();
  971. default:
  972. break;
  973. }
  974. return (UI_method_get_writer(UI_OpenSSL()))(ui, uis);
  975. }
  976. /*
  977. * Check if a given string is a PKCS#11 URI
  978. */
  979. static bool is_pkcs11_uri(const char *string)
  980. {
  981. return string && curl_strnequal(string, "pkcs11:", 7);
  982. }
  983. #endif
  984. static CURLcode ossl_set_engine(struct Curl_easy *data, const char *engine);
  985. #ifdef OPENSSL_HAS_PROVIDERS
  986. static CURLcode ossl_set_provider(struct Curl_easy *data,
  987. const char *provider);
  988. #endif
  989. static int use_certificate_blob(SSL_CTX *ctx, const struct curl_blob *blob,
  990. int type, const char *key_passwd)
  991. {
  992. int ret = 0;
  993. X509 *x = NULL;
  994. /* the typecast of blob->len is fine since it is guaranteed to never be
  995. larger than CURL_MAX_INPUT_LENGTH */
  996. BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len));
  997. if(!in)
  998. return CURLE_OUT_OF_MEMORY;
  999. if(type == SSL_FILETYPE_ASN1) {
  1000. /* j = ERR_R_ASN1_LIB; */
  1001. x = d2i_X509_bio(in, NULL);
  1002. }
  1003. else if(type == SSL_FILETYPE_PEM) {
  1004. /* ERR_R_PEM_LIB; */
  1005. x = PEM_read_bio_X509(in, NULL,
  1006. passwd_callback, CURL_UNCONST(key_passwd));
  1007. }
  1008. else {
  1009. ret = 0;
  1010. goto end;
  1011. }
  1012. if(!x) {
  1013. ret = 0;
  1014. goto end;
  1015. }
  1016. ret = SSL_CTX_use_certificate(ctx, x);
  1017. end:
  1018. X509_free(x);
  1019. BIO_free(in);
  1020. return ret;
  1021. }
  1022. static int use_privatekey_blob(SSL_CTX *ctx, const struct curl_blob *blob,
  1023. int type, const char *key_passwd)
  1024. {
  1025. int ret = 0;
  1026. EVP_PKEY *pkey = NULL;
  1027. BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len));
  1028. if(!in)
  1029. return CURLE_OUT_OF_MEMORY;
  1030. if(type == SSL_FILETYPE_PEM)
  1031. pkey = PEM_read_bio_PrivateKey(in, NULL, passwd_callback,
  1032. CURL_UNCONST(key_passwd));
  1033. else if(type == SSL_FILETYPE_ASN1)
  1034. pkey = d2i_PrivateKey_bio(in, NULL);
  1035. else
  1036. goto end;
  1037. if(!pkey)
  1038. goto end;
  1039. ret = SSL_CTX_use_PrivateKey(ctx, pkey);
  1040. EVP_PKEY_free(pkey);
  1041. end:
  1042. BIO_free(in);
  1043. return ret;
  1044. }
  1045. static int
  1046. use_certificate_chain_blob(SSL_CTX *ctx, const struct curl_blob *blob,
  1047. const char *key_passwd)
  1048. {
  1049. int ret = 0;
  1050. X509 *x = NULL;
  1051. BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len));
  1052. if(!in)
  1053. return CURLE_OUT_OF_MEMORY;
  1054. ERR_clear_error();
  1055. x = PEM_read_bio_X509_AUX(in, NULL,
  1056. passwd_callback, CURL_UNCONST(key_passwd));
  1057. if(!x)
  1058. goto end;
  1059. ret = SSL_CTX_use_certificate(ctx, x);
  1060. if(ERR_peek_error() != 0)
  1061. ret = 0;
  1062. if(ret) {
  1063. X509 *ca;
  1064. sslerr_t err;
  1065. if(!SSL_CTX_clear_chain_certs(ctx)) {
  1066. ret = 0;
  1067. goto end;
  1068. }
  1069. while((ca = PEM_read_bio_X509(in, NULL, passwd_callback,
  1070. CURL_UNCONST(key_passwd)))
  1071. != NULL) {
  1072. if(!SSL_CTX_add0_chain_cert(ctx, ca)) {
  1073. X509_free(ca);
  1074. ret = 0;
  1075. goto end;
  1076. }
  1077. }
  1078. err = ERR_peek_last_error();
  1079. if((ERR_GET_LIB(err) == ERR_LIB_PEM) &&
  1080. (ERR_GET_REASON(err) == PEM_R_NO_START_LINE))
  1081. ERR_clear_error();
  1082. else
  1083. ret = 0;
  1084. }
  1085. end:
  1086. X509_free(x);
  1087. BIO_free(in);
  1088. return ret;
  1089. }
  1090. static int enginecheck(struct Curl_easy *data,
  1091. SSL_CTX* ctx,
  1092. const char *key_file,
  1093. const char *key_passwd)
  1094. #ifdef USE_OPENSSL_ENGINE
  1095. {
  1096. EVP_PKEY *priv_key = NULL;
  1097. /* Implicitly use pkcs11 engine if none was provided and the
  1098. * key_file is a PKCS#11 URI */
  1099. if(!data->state.engine) {
  1100. if(is_pkcs11_uri(key_file)) {
  1101. if(ossl_set_engine(data, "pkcs11") != CURLE_OK) {
  1102. return 0;
  1103. }
  1104. }
  1105. }
  1106. if(data->state.engine) {
  1107. UI_METHOD *ui_method =
  1108. UI_create_method(OSSL_UI_METHOD_CAST("curl user interface"));
  1109. if(!ui_method) {
  1110. failf(data, "unable to create " OSSL_PACKAGE " user-interface method");
  1111. return 0;
  1112. }
  1113. UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
  1114. UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
  1115. UI_method_set_reader(ui_method, ssl_ui_reader);
  1116. UI_method_set_writer(ui_method, ssl_ui_writer);
  1117. priv_key = ENGINE_load_private_key(data->state.engine, key_file,
  1118. ui_method,
  1119. CURL_UNCONST(key_passwd));
  1120. UI_destroy_method(ui_method);
  1121. if(!priv_key) {
  1122. failf(data, "failed to load private key from crypto engine");
  1123. return 0;
  1124. }
  1125. if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
  1126. failf(data, "unable to set private key");
  1127. EVP_PKEY_free(priv_key);
  1128. return 0;
  1129. }
  1130. EVP_PKEY_free(priv_key); /* we do not need the handle any more... */
  1131. }
  1132. else {
  1133. failf(data, "crypto engine not set, cannot load private key");
  1134. return 0;
  1135. }
  1136. return 1;
  1137. }
  1138. #else
  1139. {
  1140. (void)ctx;
  1141. (void)key_file;
  1142. (void)key_passwd;
  1143. failf(data, "SSL_FILETYPE_ENGINE not supported for private key");
  1144. return 0;
  1145. }
  1146. #endif
  1147. static int providercheck(struct Curl_easy *data,
  1148. SSL_CTX* ctx,
  1149. const char *key_file)
  1150. #ifdef OPENSSL_HAS_PROVIDERS
  1151. {
  1152. char error_buffer[256];
  1153. /* Implicitly use pkcs11 provider if none was provided and the
  1154. * key_file is a PKCS#11 URI */
  1155. if(!data->state.provider_loaded) {
  1156. if(is_pkcs11_uri(key_file)) {
  1157. if(ossl_set_provider(data, "pkcs11") != CURLE_OK) {
  1158. return 0;
  1159. }
  1160. }
  1161. }
  1162. if(data->state.provider_loaded) {
  1163. /* Load the private key from the provider */
  1164. EVP_PKEY *priv_key = NULL;
  1165. OSSL_STORE_CTX *store = NULL;
  1166. OSSL_STORE_INFO *info = NULL;
  1167. UI_METHOD *ui_method =
  1168. UI_create_method(OSSL_UI_METHOD_CAST("curl user interface"));
  1169. if(!ui_method) {
  1170. failf(data, "unable to create " OSSL_PACKAGE " user-interface method");
  1171. return 0;
  1172. }
  1173. UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
  1174. UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
  1175. UI_method_set_reader(ui_method, ssl_ui_reader);
  1176. UI_method_set_writer(ui_method, ssl_ui_writer);
  1177. store = OSSL_STORE_open_ex(key_file, data->state.libctx,
  1178. data->state.propq, ui_method, NULL, NULL,
  1179. NULL, NULL);
  1180. if(!store) {
  1181. failf(data, "Failed to open OpenSSL store: %s",
  1182. ossl_strerror(ERR_get_error(), error_buffer,
  1183. sizeof(error_buffer)));
  1184. UI_destroy_method(ui_method);
  1185. return 0;
  1186. }
  1187. if(OSSL_STORE_expect(store, OSSL_STORE_INFO_PKEY) != 1) {
  1188. failf(data, "Failed to set store preference. Ignoring the error: %s",
  1189. ossl_strerror(ERR_get_error(), error_buffer,
  1190. sizeof(error_buffer)));
  1191. }
  1192. info = OSSL_STORE_load(store);
  1193. if(info) {
  1194. int ossl_type = OSSL_STORE_INFO_get_type(info);
  1195. if(ossl_type == OSSL_STORE_INFO_PKEY)
  1196. priv_key = OSSL_STORE_INFO_get1_PKEY(info);
  1197. OSSL_STORE_INFO_free(info);
  1198. }
  1199. OSSL_STORE_close(store);
  1200. UI_destroy_method(ui_method);
  1201. if(!priv_key) {
  1202. failf(data, "No private key found in the openssl store: %s",
  1203. ossl_strerror(ERR_get_error(), error_buffer,
  1204. sizeof(error_buffer)));
  1205. return 0;
  1206. }
  1207. if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
  1208. failf(data, "unable to set private key [%s]",
  1209. ossl_strerror(ERR_get_error(), error_buffer,
  1210. sizeof(error_buffer)));
  1211. EVP_PKEY_free(priv_key);
  1212. return 0;
  1213. }
  1214. EVP_PKEY_free(priv_key); /* we do not need the handle any more... */
  1215. }
  1216. else {
  1217. failf(data, "crypto provider not set, cannot load private key");
  1218. return 0;
  1219. }
  1220. return 1;
  1221. }
  1222. #else
  1223. {
  1224. (void)ctx;
  1225. (void)key_file;
  1226. failf(data, "SSL_FILETYPE_PROVIDER not supported for private key");
  1227. return 0;
  1228. }
  1229. #endif
  1230. static int engineload(struct Curl_easy *data,
  1231. SSL_CTX* ctx,
  1232. const char *cert_file)
  1233. /* ENGINE_CTRL_GET_CMD_FROM_NAME supported by OpenSSL, LibreSSL <=3.8.3 */
  1234. #if defined(USE_OPENSSL_ENGINE) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
  1235. {
  1236. char error_buffer[256];
  1237. /* Implicitly use pkcs11 engine if none was provided and the
  1238. * cert_file is a PKCS#11 URI */
  1239. if(!data->state.engine) {
  1240. if(is_pkcs11_uri(cert_file)) {
  1241. if(ossl_set_engine(data, "pkcs11") != CURLE_OK) {
  1242. return 0;
  1243. }
  1244. }
  1245. }
  1246. if(data->state.engine) {
  1247. const char *cmd_name = "LOAD_CERT_CTRL";
  1248. struct {
  1249. const char *cert_id;
  1250. X509 *cert;
  1251. } params;
  1252. params.cert_id = cert_file;
  1253. params.cert = NULL;
  1254. /* Does the engine supports LOAD_CERT_CTRL ? */
  1255. if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
  1256. 0, CURL_UNCONST(cmd_name), NULL)) {
  1257. failf(data, "ssl engine does not support loading certificates");
  1258. return 0;
  1259. }
  1260. /* Load the certificate from the engine */
  1261. if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
  1262. 0, &params, NULL, 1)) {
  1263. failf(data, "ssl engine cannot load client cert with id"
  1264. " '%s' [%s]", cert_file,
  1265. ossl_strerror(ERR_get_error(), error_buffer,
  1266. sizeof(error_buffer)));
  1267. return 0;
  1268. }
  1269. if(!params.cert) {
  1270. failf(data, "ssl engine did not initialized the certificate "
  1271. "properly.");
  1272. return 0;
  1273. }
  1274. if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
  1275. failf(data, "unable to set client certificate [%s]",
  1276. ossl_strerror(ERR_get_error(), error_buffer,
  1277. sizeof(error_buffer)));
  1278. return 0;
  1279. }
  1280. X509_free(params.cert); /* we do not need the handle any more... */
  1281. }
  1282. else {
  1283. failf(data, "crypto engine not set, cannot load certificate");
  1284. return 0;
  1285. }
  1286. return 1;
  1287. }
  1288. #else
  1289. {
  1290. (void)ctx;
  1291. (void)cert_file;
  1292. failf(data, "SSL_FILETYPE_ENGINE not supported for certificate");
  1293. return 0;
  1294. }
  1295. #endif
  1296. static int providerload(struct Curl_easy *data,
  1297. SSL_CTX* ctx,
  1298. const char *cert_file)
  1299. #ifdef OPENSSL_HAS_PROVIDERS
  1300. {
  1301. char error_buffer[256];
  1302. /* Implicitly use pkcs11 provider if none was provided and the
  1303. * cert_file is a PKCS#11 URI */
  1304. if(!data->state.provider_loaded) {
  1305. if(is_pkcs11_uri(cert_file)) {
  1306. if(ossl_set_provider(data, "pkcs11") != CURLE_OK) {
  1307. return 0;
  1308. }
  1309. }
  1310. }
  1311. if(data->state.provider_loaded) {
  1312. /* Load the certificate from the provider */
  1313. OSSL_STORE_INFO *info = NULL;
  1314. X509 *cert = NULL;
  1315. OSSL_STORE_CTX *store =
  1316. OSSL_STORE_open_ex(cert_file, data->state.libctx,
  1317. NULL, NULL, NULL, NULL, NULL, NULL);
  1318. int rc;
  1319. if(!store) {
  1320. failf(data, "Failed to open OpenSSL store: %s",
  1321. ossl_strerror(ERR_get_error(), error_buffer,
  1322. sizeof(error_buffer)));
  1323. return 0;
  1324. }
  1325. if(OSSL_STORE_expect(store, OSSL_STORE_INFO_CERT) != 1) {
  1326. failf(data, "Failed to set store preference. Ignoring the error: %s",
  1327. ossl_strerror(ERR_get_error(), error_buffer,
  1328. sizeof(error_buffer)));
  1329. }
  1330. info = OSSL_STORE_load(store);
  1331. if(info) {
  1332. int ossl_type = OSSL_STORE_INFO_get_type(info);
  1333. if(ossl_type == OSSL_STORE_INFO_CERT)
  1334. cert = OSSL_STORE_INFO_get1_CERT(info);
  1335. OSSL_STORE_INFO_free(info);
  1336. }
  1337. OSSL_STORE_close(store);
  1338. if(!cert) {
  1339. failf(data, "No cert found in the openssl store: %s",
  1340. ossl_strerror(ERR_get_error(), error_buffer,
  1341. sizeof(error_buffer)));
  1342. return 0;
  1343. }
  1344. rc = SSL_CTX_use_certificate(ctx, cert);
  1345. X509_free(cert); /* we do not need the handle any more... */
  1346. if(rc != 1) {
  1347. failf(data, "unable to set client certificate [%s]",
  1348. ossl_strerror(ERR_get_error(), error_buffer,
  1349. sizeof(error_buffer)));
  1350. return 0;
  1351. }
  1352. }
  1353. else {
  1354. failf(data, "crypto provider not set, cannot load certificate");
  1355. return 0;
  1356. }
  1357. return 1;
  1358. }
  1359. #else
  1360. {
  1361. (void)ctx;
  1362. (void)cert_file;
  1363. failf(data, "SSL_FILETYPE_PROVIDER not supported for certificate");
  1364. return 0;
  1365. }
  1366. #endif
  1367. static int pkcs12load(struct Curl_easy *data,
  1368. SSL_CTX* ctx,
  1369. const struct curl_blob *cert_blob,
  1370. const char *cert_file,
  1371. const char *key_passwd)
  1372. {
  1373. char error_buffer[256];
  1374. BIO *cert_bio = NULL;
  1375. PKCS12 *p12 = NULL;
  1376. EVP_PKEY *pri;
  1377. X509 *x509;
  1378. int cert_done = 0;
  1379. STACK_OF(X509) *ca = NULL;
  1380. if(cert_blob) {
  1381. cert_bio = BIO_new_mem_buf(cert_blob->data, (int)(cert_blob->len));
  1382. if(!cert_bio) {
  1383. failf(data,
  1384. "BIO_new_mem_buf NULL, " OSSL_PACKAGE " error %s",
  1385. ossl_strerror(ERR_get_error(), error_buffer,
  1386. sizeof(error_buffer)) );
  1387. return 0;
  1388. }
  1389. }
  1390. else {
  1391. cert_bio = BIO_new(BIO_s_file());
  1392. if(!cert_bio) {
  1393. failf(data,
  1394. "BIO_new return NULL, " OSSL_PACKAGE " error %s",
  1395. ossl_strerror(ERR_get_error(), error_buffer,
  1396. sizeof(error_buffer)) );
  1397. return 0;
  1398. }
  1399. if(BIO_read_filename(cert_bio, CURL_UNCONST(cert_file)) <= 0) {
  1400. failf(data, "could not open PKCS12 file '%s'", cert_file);
  1401. BIO_free(cert_bio);
  1402. return 0;
  1403. }
  1404. }
  1405. p12 = d2i_PKCS12_bio(cert_bio, NULL);
  1406. BIO_free(cert_bio);
  1407. if(!p12) {
  1408. failf(data, "error reading PKCS12 file '%s'",
  1409. cert_blob ? "(memory blob)" : cert_file);
  1410. return 0;
  1411. }
  1412. if(!PKCS12_parse(p12, key_passwd, &pri, &x509, &ca)) {
  1413. failf(data,
  1414. "could not parse PKCS12 file, check password, " OSSL_PACKAGE
  1415. " error %s",
  1416. ossl_strerror(ERR_get_error(), error_buffer,
  1417. sizeof(error_buffer)) );
  1418. PKCS12_free(p12);
  1419. return 0;
  1420. }
  1421. PKCS12_free(p12);
  1422. if(SSL_CTX_use_certificate(ctx, x509) != 1) {
  1423. failf(data,
  1424. "could not load PKCS12 client certificate, " OSSL_PACKAGE
  1425. " error %s",
  1426. ossl_strerror(ERR_get_error(), error_buffer,
  1427. sizeof(error_buffer)) );
  1428. goto fail;
  1429. }
  1430. if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
  1431. failf(data, "unable to use private key from PKCS12 file '%s'",
  1432. cert_file);
  1433. goto fail;
  1434. }
  1435. if(!SSL_CTX_check_private_key(ctx)) {
  1436. failf(data, "private key from PKCS12 file '%s' "
  1437. "does not match certificate in same file", cert_file);
  1438. goto fail;
  1439. }
  1440. /* Set Certificate Verification chain */
  1441. if(ca) {
  1442. while(sk_X509_num(ca)) {
  1443. /*
  1444. * Note that sk_X509_pop() is used below to make sure the cert is
  1445. * removed from the stack properly before getting passed to
  1446. * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously
  1447. * we used sk_X509_value() instead, but then we would clean it in the
  1448. * subsequent sk_X509_pop_free() call.
  1449. */
  1450. X509 *x = sk_X509_pop(ca);
  1451. if(!SSL_CTX_add_client_CA(ctx, x)) {
  1452. X509_free(x);
  1453. failf(data, "cannot add certificate to client CA list");
  1454. goto fail;
  1455. }
  1456. if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
  1457. X509_free(x);
  1458. failf(data, "cannot add certificate to certificate chain");
  1459. goto fail;
  1460. }
  1461. }
  1462. }
  1463. cert_done = 1;
  1464. fail:
  1465. EVP_PKEY_free(pri);
  1466. X509_free(x509);
  1467. #if defined(__clang__) && __clang_major__ >= 16
  1468. #pragma clang diagnostic push
  1469. #pragma clang diagnostic ignored "-Wcast-function-type-strict"
  1470. #endif
  1471. sk_X509_pop_free(ca, X509_free);
  1472. #if defined(__clang__) && __clang_major__ >= 16
  1473. #pragma clang diagnostic pop
  1474. #endif
  1475. if(!cert_done)
  1476. return 0; /* failure! */
  1477. return 1;
  1478. }
  1479. static CURLcode client_cert(struct Curl_easy *data,
  1480. SSL_CTX* ctx,
  1481. char *cert_file,
  1482. const struct curl_blob *cert_blob,
  1483. const char *cert_type,
  1484. char *key_file,
  1485. const struct curl_blob *key_blob,
  1486. const char *key_type,
  1487. char *key_passwd)
  1488. {
  1489. char error_buffer[256];
  1490. bool check_privkey = TRUE;
  1491. int file_type = ossl_do_file_type(cert_type);
  1492. if(cert_file || cert_blob || (file_type == SSL_FILETYPE_ENGINE) ||
  1493. (file_type == SSL_FILETYPE_PROVIDER)) {
  1494. SSL *ssl;
  1495. X509 *x509;
  1496. bool pcks12_done = FALSE;
  1497. int cert_use_result;
  1498. if(key_passwd) {
  1499. /* set the password in the callback userdata */
  1500. SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd);
  1501. /* Set passwd callback: */
  1502. SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
  1503. }
  1504. switch(file_type) {
  1505. case SSL_FILETYPE_PEM:
  1506. /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
  1507. cert_use_result = cert_blob ?
  1508. use_certificate_chain_blob(ctx, cert_blob, key_passwd) :
  1509. SSL_CTX_use_certificate_chain_file(ctx, cert_file);
  1510. if(cert_use_result != 1) {
  1511. failf(data,
  1512. "could not load PEM client certificate from %s, " OSSL_PACKAGE
  1513. " error %s, "
  1514. "(no key found, wrong pass phrase, or wrong file format?)",
  1515. (cert_blob ? "CURLOPT_SSLCERT_BLOB" : cert_file),
  1516. ossl_strerror(ERR_get_error(), error_buffer,
  1517. sizeof(error_buffer)) );
  1518. return CURLE_SSL_CERTPROBLEM;
  1519. }
  1520. break;
  1521. case SSL_FILETYPE_ASN1:
  1522. /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
  1523. we use the case above for PEM so this can only be performed with
  1524. ASN1 files. */
  1525. cert_use_result = cert_blob ?
  1526. use_certificate_blob(ctx, cert_blob, file_type, key_passwd) :
  1527. SSL_CTX_use_certificate_file(ctx, cert_file, file_type);
  1528. if(cert_use_result != 1) {
  1529. failf(data,
  1530. "could not load ASN1 client certificate from %s, " OSSL_PACKAGE
  1531. " error %s, "
  1532. "(no key found, wrong pass phrase, or wrong file format?)",
  1533. (cert_blob ? "CURLOPT_SSLCERT_BLOB" : cert_file),
  1534. ossl_strerror(ERR_get_error(), error_buffer,
  1535. sizeof(error_buffer)) );
  1536. return CURLE_SSL_CERTPROBLEM;
  1537. }
  1538. break;
  1539. case SSL_FILETYPE_ENGINE:
  1540. if(!cert_file || !engineload(data, ctx, cert_file))
  1541. return CURLE_SSL_CERTPROBLEM;
  1542. break;
  1543. case SSL_FILETYPE_PROVIDER:
  1544. if(!cert_file || !providerload(data, ctx, cert_file))
  1545. return CURLE_SSL_CERTPROBLEM;
  1546. break;
  1547. case SSL_FILETYPE_PKCS12:
  1548. if(!pkcs12load(data, ctx, cert_blob, cert_file, key_passwd))
  1549. return CURLE_SSL_CERTPROBLEM;
  1550. pcks12_done = TRUE;
  1551. break;
  1552. default:
  1553. failf(data, "not supported file type '%s' for certificate", cert_type);
  1554. return CURLE_BAD_FUNCTION_ARGUMENT;
  1555. }
  1556. if((!key_file) && (!key_blob)) {
  1557. key_file = cert_file;
  1558. key_blob = cert_blob;
  1559. }
  1560. else
  1561. file_type = ossl_do_file_type(key_type);
  1562. switch(file_type) {
  1563. case SSL_FILETYPE_PEM:
  1564. case SSL_FILETYPE_ASN1:
  1565. cert_use_result = key_blob ?
  1566. use_privatekey_blob(ctx, key_blob, file_type, key_passwd) :
  1567. SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type);
  1568. if(cert_use_result != 1) {
  1569. failf(data, "unable to set private key file: '%s' type %s",
  1570. key_file ? key_file : "(memory blob)",
  1571. key_type ? key_type : "PEM");
  1572. return CURLE_BAD_FUNCTION_ARGUMENT;
  1573. }
  1574. break;
  1575. case SSL_FILETYPE_ENGINE:
  1576. if(!enginecheck(data, ctx, key_file, key_passwd))
  1577. return CURLE_SSL_CERTPROBLEM;
  1578. break;
  1579. case SSL_FILETYPE_PROVIDER:
  1580. if(!providercheck(data, ctx, key_file))
  1581. return CURLE_SSL_CERTPROBLEM;
  1582. break;
  1583. case SSL_FILETYPE_PKCS12:
  1584. if(!pcks12_done) {
  1585. failf(data, "file type P12 for private key not supported");
  1586. return CURLE_SSL_CERTPROBLEM;
  1587. }
  1588. break;
  1589. default:
  1590. failf(data, "not supported file type for private key");
  1591. return CURLE_BAD_FUNCTION_ARGUMENT;
  1592. }
  1593. ssl = SSL_new(ctx);
  1594. if(!ssl) {
  1595. failf(data, "unable to create an SSL structure");
  1596. return CURLE_OUT_OF_MEMORY;
  1597. }
  1598. x509 = SSL_get_certificate(ssl);
  1599. if(x509) {
  1600. EVP_PKEY *pktmp = X509_get_pubkey(x509);
  1601. EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl));
  1602. EVP_PKEY_free(pktmp);
  1603. }
  1604. #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
  1605. {
  1606. /* If RSA is used, do not check the private key if its flags indicate
  1607. * it does not support it. */
  1608. EVP_PKEY *priv_key = SSL_get_privatekey(ssl);
  1609. int pktype;
  1610. #ifdef HAVE_OPAQUE_EVP_PKEY
  1611. pktype = EVP_PKEY_id(priv_key);
  1612. #else
  1613. pktype = priv_key->type;
  1614. #endif
  1615. if(pktype == EVP_PKEY_RSA) {
  1616. RSA *rsa = EVP_PKEY_get1_RSA(priv_key);
  1617. if(RSA_flags(rsa) & RSA_METHOD_FLAG_NO_CHECK)
  1618. check_privkey = FALSE;
  1619. RSA_free(rsa); /* Decrement reference count */
  1620. }
  1621. }
  1622. #endif
  1623. SSL_free(ssl);
  1624. /* If we are using DSA, we can copy the parameters from
  1625. * the private key */
  1626. if(check_privkey == TRUE) {
  1627. /* Now we know that a key and cert have been set against
  1628. * the SSL context */
  1629. if(!SSL_CTX_check_private_key(ctx)) {
  1630. failf(data, "Private key does not match the certificate public key");
  1631. return CURLE_SSL_CERTPROBLEM;
  1632. }
  1633. }
  1634. }
  1635. return CURLE_OK;
  1636. }
  1637. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1638. /* returns non-zero on failure */
  1639. static CURLcode x509_name_oneline(X509_NAME *a, struct dynbuf *d)
  1640. {
  1641. BIO *bio_out = BIO_new(BIO_s_mem());
  1642. BUF_MEM *biomem;
  1643. int rc;
  1644. CURLcode result = CURLE_OUT_OF_MEMORY;
  1645. if(bio_out) {
  1646. unsigned long flags = XN_FLAG_SEP_SPLUS_SPC |
  1647. (XN_FLAG_ONELINE & ~ASN1_STRFLGS_ESC_MSB & ~XN_FLAG_SPC_EQ);
  1648. curlx_dyn_reset(d);
  1649. rc = X509_NAME_print_ex(bio_out, a, 0, flags);
  1650. if(rc != -1) {
  1651. BIO_get_mem_ptr(bio_out, &biomem);
  1652. result = curlx_dyn_addn(d, biomem->data, biomem->length);
  1653. BIO_free(bio_out);
  1654. }
  1655. }
  1656. return result;
  1657. }
  1658. #endif
  1659. /**
  1660. * Global SSL init
  1661. *
  1662. * @retval 0 error initializing SSL
  1663. * @retval 1 SSL initialized successfully
  1664. */
  1665. static int ossl_init(void)
  1666. {
  1667. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  1668. const uint64_t flags =
  1669. #ifdef OPENSSL_INIT_ENGINE_ALL_BUILTIN
  1670. /* not present in BoringSSL */
  1671. OPENSSL_INIT_ENGINE_ALL_BUILTIN |
  1672. #endif
  1673. #ifdef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG
  1674. OPENSSL_INIT_NO_LOAD_CONFIG |
  1675. #else
  1676. OPENSSL_INIT_LOAD_CONFIG |
  1677. #endif
  1678. 0;
  1679. OPENSSL_init_ssl(flags, NULL);
  1680. #else
  1681. OPENSSL_load_builtin_modules();
  1682. #ifdef USE_OPENSSL_ENGINE
  1683. ENGINE_load_builtin_engines();
  1684. #endif
  1685. #ifndef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG
  1686. CONF_modules_load_file(NULL, NULL,
  1687. CONF_MFLAGS_DEFAULT_SECTION|
  1688. CONF_MFLAGS_IGNORE_MISSING_FILE);
  1689. #endif
  1690. /* Let's get nice error messages */
  1691. SSL_load_error_strings();
  1692. /* Init the global ciphers and digests */
  1693. if(!SSLeay_add_ssl_algorithms())
  1694. return 0;
  1695. OpenSSL_add_all_algorithms();
  1696. #endif
  1697. Curl_tls_keylog_open();
  1698. return 1;
  1699. }
  1700. /* Global cleanup */
  1701. static void ossl_cleanup(void)
  1702. {
  1703. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  1704. /* OpenSSL 1.1 deprecates all these cleanup functions and
  1705. turns them into no-ops in OpenSSL 1.0 compatibility mode */
  1706. #else
  1707. /* Free ciphers and digests lists */
  1708. EVP_cleanup();
  1709. #ifdef USE_OPENSSL_ENGINE
  1710. /* Free engine list */
  1711. ENGINE_cleanup();
  1712. #endif
  1713. /* Free OpenSSL error strings */
  1714. ERR_free_strings();
  1715. /* Free thread local error state, destroying hash upon zero refcount */
  1716. ERR_remove_thread_state(NULL);
  1717. /* Free all memory allocated by all configuration modules */
  1718. CONF_modules_free();
  1719. #ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS
  1720. SSL_COMP_free_compression_methods();
  1721. #endif
  1722. #endif
  1723. Curl_tls_keylog_close();
  1724. }
  1725. /* Selects an OpenSSL crypto engine or provider.
  1726. */
  1727. static CURLcode ossl_set_engine(struct Curl_easy *data, const char *name)
  1728. {
  1729. #ifdef USE_OPENSSL_ENGINE
  1730. CURLcode result = CURLE_SSL_ENGINE_NOTFOUND;
  1731. ENGINE *e = ENGINE_by_id(name);
  1732. if(e) {
  1733. if(data->state.engine) {
  1734. ENGINE_finish(data->state.engine);
  1735. ENGINE_free(data->state.engine);
  1736. data->state.engine = NULL;
  1737. }
  1738. if(!ENGINE_init(e)) {
  1739. char buf[256];
  1740. ENGINE_free(e);
  1741. failf(data, "Failed to initialise SSL Engine '%s': %s",
  1742. name, ossl_strerror(ERR_get_error(), buf, sizeof(buf)));
  1743. result = CURLE_SSL_ENGINE_INITFAILED;
  1744. e = NULL;
  1745. }
  1746. else {
  1747. result = CURLE_OK;
  1748. }
  1749. data->state.engine = e;
  1750. return result;
  1751. }
  1752. #endif
  1753. #ifdef OPENSSL_HAS_PROVIDERS
  1754. return ossl_set_provider(data, name);
  1755. #else
  1756. (void)name;
  1757. failf(data, "OpenSSL engine not found");
  1758. return CURLE_SSL_ENGINE_NOTFOUND;
  1759. #endif
  1760. }
  1761. /* Sets engine as default for all SSL operations
  1762. */
  1763. static CURLcode ossl_set_engine_default(struct Curl_easy *data)
  1764. {
  1765. #ifdef USE_OPENSSL_ENGINE
  1766. if(data->state.engine) {
  1767. if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
  1768. infof(data, "set default crypto engine '%s'",
  1769. ENGINE_get_id(data->state.engine));
  1770. }
  1771. else {
  1772. failf(data, "set default crypto engine '%s' failed",
  1773. ENGINE_get_id(data->state.engine));
  1774. return CURLE_SSL_ENGINE_SETFAILED;
  1775. }
  1776. }
  1777. #else
  1778. (void)data;
  1779. #endif
  1780. return CURLE_OK;
  1781. }
  1782. /* Return list of OpenSSL crypto engine names.
  1783. */
  1784. static struct curl_slist *ossl_engines_list(struct Curl_easy *data)
  1785. {
  1786. struct curl_slist *list = NULL;
  1787. #ifdef USE_OPENSSL_ENGINE
  1788. struct curl_slist *beg;
  1789. ENGINE *e;
  1790. for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
  1791. beg = curl_slist_append(list, ENGINE_get_id(e));
  1792. if(!beg) {
  1793. curl_slist_free_all(list);
  1794. return NULL;
  1795. }
  1796. list = beg;
  1797. }
  1798. #endif
  1799. (void)data;
  1800. return list;
  1801. }
  1802. #ifdef OPENSSL_HAS_PROVIDERS
  1803. static void ossl_provider_cleanup(struct Curl_easy *data)
  1804. {
  1805. if(data->state.baseprov) {
  1806. OSSL_PROVIDER_unload(data->state.baseprov);
  1807. data->state.baseprov = NULL;
  1808. }
  1809. if(data->state.provider) {
  1810. OSSL_PROVIDER_unload(data->state.provider);
  1811. data->state.provider = NULL;
  1812. }
  1813. OSSL_LIB_CTX_free(data->state.libctx);
  1814. data->state.libctx = NULL;
  1815. Curl_safefree(data->state.propq);
  1816. data->state.provider_loaded = FALSE;
  1817. }
  1818. #define MAX_PROVIDER_LEN 128 /* reasonable */
  1819. /* Selects an OpenSSL crypto provider.
  1820. *
  1821. * A provider might need an associated property, a string passed on to
  1822. * OpenSSL. Specify this as [PROVIDER][:PROPERTY]: separate the name and the
  1823. * property with a colon. No colon means no property is set.
  1824. *
  1825. * An example provider + property looks like "tpm2:?provider=tpm2".
  1826. */
  1827. static CURLcode ossl_set_provider(struct Curl_easy *data, const char *iname)
  1828. {
  1829. char name[MAX_PROVIDER_LEN + 1];
  1830. struct Curl_str prov;
  1831. const char *propq = NULL;
  1832. if(!iname) {
  1833. /* clear and cleanup provider use */
  1834. ossl_provider_cleanup(data);
  1835. return CURLE_OK;
  1836. }
  1837. if(curlx_str_until(&iname, &prov, MAX_PROVIDER_LEN, ':'))
  1838. return CURLE_BAD_FUNCTION_ARGUMENT;
  1839. if(!curlx_str_single(&iname, ':'))
  1840. /* there was a colon, get the propq until the end of string */
  1841. propq = iname;
  1842. /* we need the name in a buffer, null-terminated */
  1843. memcpy(name, curlx_str(&prov), curlx_strlen(&prov));
  1844. name[curlx_strlen(&prov)] = 0;
  1845. if(!data->state.libctx) {
  1846. OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new();
  1847. if(!libctx)
  1848. return CURLE_OUT_OF_MEMORY;
  1849. if(propq) {
  1850. data->state.propq = strdup(propq);
  1851. if(!data->state.propq) {
  1852. OSSL_LIB_CTX_free(libctx);
  1853. return CURLE_OUT_OF_MEMORY;
  1854. }
  1855. }
  1856. data->state.libctx = libctx;
  1857. }
  1858. #ifndef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG
  1859. /* load the configuration file into the library context before checking the
  1860. * provider availability */
  1861. if(!OSSL_LIB_CTX_load_config(data->state.libctx, NULL)) {
  1862. infof(data, "Failed to load default openssl config. Proceeding.");
  1863. }
  1864. #endif
  1865. if(OSSL_PROVIDER_available(data->state.libctx, name)) {
  1866. /* already loaded through the configuration - no action needed */
  1867. data->state.provider_loaded = TRUE;
  1868. return CURLE_OK;
  1869. }
  1870. data->state.provider =
  1871. OSSL_PROVIDER_try_load(data->state.libctx, name, 1);
  1872. if(!data->state.provider) {
  1873. char error_buffer[256];
  1874. failf(data, "Failed to initialize provider: %s",
  1875. ossl_strerror(ERR_get_error(), error_buffer,
  1876. sizeof(error_buffer)));
  1877. ossl_provider_cleanup(data);
  1878. return CURLE_SSL_ENGINE_NOTFOUND;
  1879. }
  1880. /* load the base provider as well */
  1881. data->state.baseprov =
  1882. OSSL_PROVIDER_try_load(data->state.libctx, "base", 1);
  1883. if(!data->state.baseprov) {
  1884. ossl_provider_cleanup(data);
  1885. failf(data, "Failed to load base");
  1886. return CURLE_SSL_ENGINE_NOTFOUND;
  1887. }
  1888. else
  1889. data->state.provider_loaded = TRUE;
  1890. return CURLE_OK;
  1891. }
  1892. #endif
  1893. static CURLcode ossl_shutdown(struct Curl_cfilter *cf,
  1894. struct Curl_easy *data,
  1895. bool send_shutdown, bool *done)
  1896. {
  1897. struct ssl_connect_data *connssl = cf->ctx;
  1898. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  1899. CURLcode result = CURLE_OK;
  1900. char buf[1024];
  1901. int nread = -1, err;
  1902. unsigned long sslerr;
  1903. size_t i;
  1904. DEBUGASSERT(octx);
  1905. if(!octx->ssl || cf->shutdown) {
  1906. *done = TRUE;
  1907. goto out;
  1908. }
  1909. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  1910. *done = FALSE;
  1911. if(!(SSL_get_shutdown(octx->ssl) & SSL_SENT_SHUTDOWN)) {
  1912. /* We have not started the shutdown from our side yet. Check
  1913. * if the server already sent us one. */
  1914. ERR_clear_error();
  1915. for(i = 0; i < 10; ++i) {
  1916. nread = SSL_read(octx->ssl, buf, (int)sizeof(buf));
  1917. CURL_TRC_CF(data, cf, "SSL shutdown not sent, read -> %d", nread);
  1918. if(nread <= 0)
  1919. break;
  1920. }
  1921. err = SSL_get_error(octx->ssl, nread);
  1922. if(!nread && err == SSL_ERROR_ZERO_RETURN) {
  1923. bool input_pending;
  1924. /* Yes, it did. */
  1925. if(!send_shutdown) {
  1926. CURL_TRC_CF(data, cf, "SSL shutdown received, not sending");
  1927. *done = TRUE;
  1928. goto out;
  1929. }
  1930. else if(!cf->next->cft->is_alive(cf->next, data, &input_pending)) {
  1931. /* Server closed the connection after its closy notify. It
  1932. * seems not interested to see our close notify, so do not
  1933. * send it. We are done. */
  1934. connssl->peer_closed = TRUE;
  1935. CURL_TRC_CF(data, cf, "peer closed connection");
  1936. *done = TRUE;
  1937. goto out;
  1938. }
  1939. }
  1940. }
  1941. /* SSL should now have started the shutdown from our side. Since it
  1942. * was not complete, we are lacking the close notify from the server. */
  1943. if(send_shutdown && !(SSL_get_shutdown(octx->ssl) & SSL_SENT_SHUTDOWN)) {
  1944. int rc;
  1945. ERR_clear_error();
  1946. CURL_TRC_CF(data, cf, "send SSL close notify");
  1947. rc = SSL_shutdown(octx->ssl);
  1948. if(rc == 1) {
  1949. CURL_TRC_CF(data, cf, "SSL shutdown finished");
  1950. *done = TRUE;
  1951. goto out;
  1952. }
  1953. if(SSL_ERROR_WANT_WRITE == SSL_get_error(octx->ssl, rc)) {
  1954. CURL_TRC_CF(data, cf, "SSL shutdown still wants to send");
  1955. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  1956. goto out;
  1957. }
  1958. /* Having sent the close notify, we use SSL_read() to get the
  1959. * missing close notify from the server. */
  1960. }
  1961. for(i = 0; i < 10; ++i) {
  1962. ERR_clear_error();
  1963. nread = SSL_read(octx->ssl, buf, (int)sizeof(buf));
  1964. CURL_TRC_CF(data, cf, "SSL shutdown read -> %d", nread);
  1965. if(nread <= 0)
  1966. break;
  1967. }
  1968. err = SSL_get_error(octx->ssl, nread);
  1969. switch(err) {
  1970. case SSL_ERROR_ZERO_RETURN: /* no more data */
  1971. if(SSL_shutdown(octx->ssl) == 1)
  1972. CURL_TRC_CF(data, cf, "SSL shutdown finished");
  1973. else
  1974. CURL_TRC_CF(data, cf, "SSL shutdown not received, but closed");
  1975. *done = TRUE;
  1976. break;
  1977. case SSL_ERROR_NONE: /* just did not get anything */
  1978. case SSL_ERROR_WANT_READ:
  1979. /* SSL has send its notify and now wants to read the reply
  1980. * from the server. We are not really interested in that. */
  1981. CURL_TRC_CF(data, cf, "SSL shutdown sent, want receive");
  1982. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  1983. break;
  1984. case SSL_ERROR_WANT_WRITE:
  1985. CURL_TRC_CF(data, cf, "SSL shutdown send blocked");
  1986. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  1987. break;
  1988. default:
  1989. /* Server seems to have closed the connection without sending us
  1990. * a close notify. */
  1991. sslerr = ERR_get_error();
  1992. CURL_TRC_CF(data, cf, "SSL shutdown, ignore recv error: '%s', errno %d",
  1993. (sslerr ?
  1994. ossl_strerror(sslerr, buf, sizeof(buf)) :
  1995. SSL_ERROR_to_str(err)),
  1996. SOCKERRNO);
  1997. *done = TRUE;
  1998. result = CURLE_OK;
  1999. break;
  2000. }
  2001. out:
  2002. cf->shutdown = (result || *done);
  2003. if(cf->shutdown || (connssl->io_need != CURL_SSL_IO_NEED_NONE))
  2004. connssl->input_pending = FALSE;
  2005. return result;
  2006. }
  2007. static void ossl_close(struct Curl_cfilter *cf, struct Curl_easy *data)
  2008. {
  2009. struct ssl_connect_data *connssl = cf->ctx;
  2010. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  2011. (void)data;
  2012. DEBUGASSERT(octx);
  2013. connssl->input_pending = FALSE;
  2014. if(octx->ssl) {
  2015. SSL_free(octx->ssl);
  2016. octx->ssl = NULL;
  2017. }
  2018. if(octx->ssl_ctx) {
  2019. SSL_CTX_free(octx->ssl_ctx);
  2020. octx->ssl_ctx = NULL;
  2021. octx->x509_store_setup = FALSE;
  2022. }
  2023. if(octx->bio_method) {
  2024. ossl_bio_cf_method_free(octx->bio_method);
  2025. octx->bio_method = NULL;
  2026. }
  2027. }
  2028. /*
  2029. * This function is called when the 'data' struct is going away. Close
  2030. * down everything and free all resources!
  2031. */
  2032. static void ossl_close_all(struct Curl_easy *data)
  2033. {
  2034. #ifdef USE_OPENSSL_ENGINE
  2035. if(data->state.engine) {
  2036. ENGINE_finish(data->state.engine);
  2037. ENGINE_free(data->state.engine);
  2038. data->state.engine = NULL;
  2039. }
  2040. #else
  2041. (void)data;
  2042. #endif
  2043. #ifdef OPENSSL_HAS_PROVIDERS
  2044. ossl_provider_cleanup(data);
  2045. #endif
  2046. #ifndef HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED
  2047. /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread
  2048. so we need to clean it here in case the thread will be killed. All OpenSSL
  2049. code should extract the error in association with the error so clearing
  2050. this queue here should be harmless at worst. */
  2051. ERR_remove_thread_state(NULL);
  2052. #endif
  2053. }
  2054. /* ====================================================== */
  2055. /* Quote from RFC2818 section 3.1 "Server Identity"
  2056. If a subjectAltName extension of type dNSName is present, that MUST
  2057. be used as the identity. Otherwise, the (most specific) Common Name
  2058. field in the Subject field of the certificate MUST be used. Although
  2059. the use of the Common Name is existing practice, it is deprecated and
  2060. Certification Authorities are encouraged to use the dNSName instead.
  2061. Matching is performed using the matching rules specified by
  2062. [RFC2459]. If more than one identity of a given type is present in
  2063. the certificate (e.g., more than one dNSName name, a match in any one
  2064. of the set is considered acceptable.) Names may contain the wildcard
  2065. character * which is considered to match any single domain name
  2066. component or component fragment. E.g., *.a.com matches foo.a.com but
  2067. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  2068. In some cases, the URI is specified as an IP address rather than a
  2069. hostname. In this case, the iPAddress subjectAltName must be present
  2070. in the certificate and must exactly match the IP in the URI.
  2071. This function is now used from ngtcp2 (QUIC) as well.
  2072. */
  2073. static CURLcode ossl_verifyhost(struct Curl_easy *data,
  2074. struct connectdata *conn,
  2075. struct ssl_peer *peer,
  2076. X509 *server_cert)
  2077. {
  2078. bool matched = FALSE;
  2079. int target; /* target type, GEN_DNS or GEN_IPADD */
  2080. size_t addrlen = 0;
  2081. STACK_OF(GENERAL_NAME) *altnames;
  2082. #ifdef USE_IPV6
  2083. struct in6_addr addr;
  2084. #else
  2085. struct in_addr addr;
  2086. #endif
  2087. CURLcode result = CURLE_OK;
  2088. bool dNSName = FALSE; /* if a dNSName field exists in the cert */
  2089. bool iPAddress = FALSE; /* if an iPAddress field exists in the cert */
  2090. size_t hostlen = strlen(peer->hostname);
  2091. (void)conn;
  2092. switch(peer->type) {
  2093. case CURL_SSL_PEER_IPV4:
  2094. if(!curlx_inet_pton(AF_INET, peer->hostname, &addr))
  2095. return CURLE_PEER_FAILED_VERIFICATION;
  2096. target = GEN_IPADD;
  2097. addrlen = sizeof(struct in_addr);
  2098. break;
  2099. #ifdef USE_IPV6
  2100. case CURL_SSL_PEER_IPV6:
  2101. if(!curlx_inet_pton(AF_INET6, peer->hostname, &addr))
  2102. return CURLE_PEER_FAILED_VERIFICATION;
  2103. target = GEN_IPADD;
  2104. addrlen = sizeof(struct in6_addr);
  2105. break;
  2106. #endif
  2107. case CURL_SSL_PEER_DNS:
  2108. target = GEN_DNS;
  2109. break;
  2110. default:
  2111. DEBUGASSERT(0);
  2112. failf(data, "unexpected ssl peer type: %d", peer->type);
  2113. return CURLE_PEER_FAILED_VERIFICATION;
  2114. }
  2115. /* get a "list" of alternative names */
  2116. altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
  2117. if(altnames) {
  2118. #ifdef HAVE_BORINGSSL_LIKE
  2119. size_t numalts;
  2120. size_t i;
  2121. #else
  2122. int numalts;
  2123. int i;
  2124. #endif
  2125. /* get amount of alternatives, RFC2459 claims there MUST be at least
  2126. one, but we do not depend on it... */
  2127. numalts = sk_GENERAL_NAME_num(altnames);
  2128. /* loop through all alternatives - until a dnsmatch */
  2129. for(i = 0; (i < numalts) && !matched; i++) {
  2130. /* get a handle to alternative name number i */
  2131. const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
  2132. if(check->type == GEN_DNS)
  2133. dNSName = TRUE;
  2134. else if(check->type == GEN_IPADD)
  2135. iPAddress = TRUE;
  2136. /* only check alternatives of the same type the target is */
  2137. if(check->type == target) {
  2138. /* get data and length */
  2139. const char *altptr = (const char *)ASN1_STRING_get0_data(check->d.ia5);
  2140. size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
  2141. switch(target) {
  2142. case GEN_DNS: /* name/pattern comparison */
  2143. /* The OpenSSL manpage explicitly says: "In general it cannot be
  2144. assumed that the data returned by ASN1_STRING_data() is null
  2145. terminated or does not contain embedded nulls." But also that
  2146. "The actual format of the data will depend on the actual string
  2147. type itself: for example for an IA5String the data will be ASCII"
  2148. It has been however verified that in 0.9.6 and 0.9.7, IA5String
  2149. is always null-terminated.
  2150. */
  2151. if((altlen == strlen(altptr)) &&
  2152. /* if this is not true, there was an embedded zero in the name
  2153. string and we cannot match it. */
  2154. Curl_cert_hostcheck(altptr, altlen, peer->hostname, hostlen)) {
  2155. matched = TRUE;
  2156. infof(data, " subjectAltName: \"%s\" matches cert's \"%.*s\"",
  2157. peer->dispname, (int)altlen, altptr);
  2158. }
  2159. break;
  2160. case GEN_IPADD: /* IP address comparison */
  2161. /* compare alternative IP address if the data chunk is the same size
  2162. our server IP address is */
  2163. if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
  2164. matched = TRUE;
  2165. infof(data,
  2166. " subjectAltName: \"%s\" matches cert's IP address!",
  2167. peer->dispname);
  2168. }
  2169. break;
  2170. }
  2171. }
  2172. }
  2173. GENERAL_NAMES_free(altnames);
  2174. }
  2175. if(matched)
  2176. /* an alternative name matched */
  2177. ;
  2178. else if(dNSName || iPAddress) {
  2179. const char *tname = (peer->type == CURL_SSL_PEER_DNS) ? "hostname" :
  2180. (peer->type == CURL_SSL_PEER_IPV4) ?
  2181. "ipv4 address" : "ipv6 address";
  2182. infof(data, " subjectAltName does not match %s %s", tname, peer->dispname);
  2183. failf(data, "SSL: no alternative certificate subject name matches "
  2184. "target %s '%s'", tname, peer->dispname);
  2185. result = CURLE_PEER_FAILED_VERIFICATION;
  2186. }
  2187. else {
  2188. /* we have to look to the last occurrence of a commonName in the
  2189. distinguished one to get the most significant one. */
  2190. int i = -1;
  2191. unsigned char *cn = NULL;
  2192. int cnlen = 0;
  2193. bool free_cn = FALSE;
  2194. /* The following is done because of a bug in 0.9.6b */
  2195. X509_NAME *name = X509_get_subject_name(server_cert);
  2196. if(name) {
  2197. int j;
  2198. while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0)
  2199. i = j;
  2200. }
  2201. /* we have the name entry and we will now convert this to a string
  2202. that we can use for comparison. Doing this we support BMPstring,
  2203. UTF8, etc. */
  2204. if(i >= 0) {
  2205. ASN1_STRING *tmp =
  2206. X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
  2207. /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
  2208. is already UTF-8 encoded. We check for this case and copy the raw
  2209. string manually to avoid the problem. This code can be made
  2210. conditional in the future when OpenSSL has been fixed. */
  2211. if(tmp) {
  2212. if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
  2213. cnlen = ASN1_STRING_length(tmp);
  2214. cn = (unsigned char *)CURL_UNCONST(ASN1_STRING_get0_data(tmp));
  2215. }
  2216. else { /* not a UTF8 name */
  2217. cnlen = ASN1_STRING_to_UTF8(&cn, tmp);
  2218. free_cn = TRUE;
  2219. }
  2220. if((cnlen <= 0) || !cn)
  2221. result = CURLE_OUT_OF_MEMORY;
  2222. else if((size_t)cnlen != strlen((char *)cn)) {
  2223. /* there was a terminating zero before the end of string, this
  2224. cannot match and we return failure! */
  2225. failf(data, "SSL: illegal cert name field");
  2226. result = CURLE_PEER_FAILED_VERIFICATION;
  2227. }
  2228. }
  2229. }
  2230. if(result)
  2231. /* error already detected, pass through */
  2232. ;
  2233. else if(!cn) {
  2234. failf(data,
  2235. "SSL: unable to obtain common name from peer certificate");
  2236. result = CURLE_PEER_FAILED_VERIFICATION;
  2237. }
  2238. else if(!Curl_cert_hostcheck((const char *)cn, cnlen,
  2239. peer->hostname, hostlen)) {
  2240. failf(data, "SSL: certificate subject name '%s' does not match "
  2241. "target hostname '%s'", cn, peer->dispname);
  2242. result = CURLE_PEER_FAILED_VERIFICATION;
  2243. }
  2244. else {
  2245. infof(data, " common name: %s (matched)", cn);
  2246. }
  2247. if(free_cn)
  2248. OPENSSL_free(cn);
  2249. }
  2250. return result;
  2251. }
  2252. #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_OCSP)
  2253. static CURLcode verifystatus(struct Curl_cfilter *cf,
  2254. struct Curl_easy *data,
  2255. struct ossl_ctx *octx)
  2256. {
  2257. int i, ocsp_status;
  2258. #ifdef HAVE_BORINGSSL_LIKE
  2259. const uint8_t *status;
  2260. #else
  2261. unsigned char *status;
  2262. #endif
  2263. const unsigned char *p;
  2264. CURLcode result = CURLE_OK;
  2265. OCSP_RESPONSE *rsp = NULL;
  2266. OCSP_BASICRESP *br = NULL;
  2267. X509_STORE *st = NULL;
  2268. STACK_OF(X509) *ch = NULL;
  2269. X509 *cert;
  2270. OCSP_CERTID *id = NULL;
  2271. int cert_status, crl_reason;
  2272. ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
  2273. int ret;
  2274. long len;
  2275. (void)cf;
  2276. DEBUGASSERT(octx);
  2277. len = (long)SSL_get_tlsext_status_ocsp_resp(octx->ssl, &status);
  2278. if(!status) {
  2279. failf(data, "No OCSP response received");
  2280. result = CURLE_SSL_INVALIDCERTSTATUS;
  2281. goto end;
  2282. }
  2283. p = status;
  2284. rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
  2285. if(!rsp) {
  2286. failf(data, "Invalid OCSP response");
  2287. result = CURLE_SSL_INVALIDCERTSTATUS;
  2288. goto end;
  2289. }
  2290. ocsp_status = OCSP_response_status(rsp);
  2291. if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
  2292. failf(data, "Invalid OCSP response status: %s (%d)",
  2293. OCSP_response_status_str(ocsp_status), ocsp_status);
  2294. result = CURLE_SSL_INVALIDCERTSTATUS;
  2295. goto end;
  2296. }
  2297. br = OCSP_response_get1_basic(rsp);
  2298. if(!br) {
  2299. failf(data, "Invalid OCSP response");
  2300. result = CURLE_SSL_INVALIDCERTSTATUS;
  2301. goto end;
  2302. }
  2303. ch = SSL_get_peer_cert_chain(octx->ssl);
  2304. if(!ch) {
  2305. failf(data, "Could not get peer certificate chain");
  2306. result = CURLE_SSL_INVALIDCERTSTATUS;
  2307. goto end;
  2308. }
  2309. st = SSL_CTX_get_cert_store(octx->ssl_ctx);
  2310. if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
  2311. failf(data, "OCSP response verification failed");
  2312. result = CURLE_SSL_INVALIDCERTSTATUS;
  2313. goto end;
  2314. }
  2315. /* Compute the certificate's ID */
  2316. cert = SSL_get1_peer_certificate(octx->ssl);
  2317. if(!cert) {
  2318. failf(data, "Error getting peer certificate");
  2319. result = CURLE_SSL_INVALIDCERTSTATUS;
  2320. goto end;
  2321. }
  2322. for(i = 0; i < (int)sk_X509_num(ch); i++) {
  2323. X509 *issuer = sk_X509_value(ch, (ossl_valsize_t)i);
  2324. if(X509_check_issued(issuer, cert) == X509_V_OK) {
  2325. /* Note to analysis tools: using SHA1 here is fine. The `id`
  2326. * generated is used as a hash lookup key, not as a verifier
  2327. * of the OCSP data itself. This all according to RFC 5019. */
  2328. id = OCSP_cert_to_id(EVP_sha1(), cert, issuer);
  2329. break;
  2330. }
  2331. }
  2332. X509_free(cert);
  2333. if(!id) {
  2334. failf(data, "Error computing OCSP ID");
  2335. result = CURLE_SSL_INVALIDCERTSTATUS;
  2336. goto end;
  2337. }
  2338. /* Find the single OCSP response corresponding to the certificate ID */
  2339. ret = OCSP_resp_find_status(br, id, &cert_status, &crl_reason, &rev,
  2340. &thisupd, &nextupd);
  2341. OCSP_CERTID_free(id);
  2342. if(ret != 1) {
  2343. failf(data, "Could not find certificate ID in OCSP response");
  2344. result = CURLE_SSL_INVALIDCERTSTATUS;
  2345. goto end;
  2346. }
  2347. /* Validate the OCSP response issuing and update times.
  2348. * - `thisupd` is the time the OCSP response was issued
  2349. * - `nextupd` is the time the OCSP response should be updated
  2350. * (valid life time assigned by the OCSP responder)
  2351. * - 3rd param: how many seconds of clock skew we allow between
  2352. * our clock and the instance that issued the OCSP response
  2353. * - 4th param: how many seconds in the past `thisupd` may be, with
  2354. * -1 meaning there is no limit. */
  2355. if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
  2356. failf(data, "OCSP response has expired");
  2357. result = CURLE_SSL_INVALIDCERTSTATUS;
  2358. goto end;
  2359. }
  2360. infof(data, "SSL certificate status: %s (%d)",
  2361. OCSP_cert_status_str(cert_status), cert_status);
  2362. switch(cert_status) {
  2363. case V_OCSP_CERTSTATUS_GOOD:
  2364. break;
  2365. case V_OCSP_CERTSTATUS_REVOKED:
  2366. result = CURLE_SSL_INVALIDCERTSTATUS;
  2367. failf(data, "SSL certificate revocation reason: %s (%d)",
  2368. OCSP_crl_reason_str(crl_reason), crl_reason);
  2369. goto end;
  2370. case V_OCSP_CERTSTATUS_UNKNOWN:
  2371. default:
  2372. result = CURLE_SSL_INVALIDCERTSTATUS;
  2373. goto end;
  2374. }
  2375. end:
  2376. if(br)
  2377. OCSP_BASICRESP_free(br);
  2378. OCSP_RESPONSE_free(rsp);
  2379. return result;
  2380. }
  2381. #endif
  2382. static const char *ssl_msg_type(int ssl_ver, int msg)
  2383. {
  2384. #ifdef SSL2_VERSION_MAJOR /* OpenSSL 1.0.2, LibreSSL <=3.9.2 */
  2385. if(ssl_ver == SSL2_VERSION_MAJOR) {
  2386. switch(msg) {
  2387. case SSL2_MT_ERROR:
  2388. return "Error";
  2389. case SSL2_MT_CLIENT_HELLO:
  2390. return "Client hello";
  2391. case SSL2_MT_CLIENT_MASTER_KEY:
  2392. return "Client key";
  2393. case SSL2_MT_CLIENT_FINISHED:
  2394. return "Client finished";
  2395. case SSL2_MT_SERVER_HELLO:
  2396. return "Server hello";
  2397. case SSL2_MT_SERVER_VERIFY:
  2398. return "Server verify";
  2399. case SSL2_MT_SERVER_FINISHED:
  2400. return "Server finished";
  2401. case SSL2_MT_REQUEST_CERTIFICATE:
  2402. return "Request CERT";
  2403. case SSL2_MT_CLIENT_CERTIFICATE:
  2404. return "Client CERT";
  2405. }
  2406. }
  2407. else
  2408. #endif
  2409. if(ssl_ver == SSL3_VERSION_MAJOR) {
  2410. switch(msg) {
  2411. case SSL3_MT_HELLO_REQUEST:
  2412. return "Hello request";
  2413. case SSL3_MT_CLIENT_HELLO:
  2414. return "Client hello";
  2415. case SSL3_MT_SERVER_HELLO:
  2416. return "Server hello";
  2417. #ifdef SSL3_MT_NEWSESSION_TICKET
  2418. case SSL3_MT_NEWSESSION_TICKET:
  2419. return "Newsession Ticket";
  2420. #endif
  2421. case SSL3_MT_CERTIFICATE:
  2422. return "Certificate";
  2423. case SSL3_MT_SERVER_KEY_EXCHANGE:
  2424. return "Server key exchange";
  2425. case SSL3_MT_CLIENT_KEY_EXCHANGE:
  2426. return "Client key exchange";
  2427. case SSL3_MT_CERTIFICATE_REQUEST:
  2428. return "Request CERT";
  2429. case SSL3_MT_SERVER_DONE:
  2430. return "Server finished";
  2431. case SSL3_MT_CERTIFICATE_VERIFY:
  2432. return "CERT verify";
  2433. case SSL3_MT_FINISHED:
  2434. return "Finished";
  2435. #ifdef SSL3_MT_CERTIFICATE_STATUS
  2436. case SSL3_MT_CERTIFICATE_STATUS:
  2437. return "Certificate Status";
  2438. #endif
  2439. #ifdef SSL3_MT_ENCRYPTED_EXTENSIONS
  2440. case SSL3_MT_ENCRYPTED_EXTENSIONS:
  2441. return "Encrypted Extensions";
  2442. #endif
  2443. #ifdef SSL3_MT_SUPPLEMENTAL_DATA
  2444. case SSL3_MT_SUPPLEMENTAL_DATA:
  2445. return "Supplemental data";
  2446. #endif
  2447. #ifdef SSL3_MT_END_OF_EARLY_DATA
  2448. case SSL3_MT_END_OF_EARLY_DATA:
  2449. return "End of early data";
  2450. #endif
  2451. #ifdef SSL3_MT_KEY_UPDATE
  2452. case SSL3_MT_KEY_UPDATE:
  2453. return "Key update";
  2454. #endif
  2455. #ifdef SSL3_MT_NEXT_PROTO
  2456. case SSL3_MT_NEXT_PROTO:
  2457. return "Next protocol";
  2458. #endif
  2459. #ifdef SSL3_MT_MESSAGE_HASH
  2460. case SSL3_MT_MESSAGE_HASH:
  2461. return "Message hash";
  2462. #endif
  2463. }
  2464. }
  2465. return "Unknown";
  2466. }
  2467. static const char *tls_rt_type(int type)
  2468. {
  2469. switch(type) {
  2470. #ifdef SSL3_RT_HEADER
  2471. case SSL3_RT_HEADER:
  2472. return "TLS header";
  2473. #endif
  2474. case SSL3_RT_CHANGE_CIPHER_SPEC:
  2475. return "TLS change cipher";
  2476. case SSL3_RT_ALERT:
  2477. return "TLS alert";
  2478. case SSL3_RT_HANDSHAKE:
  2479. return "TLS handshake";
  2480. case SSL3_RT_APPLICATION_DATA:
  2481. return "TLS app data";
  2482. default:
  2483. return "TLS Unknown";
  2484. }
  2485. }
  2486. /*
  2487. * Our callback from the SSL/TLS layers.
  2488. */
  2489. static void ossl_trace(int direction, int ssl_ver, int content_type,
  2490. const void *buf, size_t len, SSL *ssl,
  2491. void *userp)
  2492. {
  2493. const char *verstr = "???";
  2494. struct Curl_cfilter *cf = userp;
  2495. struct Curl_easy *data = NULL;
  2496. char unknown[32];
  2497. if(!cf)
  2498. return;
  2499. data = CF_DATA_CURRENT(cf);
  2500. if(!data || !data->set.fdebug || (direction && direction != 1))
  2501. return;
  2502. switch(ssl_ver) {
  2503. #ifdef SSL2_VERSION /* removed in recent versions */
  2504. case SSL2_VERSION:
  2505. verstr = "SSLv2";
  2506. break;
  2507. #endif
  2508. #ifdef SSL3_VERSION
  2509. case SSL3_VERSION:
  2510. verstr = "SSLv3";
  2511. break;
  2512. #endif
  2513. case TLS1_VERSION:
  2514. verstr = "TLSv1.0";
  2515. break;
  2516. #ifdef TLS1_1_VERSION
  2517. case TLS1_1_VERSION:
  2518. verstr = "TLSv1.1";
  2519. break;
  2520. #endif
  2521. #ifdef TLS1_2_VERSION
  2522. case TLS1_2_VERSION:
  2523. verstr = "TLSv1.2";
  2524. break;
  2525. #endif
  2526. #ifdef TLS1_3_VERSION /* OpenSSL 1.1.1+, all forks */
  2527. case TLS1_3_VERSION:
  2528. verstr = "TLSv1.3";
  2529. break;
  2530. #endif
  2531. case 0:
  2532. break;
  2533. default:
  2534. curl_msnprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
  2535. verstr = unknown;
  2536. break;
  2537. }
  2538. /* Log progress for interesting records only (like Handshake or Alert), skip
  2539. * all raw record headers (content_type == SSL3_RT_HEADER or ssl_ver == 0).
  2540. * For TLS 1.3, skip notification of the decrypted inner Content-Type.
  2541. */
  2542. if(ssl_ver
  2543. #ifdef SSL3_RT_HEADER
  2544. && content_type != SSL3_RT_HEADER
  2545. #endif
  2546. #ifdef SSL3_RT_INNER_CONTENT_TYPE
  2547. && content_type != SSL3_RT_INNER_CONTENT_TYPE
  2548. #endif
  2549. ) {
  2550. const char *msg_name, *tls_rt_name;
  2551. char ssl_buf[1024];
  2552. int msg_type, txt_len;
  2553. /* the info given when the version is zero is not that useful for us */
  2554. ssl_ver >>= 8; /* check the upper 8 bits only below */
  2555. /* SSLv2 does not seem to have TLS record-type headers, so OpenSSL
  2556. * always pass-up content-type as 0. But the interesting message-type
  2557. * is at 'buf[0]'.
  2558. */
  2559. if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
  2560. tls_rt_name = tls_rt_type(content_type);
  2561. else
  2562. tls_rt_name = "";
  2563. if(content_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  2564. msg_type = *(const char *)buf;
  2565. msg_name = "Change cipher spec";
  2566. }
  2567. else if(content_type == SSL3_RT_ALERT) {
  2568. msg_type = (((const char *)buf)[0] << 8) + ((const char *)buf)[1];
  2569. msg_name = SSL_alert_desc_string_long(msg_type);
  2570. }
  2571. else {
  2572. msg_type = *(const char *)buf;
  2573. msg_name = ssl_msg_type(ssl_ver, msg_type);
  2574. }
  2575. txt_len = curl_msnprintf(ssl_buf, sizeof(ssl_buf),
  2576. "%s (%s), %s, %s (%d):\n",
  2577. verstr, direction ? "OUT" : "IN",
  2578. tls_rt_name, msg_name, msg_type);
  2579. Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len);
  2580. }
  2581. Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
  2582. CURLINFO_SSL_DATA_IN, (const char *)buf, len);
  2583. (void)ssl;
  2584. }
  2585. /* Check for ALPN support. */
  2586. #ifndef OPENSSL_NO_TLSEXT
  2587. # define HAS_ALPN_OPENSSL
  2588. #endif
  2589. /* Check for OpenSSL 1.1.0 which has set_{min,max}_proto_version(). */
  2590. #undef HAS_MODERN_SET_PROTO_VER
  2591. #if OPENSSL_VERSION_NUMBER >= 0x10100000L \
  2592. && !(defined(LIBRESSL_VERSION_NUMBER) && \
  2593. LIBRESSL_VERSION_NUMBER < 0x20600000L)
  2594. # define HAS_MODERN_SET_PROTO_VER 1
  2595. #endif
  2596. #ifdef HAS_MODERN_SET_PROTO_VER
  2597. static CURLcode
  2598. ossl_set_ssl_version_min_max(struct Curl_cfilter *cf, SSL_CTX *ctx,
  2599. unsigned int ssl_version_min)
  2600. {
  2601. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2602. /* first, TLS min version... */
  2603. long curl_ssl_version_min = (long)ssl_version_min;
  2604. long curl_ssl_version_max;
  2605. /* convert curl min SSL version option to OpenSSL constant */
  2606. #if defined(HAVE_BORINGSSL_LIKE) || defined(LIBRESSL_VERSION_NUMBER)
  2607. uint16_t ossl_ssl_version_min = 0;
  2608. uint16_t ossl_ssl_version_max = 0;
  2609. #else
  2610. long ossl_ssl_version_min = 0;
  2611. long ossl_ssl_version_max = 0;
  2612. #endif
  2613. switch(curl_ssl_version_min) {
  2614. case CURL_SSLVERSION_TLSv1: /* TLS 1.x */
  2615. case CURL_SSLVERSION_TLSv1_0:
  2616. ossl_ssl_version_min = TLS1_VERSION;
  2617. break;
  2618. case CURL_SSLVERSION_TLSv1_1:
  2619. ossl_ssl_version_min = TLS1_1_VERSION;
  2620. break;
  2621. case CURL_SSLVERSION_TLSv1_2:
  2622. ossl_ssl_version_min = TLS1_2_VERSION;
  2623. break;
  2624. case CURL_SSLVERSION_TLSv1_3:
  2625. #ifdef TLS1_3_VERSION
  2626. ossl_ssl_version_min = TLS1_3_VERSION;
  2627. break;
  2628. #else
  2629. return CURLE_NOT_BUILT_IN;
  2630. #endif
  2631. }
  2632. /* CURL_SSLVERSION_DEFAULT means that no option was selected.
  2633. We do not want to pass 0 to SSL_CTX_set_min_proto_version as
  2634. it would enable all versions down to the lowest supported by
  2635. the library.
  2636. So we skip this, and stay with the library default
  2637. */
  2638. if(curl_ssl_version_min != CURL_SSLVERSION_DEFAULT) {
  2639. if(!SSL_CTX_set_min_proto_version(ctx, ossl_ssl_version_min)) {
  2640. return CURLE_SSL_CONNECT_ERROR;
  2641. }
  2642. }
  2643. /* ... then, TLS max version */
  2644. curl_ssl_version_max = (long)conn_config->version_max;
  2645. /* convert curl max SSL version option to OpenSSL constant */
  2646. switch(curl_ssl_version_max) {
  2647. case CURL_SSLVERSION_MAX_TLSv1_0:
  2648. ossl_ssl_version_max = TLS1_VERSION;
  2649. break;
  2650. case CURL_SSLVERSION_MAX_TLSv1_1:
  2651. ossl_ssl_version_max = TLS1_1_VERSION;
  2652. break;
  2653. case CURL_SSLVERSION_MAX_TLSv1_2:
  2654. ossl_ssl_version_max = TLS1_2_VERSION;
  2655. break;
  2656. #ifdef TLS1_3_VERSION
  2657. case CURL_SSLVERSION_MAX_TLSv1_3:
  2658. ossl_ssl_version_max = TLS1_3_VERSION;
  2659. break;
  2660. #endif
  2661. case CURL_SSLVERSION_MAX_NONE: /* none selected */
  2662. case CURL_SSLVERSION_MAX_DEFAULT: /* max selected */
  2663. default:
  2664. /* SSL_CTX_set_max_proto_version states that: setting the maximum to 0
  2665. will enable protocol versions up to the highest version supported by
  2666. the library */
  2667. ossl_ssl_version_max = 0;
  2668. break;
  2669. }
  2670. if(!SSL_CTX_set_max_proto_version(ctx, ossl_ssl_version_max)) {
  2671. return CURLE_SSL_CONNECT_ERROR;
  2672. }
  2673. return CURLE_OK;
  2674. }
  2675. #endif /* HAS_MODERN_SET_PROTO_VER */
  2676. #ifdef HAVE_BORINGSSL_LIKE
  2677. typedef uint32_t ctx_option_t;
  2678. #elif defined(HAVE_OPENSSL3)
  2679. typedef uint64_t ctx_option_t;
  2680. #elif OPENSSL_VERSION_NUMBER >= 0x10100000L && \
  2681. !defined(LIBRESSL_VERSION_NUMBER)
  2682. typedef unsigned long ctx_option_t;
  2683. #else
  2684. typedef long ctx_option_t;
  2685. #endif
  2686. #if !defined(HAS_MODERN_SET_PROTO_VER)
  2687. static CURLcode
  2688. ossl_set_ssl_version_min_max_legacy(ctx_option_t *ctx_options,
  2689. struct Curl_cfilter *cf,
  2690. struct Curl_easy *data)
  2691. {
  2692. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2693. long ssl_version = conn_config->version;
  2694. long ssl_version_max = conn_config->version_max;
  2695. (void)data; /* In case it is unused. */
  2696. switch(ssl_version) {
  2697. case CURL_SSLVERSION_TLSv1_3:
  2698. #ifdef TLS1_3_VERSION
  2699. {
  2700. struct ssl_connect_data *connssl = cf->ctx;
  2701. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  2702. DEBUGASSERT(octx);
  2703. SSL_CTX_set_max_proto_version(octx->ssl_ctx, TLS1_3_VERSION);
  2704. *ctx_options |= SSL_OP_NO_TLSv1_2;
  2705. }
  2706. #else
  2707. (void)ctx_options;
  2708. failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
  2709. return CURLE_NOT_BUILT_IN;
  2710. #endif
  2711. FALLTHROUGH();
  2712. case CURL_SSLVERSION_TLSv1_2:
  2713. *ctx_options |= SSL_OP_NO_TLSv1_1;
  2714. FALLTHROUGH();
  2715. case CURL_SSLVERSION_TLSv1_1:
  2716. *ctx_options |= SSL_OP_NO_TLSv1;
  2717. FALLTHROUGH();
  2718. case CURL_SSLVERSION_TLSv1_0:
  2719. case CURL_SSLVERSION_TLSv1:
  2720. break;
  2721. }
  2722. switch(ssl_version_max) {
  2723. case CURL_SSLVERSION_MAX_TLSv1_0:
  2724. *ctx_options |= SSL_OP_NO_TLSv1_1;
  2725. FALLTHROUGH();
  2726. case CURL_SSLVERSION_MAX_TLSv1_1:
  2727. *ctx_options |= SSL_OP_NO_TLSv1_2;
  2728. FALLTHROUGH();
  2729. case CURL_SSLVERSION_MAX_TLSv1_2:
  2730. #ifdef TLS1_3_VERSION
  2731. *ctx_options |= SSL_OP_NO_TLSv1_3;
  2732. #endif
  2733. break;
  2734. case CURL_SSLVERSION_MAX_TLSv1_3:
  2735. #ifdef TLS1_3_VERSION
  2736. break;
  2737. #else
  2738. failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
  2739. return CURLE_NOT_BUILT_IN;
  2740. #endif
  2741. }
  2742. return CURLE_OK;
  2743. }
  2744. #endif /* ! HAS_MODERN_SET_PROTO_VER */
  2745. CURLcode Curl_ossl_add_session(struct Curl_cfilter *cf,
  2746. struct Curl_easy *data,
  2747. const char *ssl_peer_key,
  2748. SSL_SESSION *session,
  2749. int ietf_tls_id,
  2750. const char *alpn,
  2751. unsigned char *quic_tp,
  2752. size_t quic_tp_len)
  2753. {
  2754. unsigned char *der_session_buf = NULL;
  2755. unsigned char *qtp_clone = NULL;
  2756. CURLcode result = CURLE_OK;
  2757. if(!cf || !data)
  2758. goto out;
  2759. if(Curl_ssl_scache_use(cf, data)) {
  2760. struct Curl_ssl_session *sc_session = NULL;
  2761. size_t der_session_size;
  2762. unsigned char *der_session_ptr;
  2763. size_t earlydata_max = 0;
  2764. der_session_size = i2d_SSL_SESSION(session, NULL);
  2765. if(der_session_size == 0) {
  2766. result = CURLE_OUT_OF_MEMORY;
  2767. goto out;
  2768. }
  2769. der_session_buf = der_session_ptr = malloc(der_session_size);
  2770. if(!der_session_buf) {
  2771. result = CURLE_OUT_OF_MEMORY;
  2772. goto out;
  2773. }
  2774. der_session_size = i2d_SSL_SESSION(session, &der_session_ptr);
  2775. if(der_session_size == 0) {
  2776. result = CURLE_OUT_OF_MEMORY;
  2777. goto out;
  2778. }
  2779. #ifdef HAVE_OPENSSL_EARLYDATA
  2780. earlydata_max = SSL_SESSION_get_max_early_data(session);
  2781. #endif
  2782. if(quic_tp && quic_tp_len) {
  2783. qtp_clone = Curl_memdup0((char *)quic_tp, quic_tp_len);
  2784. if(!qtp_clone) {
  2785. result = CURLE_OUT_OF_MEMORY;
  2786. goto out;
  2787. }
  2788. }
  2789. result = Curl_ssl_session_create2(der_session_buf, der_session_size,
  2790. ietf_tls_id, alpn,
  2791. (curl_off_t)time(NULL) +
  2792. SSL_SESSION_get_timeout(session),
  2793. earlydata_max, qtp_clone, quic_tp_len,
  2794. &sc_session);
  2795. der_session_buf = NULL; /* took ownership of sdata */
  2796. if(!result) {
  2797. result = Curl_ssl_scache_put(cf, data, ssl_peer_key, sc_session);
  2798. /* took ownership of `sc_session` */
  2799. }
  2800. }
  2801. out:
  2802. free(der_session_buf);
  2803. return result;
  2804. }
  2805. /* The "new session" callback must return zero if the session can be removed
  2806. * or non-zero if the session has been put into the session cache.
  2807. */
  2808. static int ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid)
  2809. {
  2810. struct Curl_cfilter *cf = (struct Curl_cfilter*) SSL_get_app_data(ssl);
  2811. if(cf) {
  2812. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  2813. struct ssl_connect_data *connssl = cf->ctx;
  2814. Curl_ossl_add_session(cf, data, connssl->peer.scache_key, ssl_sessionid,
  2815. SSL_version(ssl), connssl->negotiated.alpn,
  2816. NULL, 0);
  2817. }
  2818. return 0;
  2819. }
  2820. static CURLcode load_cacert_from_memory(X509_STORE *store,
  2821. const struct curl_blob *ca_info_blob)
  2822. {
  2823. /* these need to be freed at the end */
  2824. BIO *cbio = NULL;
  2825. STACK_OF(X509_INFO) *inf = NULL;
  2826. /* everything else is just a reference */
  2827. int i, count = 0;
  2828. X509_INFO *itmp = NULL;
  2829. if(ca_info_blob->len > (size_t)INT_MAX)
  2830. return CURLE_SSL_CACERT_BADFILE;
  2831. cbio = BIO_new_mem_buf(ca_info_blob->data, (int)ca_info_blob->len);
  2832. if(!cbio)
  2833. return CURLE_OUT_OF_MEMORY;
  2834. inf = PEM_X509_INFO_read_bio(cbio, NULL, NULL, NULL);
  2835. if(!inf) {
  2836. BIO_free(cbio);
  2837. return CURLE_SSL_CACERT_BADFILE;
  2838. }
  2839. /* add each entry from PEM file to x509_store */
  2840. for(i = 0; i < (int)sk_X509_INFO_num(inf); ++i) {
  2841. itmp = sk_X509_INFO_value(inf, (ossl_valsize_t)i);
  2842. if(itmp->x509) {
  2843. if(X509_STORE_add_cert(store, itmp->x509)) {
  2844. ++count;
  2845. }
  2846. else {
  2847. /* set count to 0 to return an error */
  2848. count = 0;
  2849. break;
  2850. }
  2851. }
  2852. if(itmp->crl) {
  2853. if(X509_STORE_add_crl(store, itmp->crl)) {
  2854. ++count;
  2855. }
  2856. else {
  2857. /* set count to 0 to return an error */
  2858. count = 0;
  2859. break;
  2860. }
  2861. }
  2862. }
  2863. #if defined(__clang__) && __clang_major__ >= 16
  2864. #pragma clang diagnostic push
  2865. #pragma clang diagnostic ignored "-Wcast-function-type-strict"
  2866. #endif
  2867. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  2868. #if defined(__clang__) && __clang_major__ >= 16
  2869. #pragma clang diagnostic pop
  2870. #endif
  2871. BIO_free(cbio);
  2872. /* if we did not end up importing anything, treat that as an error */
  2873. return (count > 0) ? CURLE_OK : CURLE_SSL_CACERT_BADFILE;
  2874. }
  2875. #ifdef USE_WIN32_CRYPTO
  2876. static CURLcode ossl_win_load_store(struct Curl_easy *data,
  2877. const char *win_store,
  2878. X509_STORE *store,
  2879. bool *padded)
  2880. {
  2881. CURLcode result = CURLE_OK;
  2882. HCERTSTORE hStore;
  2883. *padded = FALSE;
  2884. hStore = CertOpenSystemStoreA(0, win_store);
  2885. if(hStore) {
  2886. PCCERT_CONTEXT pContext = NULL;
  2887. /* The array of enhanced key usage OIDs will vary per certificate and
  2888. is declared outside of the loop so that rather than malloc/free each
  2889. iteration we can grow it with realloc, when necessary. */
  2890. CERT_ENHKEY_USAGE *enhkey_usage = NULL;
  2891. DWORD enhkey_usage_size = 0;
  2892. /* This loop makes a best effort to import all valid certificates from
  2893. the MS root store. If a certificate cannot be imported it is
  2894. skipped. 'result' is used to store only hard-fail conditions (such
  2895. as out of memory) that cause an early break. */
  2896. result = CURLE_OK;
  2897. for(;;) {
  2898. X509 *x509;
  2899. FILETIME now;
  2900. BYTE key_usage[2];
  2901. DWORD req_size;
  2902. const unsigned char *encoded_cert;
  2903. pContext = CertEnumCertificatesInStore(hStore, pContext);
  2904. if(!pContext)
  2905. break;
  2906. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  2907. else {
  2908. char cert_name[256];
  2909. if(!CertGetNameStringA(pContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0,
  2910. NULL, cert_name, sizeof(cert_name)))
  2911. infof(data, "SSL: unknown cert name");
  2912. else
  2913. infof(data, "SSL: Checking cert \"%s\"", cert_name);
  2914. }
  2915. #endif
  2916. encoded_cert = (const unsigned char *)pContext->pbCertEncoded;
  2917. if(!encoded_cert)
  2918. continue;
  2919. GetSystemTimeAsFileTime(&now);
  2920. if(CompareFileTime(&pContext->pCertInfo->NotBefore, &now) > 0 ||
  2921. CompareFileTime(&now, &pContext->pCertInfo->NotAfter) > 0)
  2922. continue;
  2923. /* If key usage exists check for signing attribute */
  2924. if(CertGetIntendedKeyUsage(pContext->dwCertEncodingType,
  2925. pContext->pCertInfo,
  2926. key_usage, sizeof(key_usage))) {
  2927. if(!(key_usage[0] & CERT_KEY_CERT_SIGN_KEY_USAGE))
  2928. continue;
  2929. }
  2930. else if(GetLastError())
  2931. continue;
  2932. /* If enhanced key usage exists check for server auth attribute.
  2933. *
  2934. * Note "In a Microsoft environment, a certificate might also have
  2935. * EKU extended properties that specify valid uses for the
  2936. * certificate." The call below checks both, and behavior varies
  2937. * depending on what is found. For more details see
  2938. * CertGetEnhancedKeyUsage doc.
  2939. */
  2940. if(CertGetEnhancedKeyUsage(pContext, 0, NULL, &req_size)) {
  2941. if(req_size && req_size > enhkey_usage_size) {
  2942. void *tmp = realloc(enhkey_usage, req_size);
  2943. if(!tmp) {
  2944. failf(data, "SSL: Out of memory allocating for OID list");
  2945. result = CURLE_OUT_OF_MEMORY;
  2946. break;
  2947. }
  2948. enhkey_usage = (CERT_ENHKEY_USAGE *)tmp;
  2949. enhkey_usage_size = req_size;
  2950. }
  2951. if(CertGetEnhancedKeyUsage(pContext, 0, enhkey_usage, &req_size)) {
  2952. if(!enhkey_usage->cUsageIdentifier) {
  2953. /* "If GetLastError returns CRYPT_E_NOT_FOUND, the certificate
  2954. is good for all uses. If it returns zero, the certificate
  2955. has no valid uses." */
  2956. if((HRESULT)GetLastError() != CRYPT_E_NOT_FOUND)
  2957. continue;
  2958. }
  2959. else {
  2960. DWORD i;
  2961. bool found = FALSE;
  2962. for(i = 0; i < enhkey_usage->cUsageIdentifier; ++i) {
  2963. if(!strcmp("1.3.6.1.5.5.7.3.1" /* OID server auth */,
  2964. enhkey_usage->rgpszUsageIdentifier[i])) {
  2965. found = TRUE;
  2966. break;
  2967. }
  2968. }
  2969. if(!found)
  2970. continue;
  2971. }
  2972. }
  2973. else
  2974. continue;
  2975. }
  2976. else
  2977. continue;
  2978. x509 = d2i_X509(NULL, &encoded_cert, (long)pContext->cbCertEncoded);
  2979. if(!x509)
  2980. continue;
  2981. /* Try to import the certificate. This may fail for legitimate reasons
  2982. such as duplicate certificate, which is allowed by MS but not
  2983. OpenSSL. */
  2984. if(X509_STORE_add_cert(store, x509) == 1) {
  2985. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  2986. infof(data, "SSL: Imported cert");
  2987. #endif
  2988. *padded = TRUE;
  2989. }
  2990. X509_free(x509);
  2991. }
  2992. free(enhkey_usage);
  2993. CertFreeCertificateContext(pContext);
  2994. CertCloseStore(hStore, 0);
  2995. if(result)
  2996. return result;
  2997. }
  2998. return result;
  2999. }
  3000. static CURLcode ossl_windows_load_anchors(struct Curl_cfilter *cf,
  3001. struct Curl_easy *data,
  3002. X509_STORE *store,
  3003. bool *padded)
  3004. {
  3005. /* Import certificates from the Windows root certificate store if
  3006. requested.
  3007. https://stackoverflow.com/questions/9507184/
  3008. https://github.com/d3x0r/SACK/blob/master/src/netlib/ssl_layer.c#L1037
  3009. https://datatracker.ietf.org/doc/html/rfc5280 */
  3010. const char *win_stores[] = {
  3011. "ROOT", /* Trusted Root Certification Authorities */
  3012. "CA" /* Intermediate Certification Authorities */
  3013. };
  3014. size_t i;
  3015. CURLcode result = CURLE_OK;
  3016. *padded = FALSE;
  3017. for(i = 0; i < CURL_ARRAYSIZE(win_stores); ++i) {
  3018. bool store_added = FALSE;
  3019. result = ossl_win_load_store(data, win_stores[i], store, &store_added);
  3020. if(result)
  3021. return result;
  3022. if(store_added) {
  3023. CURL_TRC_CF(data, cf, "added trust anchors from Windows %s store",
  3024. win_stores[i]);
  3025. *padded = TRUE;
  3026. }
  3027. else
  3028. infof(data, "error importing Windows %s store, continuing anyway",
  3029. win_stores[i]);
  3030. }
  3031. return result;
  3032. }
  3033. #endif /* USE_WIN32_CRYPTO */
  3034. static CURLcode ossl_load_trust_anchors(struct Curl_cfilter *cf,
  3035. struct Curl_easy *data,
  3036. struct ossl_ctx *octx,
  3037. X509_STORE *store)
  3038. {
  3039. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  3040. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  3041. CURLcode result = CURLE_OK;
  3042. const char * const ssl_cafile =
  3043. /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
  3044. (conn_config->ca_info_blob ? NULL : conn_config->CAfile);
  3045. const char * const ssl_capath = conn_config->CApath;
  3046. bool have_native_check = FALSE;
  3047. octx->store_is_empty = TRUE;
  3048. if(ssl_config->native_ca_store) {
  3049. #ifdef USE_WIN32_CRYPTO
  3050. bool added = FALSE;
  3051. result = ossl_windows_load_anchors(cf, data, store, &added);
  3052. if(result)
  3053. return result;
  3054. if(added) {
  3055. infof(data, " Native: Windows System Stores ROOT+CA");
  3056. octx->store_is_empty = FALSE;
  3057. }
  3058. #elif defined(USE_APPLE_SECTRUST)
  3059. infof(data, " Native: Apple SecTrust");
  3060. have_native_check = TRUE;
  3061. #endif
  3062. }
  3063. if(conn_config->ca_info_blob) {
  3064. result = load_cacert_from_memory(store, conn_config->ca_info_blob);
  3065. if(result) {
  3066. failf(data, "error adding trust anchors from certificate blob: %d",
  3067. result);
  3068. return result;
  3069. }
  3070. infof(data, " CA Blob from configuration");
  3071. octx->store_is_empty = FALSE;
  3072. }
  3073. if(ssl_cafile || ssl_capath) {
  3074. #ifdef HAVE_OPENSSL3
  3075. /* OpenSSL 3.0.0 has deprecated SSL_CTX_load_verify_locations */
  3076. if(ssl_cafile) {
  3077. if(!X509_STORE_load_file(store, ssl_cafile)) {
  3078. if(octx->store_is_empty && !have_native_check) {
  3079. /* Fail if we insist on successfully verifying the server. */
  3080. failf(data, "error adding trust anchors from file: %s", ssl_cafile);
  3081. return CURLE_SSL_CACERT_BADFILE;
  3082. }
  3083. else
  3084. infof(data, "error setting certificate file, continuing anyway");
  3085. }
  3086. infof(data, " CAfile: %s", ssl_cafile);
  3087. octx->store_is_empty = FALSE;
  3088. }
  3089. if(ssl_capath) {
  3090. if(!X509_STORE_load_path(store, ssl_capath)) {
  3091. if(octx->store_is_empty && !have_native_check) {
  3092. /* Fail if we insist on successfully verifying the server. */
  3093. failf(data, "error adding trust anchors from path: %s", ssl_capath);
  3094. return CURLE_SSL_CACERT_BADFILE;
  3095. }
  3096. else
  3097. infof(data, "error setting certificate path, continuing anyway");
  3098. }
  3099. infof(data, " CApath: %s", ssl_capath);
  3100. octx->store_is_empty = FALSE;
  3101. }
  3102. #else
  3103. /* tell OpenSSL where to find CA certificates that are used to verify the
  3104. server's certificate. */
  3105. if(!X509_STORE_load_locations(store, ssl_cafile, ssl_capath)) {
  3106. if(octx->store_is_empty && !have_native_check) {
  3107. /* Fail if we insist on successfully verifying the server. */
  3108. failf(data, "error adding trust anchors from locations:"
  3109. " CAfile: %s CApath: %s",
  3110. ssl_cafile ? ssl_cafile : "none",
  3111. ssl_capath ? ssl_capath : "none");
  3112. return CURLE_SSL_CACERT_BADFILE;
  3113. }
  3114. else {
  3115. infof(data, "error setting certificate verify locations,"
  3116. " continuing anyway");
  3117. }
  3118. }
  3119. if(ssl_cafile)
  3120. infof(data, " CAfile: %s", ssl_cafile);
  3121. if(ssl_capath)
  3122. infof(data, " CApath: %s", ssl_capath);
  3123. octx->store_is_empty = FALSE;
  3124. #endif
  3125. }
  3126. #ifdef CURL_CA_FALLBACK
  3127. if(octx->store_is_empty) {
  3128. /* verifying the peer without any CA certificates will not
  3129. work so use OpenSSL's built-in default as fallback */
  3130. X509_STORE_set_default_paths(store);
  3131. infof(data, " OpenSSL default paths (fallback)");
  3132. octx->store_is_empty = FALSE;
  3133. }
  3134. #endif
  3135. if(octx->store_is_empty && !have_native_check)
  3136. infof(data, " no trust anchors configured");
  3137. return result;
  3138. }
  3139. static CURLcode ossl_populate_x509_store(struct Curl_cfilter *cf,
  3140. struct Curl_easy *data,
  3141. struct ossl_ctx *octx,
  3142. X509_STORE *store)
  3143. {
  3144. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  3145. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  3146. CURLcode result = CURLE_OK;
  3147. X509_LOOKUP *lookup = NULL;
  3148. const char * const ssl_crlfile = ssl_config->primary.CRLfile;
  3149. unsigned long x509flags = 0;
  3150. CURL_TRC_CF(data, cf, "configuring OpenSSL's x509 trust store");
  3151. if(!store)
  3152. return CURLE_OUT_OF_MEMORY;
  3153. if(!conn_config->verifypeer) {
  3154. infof(data, "SSL Trust: peer verification disabled");
  3155. return CURLE_OK;
  3156. }
  3157. infof(data, "SSL Trust Anchors:");
  3158. result = ossl_load_trust_anchors(cf, data, octx, store);
  3159. if(result)
  3160. return result;
  3161. /* Does not make sense to load a CRL file without peer verification */
  3162. if(ssl_crlfile) {
  3163. /* tell OpenSSL where to find CRL file that is used to check certificate
  3164. * revocation */
  3165. lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
  3166. if(!lookup ||
  3167. (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
  3168. failf(data, "error loading CRL file: %s", ssl_crlfile);
  3169. return CURLE_SSL_CRL_BADFILE;
  3170. }
  3171. x509flags = X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
  3172. infof(data, " CRLfile: %s", ssl_crlfile);
  3173. }
  3174. /* Try building a chain using issuers in the trusted store first to avoid
  3175. problems with server-sent legacy intermediates. Newer versions of
  3176. OpenSSL do alternate chain checking by default but we do not know how to
  3177. determine that in a reliable manner.
  3178. https://web.archive.org/web/20190422050538/rt.openssl.org/Ticket/Display.html?id=3621
  3179. */
  3180. x509flags |= X509_V_FLAG_TRUSTED_FIRST;
  3181. if(!ssl_config->no_partialchain && !ssl_crlfile) {
  3182. /* Have intermediate certificates in the trust store be treated as
  3183. trust-anchors, in the same way as self-signed root CA certificates are.
  3184. This allows users to verify servers using the intermediate cert only,
  3185. instead of needing the whole chain.
  3186. Due to OpenSSL bug https://github.com/openssl/openssl/issues/5081 we
  3187. cannot do partial chains with a CRL check.
  3188. */
  3189. x509flags |= X509_V_FLAG_PARTIAL_CHAIN;
  3190. }
  3191. (void)X509_STORE_set_flags(store, x509flags);
  3192. return result;
  3193. }
  3194. #ifdef HAVE_SSL_X509_STORE_SHARE
  3195. /* key to use at `multi->proto_hash` */
  3196. #define MPROTO_OSSL_X509_KEY "tls:ossl:x509:share"
  3197. struct ossl_x509_share {
  3198. char *CAfile; /* CAfile path used to generate X509 store */
  3199. X509_STORE *store; /* cached X509 store or NULL if none */
  3200. struct curltime time; /* when the cached store was created */
  3201. BIT(store_is_empty); /* no certs/paths/blobs are in the store */
  3202. };
  3203. static void oss_x509_share_free(void *key, size_t key_len, void *p)
  3204. {
  3205. struct ossl_x509_share *share = p;
  3206. DEBUGASSERT(key_len == (sizeof(MPROTO_OSSL_X509_KEY)-1));
  3207. DEBUGASSERT(!memcmp(MPROTO_OSSL_X509_KEY, key, key_len));
  3208. (void)key;
  3209. (void)key_len;
  3210. if(share->store) {
  3211. X509_STORE_free(share->store);
  3212. }
  3213. free(share->CAfile);
  3214. free(share);
  3215. }
  3216. static bool
  3217. ossl_cached_x509_store_expired(const struct Curl_easy *data,
  3218. const struct ossl_x509_share *mb)
  3219. {
  3220. const struct ssl_general_config *cfg = &data->set.general_ssl;
  3221. if(cfg->ca_cache_timeout < 0)
  3222. return FALSE;
  3223. else {
  3224. struct curltime now = curlx_now();
  3225. timediff_t elapsed_ms = curlx_timediff(now, mb->time);
  3226. timediff_t timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000;
  3227. return elapsed_ms >= timeout_ms;
  3228. }
  3229. }
  3230. static bool
  3231. ossl_cached_x509_store_different(struct Curl_cfilter *cf,
  3232. const struct ossl_x509_share *mb)
  3233. {
  3234. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  3235. if(!mb->CAfile || !conn_config->CAfile)
  3236. return mb->CAfile != conn_config->CAfile;
  3237. return strcmp(mb->CAfile, conn_config->CAfile);
  3238. }
  3239. static X509_STORE *ossl_get_cached_x509_store(struct Curl_cfilter *cf,
  3240. const struct Curl_easy *data,
  3241. bool *pempty)
  3242. {
  3243. struct Curl_multi *multi = data->multi;
  3244. struct ossl_x509_share *share;
  3245. X509_STORE *store = NULL;
  3246. DEBUGASSERT(multi);
  3247. *pempty = TRUE;
  3248. share = multi ? Curl_hash_pick(&multi->proto_hash,
  3249. CURL_UNCONST(MPROTO_OSSL_X509_KEY),
  3250. sizeof(MPROTO_OSSL_X509_KEY)-1) : NULL;
  3251. if(share && share->store &&
  3252. !ossl_cached_x509_store_expired(data, share) &&
  3253. !ossl_cached_x509_store_different(cf, share)) {
  3254. store = share->store;
  3255. *pempty = share->store_is_empty;
  3256. }
  3257. return store;
  3258. }
  3259. static void ossl_set_cached_x509_store(struct Curl_cfilter *cf,
  3260. const struct Curl_easy *data,
  3261. X509_STORE *store,
  3262. bool is_empty)
  3263. {
  3264. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  3265. struct Curl_multi *multi = data->multi;
  3266. struct ossl_x509_share *share;
  3267. DEBUGASSERT(multi);
  3268. if(!multi)
  3269. return;
  3270. share = Curl_hash_pick(&multi->proto_hash,
  3271. CURL_UNCONST(MPROTO_OSSL_X509_KEY),
  3272. sizeof(MPROTO_OSSL_X509_KEY)-1);
  3273. if(!share) {
  3274. share = calloc(1, sizeof(*share));
  3275. if(!share)
  3276. return;
  3277. if(!Curl_hash_add2(&multi->proto_hash,
  3278. CURL_UNCONST(MPROTO_OSSL_X509_KEY),
  3279. sizeof(MPROTO_OSSL_X509_KEY)-1,
  3280. share, oss_x509_share_free)) {
  3281. free(share);
  3282. return;
  3283. }
  3284. }
  3285. if(X509_STORE_up_ref(store)) {
  3286. char *CAfile = NULL;
  3287. if(conn_config->CAfile) {
  3288. CAfile = strdup(conn_config->CAfile);
  3289. if(!CAfile) {
  3290. X509_STORE_free(store);
  3291. return;
  3292. }
  3293. }
  3294. if(share->store) {
  3295. X509_STORE_free(share->store);
  3296. free(share->CAfile);
  3297. }
  3298. share->time = curlx_now();
  3299. share->store = store;
  3300. share->store_is_empty = is_empty;
  3301. share->CAfile = CAfile;
  3302. }
  3303. }
  3304. CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf,
  3305. struct Curl_easy *data,
  3306. struct ossl_ctx *octx)
  3307. {
  3308. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  3309. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  3310. CURLcode result = CURLE_OK;
  3311. X509_STORE *cached_store;
  3312. bool cache_criteria_met, is_empty;
  3313. /* Consider the X509 store cacheable if it comes exclusively from a CAfile,
  3314. or no source is provided and we are falling back to OpenSSL's built-in
  3315. default. */
  3316. cache_criteria_met = (data->set.general_ssl.ca_cache_timeout != 0) &&
  3317. conn_config->verifypeer &&
  3318. !conn_config->CApath &&
  3319. !conn_config->ca_info_blob &&
  3320. !ssl_config->primary.CRLfile &&
  3321. !ssl_config->native_ca_store;
  3322. ERR_set_mark();
  3323. cached_store = ossl_get_cached_x509_store(cf, data, &is_empty);
  3324. if(cached_store && cache_criteria_met && X509_STORE_up_ref(cached_store)) {
  3325. SSL_CTX_set_cert_store(octx->ssl_ctx, cached_store);
  3326. octx->store_is_empty = is_empty;
  3327. }
  3328. else {
  3329. X509_STORE *store = SSL_CTX_get_cert_store(octx->ssl_ctx);
  3330. result = ossl_populate_x509_store(cf, data, octx, store);
  3331. if(result == CURLE_OK && cache_criteria_met) {
  3332. ossl_set_cached_x509_store(cf, data, store, octx->store_is_empty);
  3333. }
  3334. }
  3335. ERR_pop_to_mark();
  3336. return result;
  3337. }
  3338. #else /* HAVE_SSL_X509_STORE_SHARE */
  3339. CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf,
  3340. struct Curl_easy *data,
  3341. struct ossl_ctx *octx)
  3342. {
  3343. CURLcode result;
  3344. X509_STORE *store;
  3345. ERR_set_mark();
  3346. store = SSL_CTX_get_cert_store(octx->ssl_ctx);
  3347. result = ossl_populate_x509_store(cf, data, octx, store);
  3348. ERR_pop_to_mark();
  3349. return result;
  3350. }
  3351. #endif /* HAVE_SSL_X509_STORE_SHARE */
  3352. static CURLcode
  3353. ossl_init_session_and_alpns(struct ossl_ctx *octx,
  3354. struct Curl_cfilter *cf,
  3355. struct Curl_easy *data,
  3356. struct ssl_peer *peer,
  3357. const struct alpn_spec *alpns_requested,
  3358. Curl_ossl_init_session_reuse_cb *sess_reuse_cb)
  3359. {
  3360. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  3361. struct ssl_primary_config *conn_cfg = Curl_ssl_cf_get_primary_config(cf);
  3362. struct alpn_spec alpns;
  3363. char error_buffer[256];
  3364. CURLcode result;
  3365. Curl_alpn_copy(&alpns, alpns_requested);
  3366. octx->reused_session = FALSE;
  3367. if(Curl_ssl_scache_use(cf, data) && !conn_cfg->verifystatus) {
  3368. struct Curl_ssl_session *scs = NULL;
  3369. result = Curl_ssl_scache_take(cf, data, peer->scache_key, &scs);
  3370. if(!result && scs && scs->sdata && scs->sdata_len) {
  3371. const unsigned char *der_sessionid = scs->sdata;
  3372. size_t der_sessionid_size = scs->sdata_len;
  3373. SSL_SESSION *ssl_session = NULL;
  3374. /* If OpenSSL does not accept the session from the cache, this
  3375. * is not an error. We just continue without it. */
  3376. ssl_session = d2i_SSL_SESSION(NULL, &der_sessionid,
  3377. (long)der_sessionid_size);
  3378. if(ssl_session) {
  3379. if(!SSL_set_session(octx->ssl, ssl_session)) {
  3380. infof(data, "SSL: SSL_set_session not accepted, "
  3381. "continuing without: %s",
  3382. ossl_strerror(ERR_get_error(), error_buffer,
  3383. sizeof(error_buffer)));
  3384. }
  3385. else {
  3386. infof(data, "SSL reusing session with ALPN '%s'",
  3387. scs->alpn ? scs->alpn : "-");
  3388. octx->reused_session = TRUE;
  3389. #ifdef HAVE_OPENSSL_EARLYDATA
  3390. if(ssl_config->earlydata && scs->alpn &&
  3391. SSL_SESSION_get_max_early_data(ssl_session) &&
  3392. !cf->conn->connect_only &&
  3393. (SSL_version(octx->ssl) == TLS1_3_VERSION)) {
  3394. bool do_early_data = FALSE;
  3395. if(sess_reuse_cb) {
  3396. result = sess_reuse_cb(cf, data, &alpns, scs, &do_early_data);
  3397. if(result)
  3398. return result;
  3399. }
  3400. if(do_early_data) {
  3401. /* We only try the ALPN protocol the session used before,
  3402. * otherwise we might send early data for the wrong protocol */
  3403. Curl_alpn_restrict_to(&alpns, scs->alpn);
  3404. }
  3405. }
  3406. #else
  3407. (void)ssl_config;
  3408. (void)sess_reuse_cb;
  3409. #endif
  3410. }
  3411. SSL_SESSION_free(ssl_session);
  3412. }
  3413. else {
  3414. infof(data, "SSL session not accepted by OpenSSL, continuing without");
  3415. }
  3416. }
  3417. Curl_ssl_scache_return(cf, data, peer->scache_key, scs);
  3418. }
  3419. #ifdef HAS_ALPN_OPENSSL
  3420. if(alpns.count) {
  3421. struct alpn_proto_buf proto;
  3422. memset(&proto, 0, sizeof(proto));
  3423. result = Curl_alpn_to_proto_buf(&proto, &alpns);
  3424. if(result) {
  3425. failf(data, "Error determining ALPN");
  3426. return CURLE_SSL_CONNECT_ERROR;
  3427. }
  3428. if(SSL_set_alpn_protos(octx->ssl, proto.data, (int)proto.len)) {
  3429. failf(data, "Error setting ALPN");
  3430. return CURLE_SSL_CONNECT_ERROR;
  3431. }
  3432. }
  3433. #endif
  3434. return CURLE_OK;
  3435. }
  3436. #ifdef USE_ECH_OPENSSL
  3437. static CURLcode ossl_init_ech(struct ossl_ctx *octx,
  3438. struct Curl_cfilter *cf,
  3439. struct Curl_easy *data,
  3440. struct ssl_peer *peer)
  3441. {
  3442. unsigned char *ech_config = NULL;
  3443. size_t ech_config_len = 0;
  3444. char *outername = data->set.str[STRING_ECH_PUBLIC];
  3445. int trying_ech_now = 0;
  3446. CURLcode result;
  3447. if(!ECH_ENABLED(data))
  3448. return CURLE_OK;
  3449. if(data->set.tls_ech & CURLECH_GREASE) {
  3450. infof(data, "ECH: will GREASE ClientHello");
  3451. # ifdef HAVE_BORINGSSL_LIKE
  3452. SSL_set_enable_ech_grease(octx->ssl, 1);
  3453. # else
  3454. SSL_set_options(octx->ssl, SSL_OP_ECH_GREASE);
  3455. # endif
  3456. }
  3457. else if(data->set.tls_ech & CURLECH_CLA_CFG) {
  3458. # ifdef HAVE_BORINGSSL_LIKE
  3459. /* have to do base64 decode here for BoringSSL */
  3460. const char *b64 = data->set.str[STRING_ECH_CONFIG];
  3461. if(!b64) {
  3462. infof(data, "ECH: ECHConfig from command line empty");
  3463. return CURLE_SSL_CONNECT_ERROR;
  3464. }
  3465. ech_config_len = 2 * strlen(b64);
  3466. result = curlx_base64_decode(b64, &ech_config, &ech_config_len);
  3467. if(result || !ech_config) {
  3468. infof(data, "ECH: cannot base64 decode ECHConfig from command line");
  3469. if(data->set.tls_ech & CURLECH_HARD)
  3470. return result;
  3471. }
  3472. if(SSL_set1_ech_config_list(octx->ssl, ech_config,
  3473. ech_config_len) != 1) {
  3474. infof(data, "ECH: SSL_ECH_set1_ech_config_list failed");
  3475. if(data->set.tls_ech & CURLECH_HARD) {
  3476. free(ech_config);
  3477. return CURLE_SSL_CONNECT_ERROR;
  3478. }
  3479. }
  3480. free(ech_config);
  3481. trying_ech_now = 1;
  3482. # else
  3483. ech_config = (unsigned char *) data->set.str[STRING_ECH_CONFIG];
  3484. if(!ech_config) {
  3485. infof(data, "ECH: ECHConfig from command line empty");
  3486. return CURLE_SSL_CONNECT_ERROR;
  3487. }
  3488. ech_config_len = strlen(data->set.str[STRING_ECH_CONFIG]);
  3489. if(SSL_set1_ech_config_list(octx->ssl, ech_config,
  3490. ech_config_len) != 1) {
  3491. infof(data, "ECH: SSL_ECH_set1_ech_config_list failed");
  3492. if(data->set.tls_ech & CURLECH_HARD)
  3493. return CURLE_SSL_CONNECT_ERROR;
  3494. }
  3495. else
  3496. trying_ech_now = 1;
  3497. # endif
  3498. infof(data, "ECH: ECHConfig from command line");
  3499. }
  3500. else {
  3501. struct Curl_dns_entry *dns = NULL;
  3502. if(peer->hostname)
  3503. dns = Curl_dnscache_get(data, peer->hostname, peer->port,
  3504. cf->conn->ip_version);
  3505. if(!dns) {
  3506. infof(data, "ECH: requested but no DNS info available");
  3507. if(data->set.tls_ech & CURLECH_HARD)
  3508. return CURLE_SSL_CONNECT_ERROR;
  3509. }
  3510. else {
  3511. struct Curl_https_rrinfo *rinfo = NULL;
  3512. rinfo = dns->hinfo;
  3513. if(rinfo && rinfo->echconfiglist) {
  3514. unsigned char *ecl = rinfo->echconfiglist;
  3515. size_t elen = rinfo->echconfiglist_len;
  3516. infof(data, "ECH: ECHConfig from DoH HTTPS RR");
  3517. if(SSL_set1_ech_config_list(octx->ssl, ecl, elen) != 1) {
  3518. infof(data, "ECH: SSL_set1_ech_config_list failed");
  3519. if(data->set.tls_ech & CURLECH_HARD)
  3520. return CURLE_SSL_CONNECT_ERROR;
  3521. }
  3522. else {
  3523. trying_ech_now = 1;
  3524. infof(data, "ECH: imported ECHConfigList of length %zu", elen);
  3525. }
  3526. }
  3527. else {
  3528. infof(data, "ECH: requested but no ECHConfig available");
  3529. if(data->set.tls_ech & CURLECH_HARD)
  3530. return CURLE_SSL_CONNECT_ERROR;
  3531. }
  3532. Curl_resolv_unlink(data, &dns);
  3533. }
  3534. }
  3535. # ifdef HAVE_BORINGSSL_LIKE
  3536. if(trying_ech_now && outername) {
  3537. infof(data, "ECH: setting public_name not supported with BoringSSL");
  3538. return CURLE_SSL_CONNECT_ERROR;
  3539. }
  3540. # else
  3541. if(trying_ech_now && outername) {
  3542. infof(data, "ECH: inner: '%s', outer: '%s'",
  3543. peer->hostname ? peer->hostname : "NULL", outername);
  3544. result = SSL_ech_set1_server_names(octx->ssl,
  3545. peer->hostname, outername,
  3546. 0 /* do send outer */);
  3547. if(result != 1) {
  3548. infof(data, "ECH: rv failed to set server name(s) %d [ERROR]", result);
  3549. return CURLE_SSL_CONNECT_ERROR;
  3550. }
  3551. }
  3552. # endif /* HAVE_BORINGSSL_LIKE */
  3553. if(trying_ech_now
  3554. && SSL_set_min_proto_version(octx->ssl, TLS1_3_VERSION) != 1) {
  3555. infof(data, "ECH: cannot force TLSv1.3 [ERROR]");
  3556. return CURLE_SSL_CONNECT_ERROR;
  3557. }
  3558. return CURLE_OK;
  3559. }
  3560. #endif /* USE_ECH_OPENSSL */
  3561. static CURLcode ossl_init_ssl(struct ossl_ctx *octx,
  3562. struct Curl_cfilter *cf,
  3563. struct Curl_easy *data,
  3564. struct ssl_peer *peer,
  3565. const struct alpn_spec *alpns_requested,
  3566. void *ssl_user_data,
  3567. Curl_ossl_init_session_reuse_cb *sess_reuse_cb)
  3568. {
  3569. /* Let's make an SSL structure */
  3570. if(octx->ssl)
  3571. SSL_free(octx->ssl);
  3572. octx->ssl = SSL_new(octx->ssl_ctx);
  3573. if(!octx->ssl) {
  3574. failf(data, "SSL: could not create a context (handle)");
  3575. return CURLE_OUT_OF_MEMORY;
  3576. }
  3577. SSL_set_app_data(octx->ssl, ssl_user_data);
  3578. #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_OCSP)
  3579. if(Curl_ssl_cf_get_primary_config(cf)->verifystatus)
  3580. SSL_set_tlsext_status_type(octx->ssl, TLSEXT_STATUSTYPE_ocsp);
  3581. #endif
  3582. SSL_set_connect_state(octx->ssl);
  3583. if(peer->sni) {
  3584. if(!SSL_set_tlsext_host_name(octx->ssl, peer->sni)) {
  3585. failf(data, "Failed set SNI");
  3586. return CURLE_SSL_CONNECT_ERROR;
  3587. }
  3588. }
  3589. #ifdef USE_ECH_OPENSSL
  3590. {
  3591. CURLcode result = ossl_init_ech(octx, cf, data, peer);
  3592. if(result)
  3593. return result;
  3594. }
  3595. #endif /* USE_ECH_OPENSSL */
  3596. return ossl_init_session_and_alpns(octx, cf, data, peer,
  3597. alpns_requested, sess_reuse_cb);
  3598. }
  3599. static CURLcode ossl_init_method(struct Curl_cfilter *cf,
  3600. struct Curl_easy *data,
  3601. struct ssl_peer *peer,
  3602. const SSL_METHOD **pmethod,
  3603. unsigned int *pssl_version_min)
  3604. {
  3605. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  3606. *pmethod = NULL;
  3607. *pssl_version_min = conn_config->version;
  3608. switch(peer->transport) {
  3609. case TRNSPRT_TCP:
  3610. /* check to see if we have been told to use an explicit SSL/TLS version */
  3611. switch(*pssl_version_min) {
  3612. case CURL_SSLVERSION_DEFAULT:
  3613. case CURL_SSLVERSION_TLSv1:
  3614. case CURL_SSLVERSION_TLSv1_0:
  3615. case CURL_SSLVERSION_TLSv1_1:
  3616. case CURL_SSLVERSION_TLSv1_2:
  3617. case CURL_SSLVERSION_TLSv1_3:
  3618. /* it will be handled later with the context options */
  3619. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  3620. *pmethod = TLS_client_method();
  3621. #else
  3622. *pmethod = SSLv23_client_method();
  3623. #endif
  3624. break;
  3625. case CURL_SSLVERSION_SSLv2:
  3626. failf(data, "No SSLv2 support");
  3627. return CURLE_NOT_BUILT_IN;
  3628. case CURL_SSLVERSION_SSLv3:
  3629. failf(data, "No SSLv3 support");
  3630. return CURLE_NOT_BUILT_IN;
  3631. default:
  3632. failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
  3633. return CURLE_SSL_CONNECT_ERROR;
  3634. }
  3635. break;
  3636. case TRNSPRT_QUIC:
  3637. *pssl_version_min = CURL_SSLVERSION_TLSv1_3;
  3638. if(conn_config->version_max &&
  3639. (conn_config->version_max != CURL_SSLVERSION_MAX_DEFAULT) &&
  3640. (conn_config->version_max != CURL_SSLVERSION_MAX_TLSv1_3)) {
  3641. failf(data, "QUIC needs at least TLS version 1.3");
  3642. return CURLE_SSL_CONNECT_ERROR;
  3643. }
  3644. #ifdef USE_OPENSSL_QUIC
  3645. *pmethod = OSSL_QUIC_client_method();
  3646. #elif (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  3647. *pmethod = TLS_method();
  3648. #else
  3649. *pmethod = SSLv23_client_method();
  3650. #endif
  3651. break;
  3652. default:
  3653. failf(data, "unsupported transport %d in SSL init", peer->transport);
  3654. return CURLE_SSL_CONNECT_ERROR;
  3655. }
  3656. return *pmethod ? CURLE_OK : CURLE_SSL_CONNECT_ERROR;
  3657. }
  3658. CURLcode Curl_ossl_ctx_init(struct ossl_ctx *octx,
  3659. struct Curl_cfilter *cf,
  3660. struct Curl_easy *data,
  3661. struct ssl_peer *peer,
  3662. const struct alpn_spec *alpns_requested,
  3663. Curl_ossl_ctx_setup_cb *cb_setup,
  3664. void *cb_user_data,
  3665. Curl_ossl_new_session_cb *cb_new_session,
  3666. void *ssl_user_data,
  3667. Curl_ossl_init_session_reuse_cb *sess_reuse_cb)
  3668. {
  3669. CURLcode result = CURLE_OK;
  3670. const char *ciphers;
  3671. const SSL_METHOD *req_method = NULL;
  3672. ctx_option_t ctx_options = 0;
  3673. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  3674. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  3675. char * const ssl_cert = ssl_config->primary.clientcert;
  3676. const struct curl_blob *ssl_cert_blob = ssl_config->primary.cert_blob;
  3677. const char * const ssl_cert_type = ssl_config->cert_type;
  3678. unsigned int ssl_version_min;
  3679. char error_buffer[256];
  3680. /* Make funny stuff to get random input */
  3681. result = ossl_seed(data);
  3682. if(result)
  3683. return result;
  3684. ssl_config->certverifyresult = !X509_V_OK;
  3685. result = ossl_init_method(cf, data, peer, &req_method, &ssl_version_min);
  3686. if(result)
  3687. return result;
  3688. DEBUGASSERT(req_method);
  3689. DEBUGASSERT(!octx->ssl_ctx);
  3690. octx->ssl_ctx =
  3691. #ifdef OPENSSL_HAS_PROVIDERS
  3692. data->state.libctx ?
  3693. SSL_CTX_new_ex(data->state.libctx, data->state.propq, req_method):
  3694. #endif
  3695. SSL_CTX_new(req_method);
  3696. if(!octx->ssl_ctx) {
  3697. failf(data, "SSL: could not create a context: %s",
  3698. ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer)));
  3699. return CURLE_OUT_OF_MEMORY;
  3700. }
  3701. if(cb_setup) {
  3702. result = cb_setup(cf, data, cb_user_data);
  3703. if(result)
  3704. return result;
  3705. }
  3706. if(data->set.fdebug && data->set.verbose) {
  3707. /* the SSL trace callback is only used for verbose logging */
  3708. SSL_CTX_set_msg_callback(octx->ssl_ctx, ossl_trace);
  3709. SSL_CTX_set_msg_callback_arg(octx->ssl_ctx, cf);
  3710. }
  3711. /* OpenSSL contains code to work around lots of bugs and flaws in various
  3712. SSL-implementations. SSL_CTX_set_options() is used to enabled those
  3713. work-arounds. The manpage for this option states that SSL_OP_ALL enables
  3714. all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
  3715. enable the bug workaround options if compatibility with somewhat broken
  3716. implementations is desired."
  3717. The "-no_ticket" option was introduced in OpenSSL 0.9.8j. it is a flag to
  3718. disable "rfc4507bis session ticket support". rfc4507bis was later turned
  3719. into the proper RFC5077: https://datatracker.ietf.org/doc/html/rfc5077
  3720. The enabled extension concerns the session management. I wonder how often
  3721. libcurl stops a connection and then resumes a TLS session. Also, sending
  3722. the session data is some overhead. I suggest that you just use your
  3723. proposed patch (which explicitly disables TICKET).
  3724. If someone writes an application with libcurl and OpenSSL who wants to
  3725. enable the feature, one can do this in the SSL callback.
  3726. SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
  3727. interoperability with web server Netscape Enterprise Server 2.0.1 which
  3728. was released back in 1996.
  3729. Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
  3730. become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
  3731. CVE-2010-4180 when using previous OpenSSL versions we no longer enable
  3732. this option regardless of OpenSSL version and SSL_OP_ALL definition.
  3733. OpenSSL added a work-around for an SSL 3.0/TLS 1.0 CBC vulnerability:
  3734. https://web.archive.org/web/20240114184648/openssl.org/~bodo/tls-cbc.txt.
  3735. In 0.9.6e they added a bit to SSL_OP_ALL that _disables_ that work-around
  3736. despite the fact that SSL_OP_ALL is documented to do "rather harmless"
  3737. workarounds. In order to keep the secure work-around, the
  3738. SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit must not be set.
  3739. */
  3740. ctx_options = SSL_OP_ALL | SSL_OP_NO_TICKET | SSL_OP_NO_COMPRESSION;
  3741. /* mitigate CVE-2010-4180 */
  3742. ctx_options &= ~(ctx_option_t)SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
  3743. /* unless the user explicitly asks to allow the protocol vulnerability we
  3744. use the work-around */
  3745. if(!ssl_config->enable_beast)
  3746. ctx_options &= ~(ctx_option_t)SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
  3747. switch(ssl_version_min) {
  3748. case CURL_SSLVERSION_SSLv2:
  3749. case CURL_SSLVERSION_SSLv3:
  3750. return CURLE_NOT_BUILT_IN;
  3751. /* "--tlsv<x.y>" options mean TLS >= version <x.y> */
  3752. case CURL_SSLVERSION_DEFAULT:
  3753. case CURL_SSLVERSION_TLSv1: /* TLS >= version 1.0 */
  3754. case CURL_SSLVERSION_TLSv1_0: /* TLS >= version 1.0 */
  3755. case CURL_SSLVERSION_TLSv1_1: /* TLS >= version 1.1 */
  3756. case CURL_SSLVERSION_TLSv1_2: /* TLS >= version 1.2 */
  3757. case CURL_SSLVERSION_TLSv1_3: /* TLS >= version 1.3 */
  3758. /* asking for any TLS version as the minimum, means no SSL versions
  3759. allowed */
  3760. ctx_options |= SSL_OP_NO_SSLv2;
  3761. ctx_options |= SSL_OP_NO_SSLv3;
  3762. #if HAS_MODERN_SET_PROTO_VER /* 1.1.0 */
  3763. result = ossl_set_ssl_version_min_max(cf, octx->ssl_ctx, ssl_version_min);
  3764. #else
  3765. result = ossl_set_ssl_version_min_max_legacy(&ctx_options, cf, data);
  3766. #endif
  3767. if(result)
  3768. return result;
  3769. break;
  3770. default:
  3771. failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
  3772. return CURLE_SSL_CONNECT_ERROR;
  3773. }
  3774. SSL_CTX_set_options(octx->ssl_ctx, ctx_options);
  3775. SSL_CTX_set_read_ahead(octx->ssl_ctx, 1);
  3776. /* Max TLS1.2 record size 0x4000 + 0x800.
  3777. OpenSSL supports processing "jumbo TLS record" (8 TLS records) in one go
  3778. for some algorithms, so match that here.
  3779. Experimentation shows that a slightly larger buffer is needed
  3780. to avoid short reads.
  3781. However using a large buffer (8 packets) actually decreases performance.
  3782. 4 packets is better.
  3783. */
  3784. #ifdef HAVE_SSL_CTX_SET_DEFAULT_READ_BUFFER_LEN
  3785. SSL_CTX_set_default_read_buffer_len(octx->ssl_ctx, 0x401e * 4);
  3786. #endif
  3787. /* We do retry writes sometimes from another buffer address */
  3788. SSL_CTX_set_mode(octx->ssl_ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  3789. ciphers = conn_config->cipher_list;
  3790. if(!ciphers && (peer->transport != TRNSPRT_QUIC))
  3791. ciphers = DEFAULT_CIPHER_SELECTION;
  3792. if(ciphers && (ssl_version_min < CURL_SSLVERSION_TLSv1_3)) {
  3793. if(!SSL_CTX_set_cipher_list(octx->ssl_ctx, ciphers)) {
  3794. failf(data, "failed setting cipher list: %s", ciphers);
  3795. return CURLE_SSL_CIPHER;
  3796. }
  3797. infof(data, "Cipher selection: %s", ciphers);
  3798. }
  3799. #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
  3800. {
  3801. const char *ciphers13 = conn_config->cipher_list13;
  3802. if(ciphers13 &&
  3803. (!conn_config->version_max ||
  3804. (conn_config->version_max == CURL_SSLVERSION_MAX_DEFAULT) ||
  3805. (conn_config->version_max >= CURL_SSLVERSION_MAX_TLSv1_3))) {
  3806. if(!SSL_CTX_set_ciphersuites(octx->ssl_ctx, ciphers13)) {
  3807. failf(data, "failed setting TLS 1.3 cipher suite: %s", ciphers13);
  3808. return CURLE_SSL_CIPHER;
  3809. }
  3810. infof(data, "TLS 1.3 cipher selection: %s", ciphers13);
  3811. }
  3812. }
  3813. #endif
  3814. if(ssl_cert || ssl_cert_blob || ssl_cert_type) {
  3815. result = client_cert(data, octx->ssl_ctx,
  3816. ssl_cert, ssl_cert_blob, ssl_cert_type,
  3817. ssl_config->key, ssl_config->key_blob,
  3818. ssl_config->key_type, ssl_config->key_passwd);
  3819. if(result)
  3820. /* failf() is already done in client_cert() */
  3821. return result;
  3822. }
  3823. #ifdef HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH
  3824. /* OpenSSL 1.1.1 requires clients to opt-in for PHA */
  3825. SSL_CTX_set_post_handshake_auth(octx->ssl_ctx, 1);
  3826. #endif
  3827. {
  3828. const char *curves = conn_config->curves;
  3829. if(curves) {
  3830. #ifdef HAVE_BORINGSSL_LIKE
  3831. #define OSSL_CURVE_CAST(x) (x)
  3832. #else
  3833. #define OSSL_CURVE_CAST(x) (char *)CURL_UNCONST(x)
  3834. #endif
  3835. if(!SSL_CTX_set1_curves_list(octx->ssl_ctx, OSSL_CURVE_CAST(curves))) {
  3836. failf(data, "failed setting curves list: '%s'", curves);
  3837. return CURLE_SSL_CIPHER;
  3838. }
  3839. }
  3840. }
  3841. #ifdef HAVE_SSL_CTX_SET1_SIGALGS
  3842. #define OSSL_SIGALG_CAST(x) OSSL_CURVE_CAST(x)
  3843. {
  3844. const char *signature_algorithms = conn_config->signature_algorithms;
  3845. if(signature_algorithms) {
  3846. if(!SSL_CTX_set1_sigalgs_list(octx->ssl_ctx,
  3847. OSSL_SIGALG_CAST(signature_algorithms))) {
  3848. failf(data, "failed setting signature algorithms: '%s'",
  3849. signature_algorithms);
  3850. return CURLE_SSL_CIPHER;
  3851. }
  3852. }
  3853. }
  3854. #endif
  3855. #if defined(HAVE_OPENSSL_SRP) && defined(USE_TLS_SRP)
  3856. if(ssl_config->primary.username && Curl_auth_allowed_to_host(data)) {
  3857. char * const ssl_username = ssl_config->primary.username;
  3858. char * const ssl_password = ssl_config->primary.password;
  3859. infof(data, "Using TLS-SRP username: %s", ssl_username);
  3860. if(!SSL_CTX_set_srp_username(octx->ssl_ctx, ssl_username)) {
  3861. failf(data, "Unable to set SRP username");
  3862. return CURLE_BAD_FUNCTION_ARGUMENT;
  3863. }
  3864. if(!SSL_CTX_set_srp_password(octx->ssl_ctx, ssl_password)) {
  3865. failf(data, "failed setting SRP password");
  3866. return CURLE_BAD_FUNCTION_ARGUMENT;
  3867. }
  3868. if(!conn_config->cipher_list) {
  3869. infof(data, "Setting cipher list SRP");
  3870. if(!SSL_CTX_set_cipher_list(octx->ssl_ctx, "SRP")) {
  3871. failf(data, "failed setting SRP cipher list");
  3872. return CURLE_SSL_CIPHER;
  3873. }
  3874. }
  3875. }
  3876. #endif /* HAVE_OPENSSL_SRP && USE_TLS_SRP */
  3877. /* OpenSSL always tries to verify the peer. By setting the failure mode
  3878. * to NONE, we allow the connect to complete, regardless of the outcome.
  3879. * We then explicitly check the result and may try alternatives like
  3880. * Apple's SecTrust for verification. */
  3881. SSL_CTX_set_verify(octx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  3882. /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */
  3883. #ifdef HAVE_KEYLOG_CALLBACK
  3884. if(Curl_tls_keylog_enabled()) {
  3885. SSL_CTX_set_keylog_callback(octx->ssl_ctx, ossl_keylog_callback);
  3886. }
  3887. #endif
  3888. if(cb_new_session) {
  3889. /* Enable the session cache because it is a prerequisite for the
  3890. * "new session" callback. Use the "external storage" mode to prevent
  3891. * OpenSSL from creating an internal session cache.
  3892. */
  3893. SSL_CTX_set_session_cache_mode(octx->ssl_ctx,
  3894. SSL_SESS_CACHE_CLIENT |
  3895. SSL_SESS_CACHE_NO_INTERNAL);
  3896. SSL_CTX_sess_set_new_cb(octx->ssl_ctx, cb_new_session);
  3897. }
  3898. /* give application a chance to interfere with SSL set up. */
  3899. if(data->set.ssl.fsslctx) {
  3900. /* When a user callback is installed to modify the SSL_CTX,
  3901. * we need to do the full initialization before calling it.
  3902. * See: #11800 */
  3903. if(!octx->x509_store_setup) {
  3904. result = Curl_ssl_setup_x509_store(cf, data, octx);
  3905. if(result)
  3906. return result;
  3907. octx->x509_store_setup = TRUE;
  3908. }
  3909. Curl_set_in_callback(data, TRUE);
  3910. result = (*data->set.ssl.fsslctx)(data, octx->ssl_ctx,
  3911. data->set.ssl.fsslctxp);
  3912. Curl_set_in_callback(data, FALSE);
  3913. if(result) {
  3914. failf(data, "error signaled by ssl ctx callback");
  3915. return result;
  3916. }
  3917. }
  3918. return ossl_init_ssl(octx, cf, data, peer, alpns_requested,
  3919. ssl_user_data, sess_reuse_cb);
  3920. }
  3921. static CURLcode ossl_on_session_reuse(struct Curl_cfilter *cf,
  3922. struct Curl_easy *data,
  3923. struct alpn_spec *alpns,
  3924. struct Curl_ssl_session *scs,
  3925. bool *do_early_data)
  3926. {
  3927. struct ssl_connect_data *connssl = cf->ctx;
  3928. CURLcode result = CURLE_OK;
  3929. *do_early_data = FALSE;
  3930. connssl->earlydata_max = scs->earlydata_max;
  3931. if(!connssl->earlydata_max) {
  3932. CURL_TRC_CF(data, cf, "SSL session does not allow earlydata");
  3933. }
  3934. else if(!Curl_alpn_contains_proto(alpns, scs->alpn)) {
  3935. CURL_TRC_CF(data, cf, "SSL session has different ALPN, no early data");
  3936. }
  3937. else {
  3938. infof(data, "SSL session allows %zu bytes of early data, "
  3939. "reusing ALPN '%s'", connssl->earlydata_max, scs->alpn);
  3940. connssl->earlydata_state = ssl_earlydata_await;
  3941. connssl->state = ssl_connection_deferred;
  3942. result = Curl_alpn_set_negotiated(cf, data, connssl,
  3943. (const unsigned char *)scs->alpn,
  3944. scs->alpn ? strlen(scs->alpn) : 0);
  3945. *do_early_data = !result;
  3946. }
  3947. return result;
  3948. }
  3949. void Curl_ossl_report_handshake(struct Curl_easy *data,
  3950. struct ossl_ctx *octx)
  3951. {
  3952. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  3953. if(Curl_trc_is_verbose(data)) {
  3954. int psigtype_nid = NID_undef;
  3955. const char *negotiated_group_name = NULL;
  3956. #ifdef HAVE_OPENSSL3
  3957. SSL_get_peer_signature_type_nid(octx->ssl, &psigtype_nid);
  3958. #if OPENSSL_VERSION_NUMBER >= 0x30200000L
  3959. negotiated_group_name = SSL_get0_group_name(octx->ssl);
  3960. #else
  3961. negotiated_group_name =
  3962. OBJ_nid2sn(SSL_get_negotiated_group(octx->ssl) & 0x0000FFFF);
  3963. #endif
  3964. #endif
  3965. /* Informational message */
  3966. infof(data, "SSL connection using %s / %s / %s / %s",
  3967. SSL_get_version(octx->ssl),
  3968. SSL_get_cipher(octx->ssl),
  3969. negotiated_group_name ? negotiated_group_name : "[blank]",
  3970. OBJ_nid2sn(psigtype_nid));
  3971. }
  3972. #else
  3973. (void)data;
  3974. (void)octx;
  3975. #endif /* CURL_DISABLE_VERBOSE_STRINGS */
  3976. }
  3977. static CURLcode ossl_connect_step1(struct Curl_cfilter *cf,
  3978. struct Curl_easy *data)
  3979. {
  3980. struct ssl_connect_data *connssl = cf->ctx;
  3981. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  3982. BIO *bio;
  3983. CURLcode result;
  3984. DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
  3985. DEBUGASSERT(octx);
  3986. result = Curl_ossl_ctx_init(octx, cf, data, &connssl->peer,
  3987. connssl->alpn, NULL, NULL,
  3988. ossl_new_session_cb, cf,
  3989. ossl_on_session_reuse);
  3990. if(result)
  3991. return result;
  3992. octx->bio_method = ossl_bio_cf_method_create();
  3993. if(!octx->bio_method)
  3994. return CURLE_OUT_OF_MEMORY;
  3995. bio = BIO_new(octx->bio_method);
  3996. if(!bio)
  3997. return CURLE_OUT_OF_MEMORY;
  3998. BIO_set_data(bio, cf);
  3999. #ifdef HAVE_SSL_SET0_WBIO
  4000. /* with OpenSSL v1.1.1 we get an alternative to SSL_set_bio() that works
  4001. * without backward compat quirks. Every call takes one reference, so we
  4002. * up it and pass. SSL* then owns it and will free.
  4003. * We check on the function in configure, since LibreSSL and friends
  4004. * each have their own versions to add support for this. */
  4005. BIO_up_ref(bio);
  4006. SSL_set0_rbio(octx->ssl, bio);
  4007. SSL_set0_wbio(octx->ssl, bio);
  4008. #else
  4009. SSL_set_bio(octx->ssl, bio, bio);
  4010. #endif
  4011. #ifdef HAS_ALPN_OPENSSL
  4012. if(connssl->alpn && (connssl->state != ssl_connection_deferred)) {
  4013. struct alpn_proto_buf proto;
  4014. memset(&proto, 0, sizeof(proto));
  4015. Curl_alpn_to_proto_str(&proto, connssl->alpn);
  4016. infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
  4017. }
  4018. #endif
  4019. connssl->connecting_state = ssl_connect_2;
  4020. return CURLE_OK;
  4021. }
  4022. #ifdef USE_ECH_OPENSSL
  4023. /* If we have retry configs, then trace those out */
  4024. static void ossl_trace_ech_retry_configs(struct Curl_easy *data, SSL* ssl,
  4025. int reason)
  4026. {
  4027. CURLcode result = CURLE_OK;
  4028. size_t rcl = 0;
  4029. int rv = 1;
  4030. # ifndef HAVE_BORINGSSL_LIKE
  4031. char *inner = NULL;
  4032. unsigned char *rcs = NULL;
  4033. char *outer = NULL;
  4034. # else
  4035. const char *inner = NULL;
  4036. const uint8_t *rcs = NULL;
  4037. const char *outer = NULL;
  4038. size_t out_name_len = 0;
  4039. int servername_type = 0;
  4040. # endif
  4041. /* nothing to trace if not doing ECH */
  4042. if(!ECH_ENABLED(data))
  4043. return;
  4044. # ifndef HAVE_BORINGSSL_LIKE
  4045. rv = SSL_ech_get1_retry_config(ssl, &rcs, &rcl);
  4046. # else
  4047. SSL_get0_ech_retry_configs(ssl, &rcs, &rcl);
  4048. rv = (int)rcl;
  4049. # endif
  4050. if(rv && rcs) {
  4051. char *b64str = NULL;
  4052. size_t blen = 0;
  4053. result = curlx_base64_encode((const char *)rcs, rcl, &b64str, &blen);
  4054. if(!result && b64str) {
  4055. infof(data, "ECH: retry_configs %s", b64str);
  4056. free(b64str);
  4057. #ifndef HAVE_BORINGSSL_LIKE
  4058. rv = SSL_ech_get1_status(ssl, &inner, &outer);
  4059. infof(data, "ECH: retry_configs for %s from %s, %d %d",
  4060. inner ? inner : "NULL", outer ? outer : "NULL", reason, rv);
  4061. #else
  4062. rv = SSL_ech_accepted(ssl);
  4063. servername_type = SSL_get_servername_type(ssl);
  4064. inner = SSL_get_servername(ssl, servername_type);
  4065. SSL_get0_ech_name_override(ssl, &outer, &out_name_len);
  4066. infof(data, "ECH: retry_configs for %s from %s, %d %d",
  4067. inner ? inner : "NULL", outer ? outer : "NULL", reason, rv);
  4068. #endif
  4069. }
  4070. }
  4071. else
  4072. infof(data, "ECH: no retry_configs (rv = %d)", rv);
  4073. # ifndef HAVE_BORINGSSL_LIKE
  4074. OPENSSL_free((void *)rcs);
  4075. # endif
  4076. return;
  4077. }
  4078. #endif
  4079. static CURLcode ossl_connect_step2(struct Curl_cfilter *cf,
  4080. struct Curl_easy *data)
  4081. {
  4082. int err;
  4083. struct ssl_connect_data *connssl = cf->ctx;
  4084. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4085. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  4086. DEBUGASSERT(ssl_connect_2 == connssl->connecting_state);
  4087. DEBUGASSERT(octx);
  4088. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  4089. ERR_clear_error();
  4090. err = SSL_connect(octx->ssl);
  4091. if(!octx->x509_store_setup) {
  4092. /* After having send off the ClientHello, we prepare the x509
  4093. * store to verify the coming certificate from the server */
  4094. CURLcode result = Curl_ssl_setup_x509_store(cf, data, octx);
  4095. if(result)
  4096. return result;
  4097. octx->x509_store_setup = TRUE;
  4098. }
  4099. #ifndef HAVE_KEYLOG_CALLBACK
  4100. /* If key logging is enabled, wait for the handshake to complete and then
  4101. * proceed with logging secrets (for TLS 1.2 or older).
  4102. */
  4103. if(Curl_tls_keylog_enabled() && !octx->keylog_done)
  4104. ossl_log_tls12_secret(octx->ssl, &octx->keylog_done);
  4105. #endif
  4106. /* 1 is fine
  4107. 0 is "not successful but was shut down controlled"
  4108. <0 is "handshake was not successful, because a fatal error occurred" */
  4109. if(err != 1) {
  4110. int detail = SSL_get_error(octx->ssl, err);
  4111. CURL_TRC_CF(data, cf, "SSL_connect() -> err=%d, detail=%d", err, detail);
  4112. if(SSL_ERROR_WANT_READ == detail) {
  4113. CURL_TRC_CF(data, cf, "SSL_connect() -> want recv");
  4114. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  4115. return CURLE_AGAIN;
  4116. }
  4117. if(SSL_ERROR_WANT_WRITE == detail) {
  4118. CURL_TRC_CF(data, cf, "SSL_connect() -> want send");
  4119. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  4120. return CURLE_AGAIN;
  4121. }
  4122. #ifdef SSL_ERROR_WANT_ASYNC
  4123. if(SSL_ERROR_WANT_ASYNC == detail) {
  4124. CURL_TRC_CF(data, cf, "SSL_connect() -> want async");
  4125. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  4126. return CURLE_AGAIN;
  4127. }
  4128. #endif
  4129. #ifdef SSL_ERROR_WANT_RETRY_VERIFY
  4130. if(SSL_ERROR_WANT_RETRY_VERIFY == detail) {
  4131. CURL_TRC_CF(data, cf, "SSL_connect() -> want retry_verify");
  4132. Curl_xfer_pause_recv(data, TRUE);
  4133. return CURLE_AGAIN;
  4134. }
  4135. #endif
  4136. else {
  4137. /* untreated error */
  4138. sslerr_t errdetail;
  4139. char error_buffer[256]="";
  4140. CURLcode result;
  4141. long lerr;
  4142. int lib;
  4143. int reason;
  4144. /* the connection failed, we are not waiting for anything else. */
  4145. connssl->connecting_state = ssl_connect_2;
  4146. /* Get the earliest error code from the thread's error queue and remove
  4147. the entry. */
  4148. errdetail = ERR_get_error();
  4149. /* Extract which lib and reason */
  4150. lib = ERR_GET_LIB(errdetail);
  4151. reason = ERR_GET_REASON(errdetail);
  4152. if((lib == ERR_LIB_SSL) &&
  4153. ((reason == SSL_R_CERTIFICATE_VERIFY_FAILED) ||
  4154. (reason == SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED))) {
  4155. result = CURLE_PEER_FAILED_VERIFICATION;
  4156. lerr = SSL_get_verify_result(octx->ssl);
  4157. if(lerr != X509_V_OK) {
  4158. ssl_config->certverifyresult = lerr;
  4159. failf(data, "SSL certificate problem: %s",
  4160. X509_verify_cert_error_string(lerr));
  4161. }
  4162. else
  4163. failf(data, "%s", "SSL certificate verification failed");
  4164. }
  4165. #ifdef SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED
  4166. /* SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED is only available on
  4167. OpenSSL version above v1.1.1, not LibreSSL, BoringSSL, or AWS-LC */
  4168. else if((lib == ERR_LIB_SSL) &&
  4169. (reason == SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED)) {
  4170. /* If client certificate is required, communicate the
  4171. error to client */
  4172. result = CURLE_SSL_CLIENTCERT;
  4173. failf(data, "TLS cert problem: %s",
  4174. ossl_strerror(errdetail, error_buffer, sizeof(error_buffer)));
  4175. }
  4176. #endif
  4177. #ifdef USE_ECH_OPENSSL
  4178. else if((lib == ERR_LIB_SSL) &&
  4179. # ifndef HAVE_BORINGSSL_LIKE
  4180. (reason == SSL_R_ECH_REQUIRED)) {
  4181. # else
  4182. (reason == SSL_R_ECH_REJECTED)) {
  4183. # endif
  4184. /* trace retry_configs if we got some */
  4185. ossl_trace_ech_retry_configs(data, octx->ssl, reason);
  4186. result = CURLE_ECH_REQUIRED;
  4187. failf(data, "ECH required: %s",
  4188. ossl_strerror(errdetail, error_buffer, sizeof(error_buffer)));
  4189. }
  4190. #endif
  4191. else {
  4192. result = CURLE_SSL_CONNECT_ERROR;
  4193. failf(data, "TLS connect error: %s",
  4194. ossl_strerror(errdetail, error_buffer, sizeof(error_buffer)));
  4195. }
  4196. /* detail is already set to the SSL error above */
  4197. /* If we e.g. use SSLv2 request-method and the server does not like us
  4198. * (RST connection, etc.), OpenSSL gives no explanation whatsoever and
  4199. * the SO_ERROR is also lost.
  4200. */
  4201. if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
  4202. char extramsg[80]="";
  4203. int sockerr = SOCKERRNO;
  4204. if(sockerr && detail == SSL_ERROR_SYSCALL)
  4205. curlx_strerror(sockerr, extramsg, sizeof(extramsg));
  4206. failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%d ",
  4207. extramsg[0] ? extramsg : SSL_ERROR_to_str(detail),
  4208. connssl->peer.hostname, connssl->peer.port);
  4209. }
  4210. return result;
  4211. }
  4212. }
  4213. else {
  4214. /* we connected fine, we are not waiting for anything else. */
  4215. connssl->connecting_state = ssl_connect_3;
  4216. Curl_ossl_report_handshake(data, octx);
  4217. #if defined(USE_ECH_OPENSSL) && !defined(HAVE_BORINGSSL_LIKE)
  4218. if(ECH_ENABLED(data)) {
  4219. char *inner = NULL, *outer = NULL;
  4220. const char *status = NULL;
  4221. int rv;
  4222. rv = SSL_ech_get1_status(octx->ssl, &inner, &outer);
  4223. switch(rv) {
  4224. case SSL_ECH_STATUS_SUCCESS:
  4225. status = "succeeded";
  4226. break;
  4227. case SSL_ECH_STATUS_GREASE_ECH:
  4228. status = "sent GREASE, got retry-configs";
  4229. break;
  4230. case SSL_ECH_STATUS_GREASE:
  4231. status = "sent GREASE";
  4232. break;
  4233. case SSL_ECH_STATUS_NOT_TRIED:
  4234. status = "not attempted";
  4235. break;
  4236. case SSL_ECH_STATUS_NOT_CONFIGURED:
  4237. status = "not configured";
  4238. break;
  4239. case SSL_ECH_STATUS_BACKEND:
  4240. status = "backend (unexpected)";
  4241. break;
  4242. case SSL_ECH_STATUS_FAILED:
  4243. status = "failed";
  4244. break;
  4245. case SSL_ECH_STATUS_BAD_CALL:
  4246. status = "bad call (unexpected)";
  4247. break;
  4248. case SSL_ECH_STATUS_BAD_NAME:
  4249. status = "bad name (unexpected)";
  4250. break;
  4251. default:
  4252. status = "unexpected status";
  4253. infof(data, "ECH: unexpected status %d",rv);
  4254. }
  4255. infof(data, "ECH: result: status is %s, inner is %s, outer is %s",
  4256. (status ? status : "NULL"),
  4257. (inner ? inner : "NULL"),
  4258. (outer ? outer : "NULL"));
  4259. OPENSSL_free(inner);
  4260. OPENSSL_free(outer);
  4261. if(rv == SSL_ECH_STATUS_GREASE_ECH) {
  4262. /* trace retry_configs if we got some */
  4263. ossl_trace_ech_retry_configs(data, octx->ssl, 0);
  4264. }
  4265. if(rv != SSL_ECH_STATUS_SUCCESS
  4266. && data->set.tls_ech & CURLECH_HARD) {
  4267. infof(data, "ECH: ech-hard failed");
  4268. return CURLE_SSL_CONNECT_ERROR;
  4269. }
  4270. }
  4271. else {
  4272. infof(data, "ECH: result: status is not attempted");
  4273. }
  4274. #endif /* USE_ECH_OPENSSL && !HAVE_BORINGSSL_LIKE */
  4275. #ifdef HAS_ALPN_OPENSSL
  4276. /* Sets data and len to negotiated protocol, len is 0 if no protocol was
  4277. * negotiated
  4278. */
  4279. if(connssl->alpn) {
  4280. const unsigned char *neg_protocol;
  4281. unsigned int len;
  4282. SSL_get0_alpn_selected(octx->ssl, &neg_protocol, &len);
  4283. return Curl_alpn_set_negotiated(cf, data, connssl, neg_protocol, len);
  4284. }
  4285. #endif
  4286. return CURLE_OK;
  4287. }
  4288. }
  4289. /*
  4290. * Heavily modified from:
  4291. * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
  4292. */
  4293. static CURLcode ossl_pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
  4294. const char *pinnedpubkey)
  4295. {
  4296. /* Scratch */
  4297. int len1 = 0, len2 = 0;
  4298. unsigned char *buff1 = NULL, *temp = NULL;
  4299. /* Result is returned to caller */
  4300. CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  4301. /* if a path was not specified, do not pin */
  4302. if(!pinnedpubkey)
  4303. return CURLE_OK;
  4304. if(!cert)
  4305. return result;
  4306. do {
  4307. /* Get the subjectPublicKeyInfo */
  4308. /* https://groups.google.com/group/mailing.openssl.users/browse_thread/thread/d61858dae102c6c7 */
  4309. len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
  4310. if(len1 < 1)
  4311. break; /* failed */
  4312. buff1 = temp = malloc(len1);
  4313. if(!buff1)
  4314. break; /* failed */
  4315. /* https://docs.openssl.org/master/man3/d2i_X509/ */
  4316. len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
  4317. /*
  4318. * These checks are verifying we got back the same values as when we
  4319. * sized the buffer. it is pretty weak since they should always be the
  4320. * same. But it gives us something to test.
  4321. */
  4322. if((len1 != len2) || !temp || ((temp - buff1) != len1))
  4323. break; /* failed */
  4324. /* End Gyrations */
  4325. /* The one good exit point */
  4326. result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
  4327. } while(0);
  4328. if(buff1)
  4329. free(buff1);
  4330. return result;
  4331. }
  4332. #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
  4333. !(defined(LIBRESSL_VERSION_NUMBER) && \
  4334. LIBRESSL_VERSION_NUMBER < 0x3060000fL) && \
  4335. !defined(HAVE_BORINGSSL_LIKE) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  4336. static void infof_certstack(struct Curl_easy *data, const SSL *ssl)
  4337. {
  4338. STACK_OF(X509) *certstack;
  4339. long verify_result;
  4340. int num_cert_levels;
  4341. int cert_level;
  4342. if(!Curl_trc_is_verbose(data))
  4343. return;
  4344. verify_result = SSL_get_verify_result(ssl);
  4345. if(verify_result != X509_V_OK)
  4346. certstack = SSL_get_peer_cert_chain(ssl);
  4347. else
  4348. certstack = SSL_get0_verified_chain(ssl);
  4349. if(!certstack)
  4350. return;
  4351. num_cert_levels = sk_X509_num(certstack);
  4352. for(cert_level = 0; cert_level < num_cert_levels; cert_level++) {
  4353. char cert_algorithm[80] = "";
  4354. char group_name_final[80] = "";
  4355. const X509_ALGOR *palg_cert = NULL;
  4356. const ASN1_OBJECT *paobj_cert = NULL;
  4357. X509 *current_cert;
  4358. EVP_PKEY *current_pkey;
  4359. int key_bits;
  4360. int key_sec_bits;
  4361. int get_group_name;
  4362. const char *type_name;
  4363. current_cert = sk_X509_value(certstack, cert_level);
  4364. if(!current_cert)
  4365. continue;
  4366. current_pkey = X509_get0_pubkey(current_cert);
  4367. if(!current_pkey)
  4368. continue;
  4369. X509_get0_signature(NULL, &palg_cert, current_cert);
  4370. X509_ALGOR_get0(&paobj_cert, NULL, NULL, palg_cert);
  4371. OBJ_obj2txt(cert_algorithm, sizeof(cert_algorithm), paobj_cert, 0);
  4372. key_bits = EVP_PKEY_bits(current_pkey);
  4373. #ifndef HAVE_OPENSSL3
  4374. #define EVP_PKEY_get_security_bits EVP_PKEY_security_bits
  4375. #endif
  4376. key_sec_bits = EVP_PKEY_get_security_bits(current_pkey);
  4377. #ifdef HAVE_OPENSSL3
  4378. {
  4379. char group_name[80] = "";
  4380. get_group_name = EVP_PKEY_get_group_name(current_pkey, group_name,
  4381. sizeof(group_name), NULL);
  4382. curl_msnprintf(group_name_final, sizeof(group_name_final), "/%s",
  4383. group_name);
  4384. }
  4385. type_name = EVP_PKEY_get0_type_name(current_pkey);
  4386. #else
  4387. get_group_name = 0;
  4388. type_name = NULL;
  4389. #endif
  4390. infof(data,
  4391. " Certificate level %d: "
  4392. "Public key type %s%s (%d/%d Bits/secBits), signed using %s",
  4393. cert_level, type_name ? type_name : "?",
  4394. get_group_name == 0 ? "" : group_name_final,
  4395. key_bits, key_sec_bits, cert_algorithm);
  4396. }
  4397. }
  4398. #else
  4399. #define infof_certstack(data, ssl)
  4400. #endif
  4401. static CURLcode ossl_check_issuer(struct Curl_cfilter *cf,
  4402. struct Curl_easy *data,
  4403. X509 *server_cert)
  4404. {
  4405. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  4406. X509 *issuer = NULL;
  4407. BIO *fp = NULL;
  4408. char err_buf[256]="";
  4409. bool strict = (conn_config->verifypeer || conn_config->verifyhost);
  4410. CURLcode result = CURLE_OK;
  4411. /* e.g. match issuer name with provided issuer certificate */
  4412. if(conn_config->issuercert_blob) {
  4413. fp = BIO_new_mem_buf(conn_config->issuercert_blob->data,
  4414. (int)conn_config->issuercert_blob->len);
  4415. if(!fp) {
  4416. failf(data, "BIO_new_mem_buf NULL, " OSSL_PACKAGE " error %s",
  4417. ossl_strerror(ERR_get_error(), err_buf, sizeof(err_buf)));
  4418. result = CURLE_OUT_OF_MEMORY;
  4419. goto out;
  4420. }
  4421. }
  4422. else if(conn_config->issuercert) {
  4423. fp = BIO_new(BIO_s_file());
  4424. if(!fp) {
  4425. failf(data, "BIO_new return NULL, " OSSL_PACKAGE " error %s",
  4426. ossl_strerror(ERR_get_error(), err_buf, sizeof(err_buf)));
  4427. result = CURLE_OUT_OF_MEMORY;
  4428. goto out;
  4429. }
  4430. if(BIO_read_filename(fp, conn_config->issuercert) <= 0) {
  4431. if(strict)
  4432. failf(data, "SSL: Unable to open issuer cert (%s)",
  4433. conn_config->issuercert);
  4434. result = CURLE_SSL_ISSUER_ERROR;
  4435. goto out;
  4436. }
  4437. }
  4438. if(fp) {
  4439. issuer = PEM_read_bio_X509(fp, NULL, ZERO_NULL, NULL);
  4440. if(!issuer) {
  4441. if(strict)
  4442. failf(data, "SSL: Unable to read issuer cert (%s)",
  4443. conn_config->issuercert);
  4444. result = CURLE_SSL_ISSUER_ERROR;
  4445. goto out;
  4446. }
  4447. if(X509_check_issued(issuer, server_cert) != X509_V_OK) {
  4448. if(strict)
  4449. failf(data, "SSL: Certificate issuer check failed (%s)",
  4450. conn_config->issuercert);
  4451. result = CURLE_SSL_ISSUER_ERROR;
  4452. goto out;
  4453. }
  4454. infof(data, " SSL certificate issuer check ok (%s)",
  4455. conn_config->issuercert);
  4456. }
  4457. out:
  4458. if(fp)
  4459. BIO_free(fp);
  4460. if(issuer)
  4461. X509_free(issuer);
  4462. return result;
  4463. }
  4464. static CURLcode ossl_check_pinned_key(struct Curl_cfilter *cf,
  4465. struct Curl_easy *data,
  4466. X509 *server_cert)
  4467. {
  4468. const char *ptr;
  4469. CURLcode result = CURLE_OK;
  4470. (void)cf;
  4471. #ifndef CURL_DISABLE_PROXY
  4472. ptr = Curl_ssl_cf_is_proxy(cf) ?
  4473. data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
  4474. data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  4475. #else
  4476. ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  4477. #endif
  4478. if(ptr) {
  4479. result = ossl_pkp_pin_peer_pubkey(data, server_cert, ptr);
  4480. if(result)
  4481. failf(data, "SSL: public key does not match pinned public key");
  4482. }
  4483. return result;
  4484. }
  4485. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  4486. #define MAX_CERT_NAME_LENGTH 2048
  4487. static CURLcode ossl_infof_cert(struct Curl_cfilter *cf,
  4488. struct Curl_easy *data,
  4489. X509 *server_cert)
  4490. {
  4491. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  4492. bool strict = (conn_config->verifypeer || conn_config->verifyhost);
  4493. BIO *mem = NULL;
  4494. struct dynbuf dname;
  4495. char err_buf[256] = "";
  4496. char *buf;
  4497. long len;
  4498. CURLcode result = CURLE_OK;
  4499. if(!Curl_trc_is_verbose(data))
  4500. return CURLE_OK;
  4501. curlx_dyn_init(&dname, MAX_CERT_NAME_LENGTH);
  4502. mem = BIO_new(BIO_s_mem());
  4503. if(!mem) {
  4504. failf(data, "BIO_new return NULL, " OSSL_PACKAGE " error %s",
  4505. ossl_strerror(ERR_get_error(), err_buf, sizeof(err_buf)));
  4506. result = CURLE_OUT_OF_MEMORY;
  4507. goto out;
  4508. }
  4509. infof(data, "%s certificate:", Curl_ssl_cf_is_proxy(cf) ?
  4510. "Proxy" : "Server");
  4511. result = x509_name_oneline(X509_get_subject_name(server_cert), &dname);
  4512. infof(data, " subject: %s", result ? "[NONE]" : curlx_dyn_ptr(&dname));
  4513. ASN1_TIME_print(mem, X509_get0_notBefore(server_cert));
  4514. len = BIO_get_mem_data(mem, (char **) &buf);
  4515. infof(data, " start date: %.*s", (int)len, buf);
  4516. (void)BIO_reset(mem);
  4517. ASN1_TIME_print(mem, X509_get0_notAfter(server_cert));
  4518. len = BIO_get_mem_data(mem, (char **) &buf);
  4519. infof(data, " expire date: %.*s", (int)len, buf);
  4520. (void)BIO_reset(mem);
  4521. result = x509_name_oneline(X509_get_issuer_name(server_cert), &dname);
  4522. if(result) {
  4523. if(strict)
  4524. failf(data, "SSL: could not get X509-issuer name");
  4525. result = CURLE_PEER_FAILED_VERIFICATION;
  4526. goto out;
  4527. }
  4528. infof(data, " issuer: %s", curlx_dyn_ptr(&dname));
  4529. out:
  4530. BIO_free(mem);
  4531. curlx_dyn_free(&dname);
  4532. return result;
  4533. }
  4534. #endif /* ! CURL_DISABLE_VERBOSE_STRINGS */
  4535. #ifdef USE_APPLE_SECTRUST
  4536. struct ossl_certs_ctx {
  4537. STACK_OF(X509) *sk;
  4538. size_t num_certs;
  4539. };
  4540. static CURLcode ossl_chain_get_der(struct Curl_cfilter *cf,
  4541. struct Curl_easy *data,
  4542. void *user_data,
  4543. size_t i,
  4544. unsigned char **pder,
  4545. size_t *pder_len)
  4546. {
  4547. struct ossl_certs_ctx *chain = user_data;
  4548. X509 *cert;
  4549. int der_len;
  4550. (void)cf;
  4551. (void)data;
  4552. *pder_len = 0;
  4553. *pder = NULL;
  4554. if(i >= chain->num_certs)
  4555. return CURLE_TOO_LARGE;
  4556. cert = sk_X509_value(chain->sk, (int)i);
  4557. if(!cert)
  4558. return CURLE_FAILED_INIT;
  4559. der_len = i2d_X509(cert, pder);
  4560. if(der_len < 0)
  4561. return CURLE_FAILED_INIT;
  4562. *pder_len = (size_t)der_len;
  4563. return CURLE_OK;
  4564. }
  4565. static CURLcode ossl_apple_verify(struct Curl_cfilter *cf,
  4566. struct Curl_easy *data,
  4567. struct ossl_ctx *octx,
  4568. struct ssl_peer *peer,
  4569. bool *pverified)
  4570. {
  4571. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  4572. struct ossl_certs_ctx chain;
  4573. CURLcode result;
  4574. memset(&chain, 0, sizeof(chain));
  4575. chain.sk = SSL_get_peer_cert_chain(octx->ssl);
  4576. chain.num_certs = chain.sk ? sk_X509_num(chain.sk) : 0;
  4577. if(!chain.num_certs &&
  4578. (conn_config->verifypeer || conn_config->verifyhost)) {
  4579. failf(data, "SSL: could not get peer certificate");
  4580. result = CURLE_PEER_FAILED_VERIFICATION;
  4581. }
  4582. else {
  4583. #ifdef HAVE_BORINGSSL_LIKE
  4584. const uint8_t *ocsp_data = NULL;
  4585. #else
  4586. unsigned char *ocsp_data = NULL;
  4587. #endif
  4588. long ocsp_len = 0;
  4589. if(conn_config->verifystatus && !octx->reused_session)
  4590. ocsp_len = (long)SSL_get_tlsext_status_ocsp_resp(octx->ssl, &ocsp_data);
  4591. /* SSL_get_tlsext_status_ocsp_resp() returns the length of the OCSP
  4592. response data or -1 if there is no OCSP response data. */
  4593. if(ocsp_len < 0)
  4594. ocsp_len = 0; /* no data available */
  4595. result = Curl_vtls_apple_verify(cf, data, peer, chain.num_certs,
  4596. ossl_chain_get_der, &chain,
  4597. ocsp_data, ocsp_len);
  4598. }
  4599. *pverified = !result;
  4600. return result;
  4601. }
  4602. #endif /* USE_APPLE_SECTRUST */
  4603. CURLcode Curl_ossl_check_peer_cert(struct Curl_cfilter *cf,
  4604. struct Curl_easy *data,
  4605. struct ossl_ctx *octx,
  4606. struct ssl_peer *peer)
  4607. {
  4608. struct connectdata *conn = cf->conn;
  4609. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  4610. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  4611. CURLcode result = CURLE_OK;
  4612. long ossl_verify;
  4613. bool strict = (conn_config->verifypeer || conn_config->verifyhost);
  4614. X509 *server_cert;
  4615. bool verified = FALSE;
  4616. #ifdef USE_APPLE_SECTRUST
  4617. bool sectrust_verified = FALSE;
  4618. #endif
  4619. if(data->set.ssl.certinfo && !octx->reused_session) {
  4620. /* asked to gather certificate info. Reused sessions don't have cert
  4621. chains */
  4622. result = ossl_certchain(data, octx->ssl);
  4623. if(result)
  4624. return result;
  4625. }
  4626. server_cert = SSL_get1_peer_certificate(octx->ssl);
  4627. if(!server_cert) {
  4628. if(!strict)
  4629. goto out;
  4630. failf(data, "SSL: could not get peer certificate");
  4631. result = CURLE_PEER_FAILED_VERIFICATION;
  4632. goto out;
  4633. }
  4634. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  4635. result = ossl_infof_cert(cf, data, server_cert);
  4636. if(result)
  4637. goto out;
  4638. infof_certstack(data, octx->ssl);
  4639. #endif
  4640. if(conn_config->verifyhost) {
  4641. result = ossl_verifyhost(data, conn, peer, server_cert);
  4642. if(result)
  4643. goto out;
  4644. }
  4645. ossl_verify = SSL_get_verify_result(octx->ssl);
  4646. ssl_config->certverifyresult = ossl_verify;
  4647. verified = (ossl_verify == X509_V_OK);
  4648. if(verified)
  4649. infof(data, "SSL certificate verified via OpenSSL.");
  4650. #ifdef USE_APPLE_SECTRUST
  4651. if(!verified &&
  4652. conn_config->verifypeer && ssl_config->native_ca_store &&
  4653. (ossl_verify == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)) {
  4654. /* we verify using Apple SecTrust *unless* OpenSSL already verified.
  4655. * This may happen if the application intercepted the OpenSSL callback
  4656. * and installed its own. */
  4657. result = ossl_apple_verify(cf, data, octx, peer, &verified);
  4658. if(result && (result != CURLE_PEER_FAILED_VERIFICATION))
  4659. goto out; /* unexpected error */
  4660. if(verified) {
  4661. infof(data, "SSL certificate verified via Apple SecTrust.");
  4662. ssl_config->certverifyresult = X509_V_OK;
  4663. sectrust_verified = TRUE;
  4664. }
  4665. }
  4666. #endif
  4667. if(!verified) {
  4668. /* no trust established, report the OpenSSL status */
  4669. failf(data, "SSL certificate OpenSSL verify result: %s (%ld)",
  4670. X509_verify_cert_error_string(ossl_verify), ossl_verify);
  4671. result = CURLE_PEER_FAILED_VERIFICATION;
  4672. if(conn_config->verifypeer)
  4673. goto out;
  4674. infof(data, " SSL certificate verification failed, continuing anyway!");
  4675. }
  4676. #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_OCSP)
  4677. if(conn_config->verifystatus &&
  4678. #ifdef USE_APPLE_SECTRUST
  4679. !sectrust_verified && /* already verified via apple sectrust, cannot
  4680. * verifystate via OpenSSL in that case as it
  4681. * does not have the trust anchors */
  4682. #endif
  4683. !octx->reused_session) {
  4684. /* do not do this after Session ID reuse */
  4685. result = verifystatus(cf, data, octx);
  4686. if(result)
  4687. goto out;
  4688. }
  4689. #endif
  4690. result = ossl_check_issuer(cf, data, server_cert);
  4691. if(result)
  4692. goto out;
  4693. result = ossl_check_pinned_key(cf, data, server_cert);
  4694. out:
  4695. X509_free(server_cert);
  4696. return result;
  4697. }
  4698. static CURLcode ossl_connect_step3(struct Curl_cfilter *cf,
  4699. struct Curl_easy *data)
  4700. {
  4701. CURLcode result = CURLE_OK;
  4702. struct ssl_connect_data *connssl = cf->ctx;
  4703. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4704. DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
  4705. /*
  4706. * We check certificates to authenticate the server; otherwise we risk
  4707. * man-in-the-middle attack; NEVERTHELESS, if we are told explicitly not to
  4708. * verify the peer, ignore faults and failures from the server cert
  4709. * operations.
  4710. */
  4711. result = Curl_ossl_check_peer_cert(cf, data, octx, &connssl->peer);
  4712. if(result)
  4713. /* on error, remove sessions we might have in the pool */
  4714. Curl_ssl_scache_remove_all(cf, data, connssl->peer.scache_key);
  4715. return result;
  4716. }
  4717. #ifdef HAVE_OPENSSL_EARLYDATA
  4718. static CURLcode ossl_send_earlydata(struct Curl_cfilter *cf,
  4719. struct Curl_easy *data)
  4720. {
  4721. struct ssl_connect_data *connssl = cf->ctx;
  4722. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4723. CURLcode result = CURLE_OK;
  4724. const unsigned char *buf;
  4725. size_t blen, nwritten;
  4726. int rc;
  4727. DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sending);
  4728. octx->io_result = CURLE_OK;
  4729. while(Curl_bufq_peek(&connssl->earlydata, &buf, &blen)) {
  4730. nwritten = 0;
  4731. rc = SSL_write_early_data(octx->ssl, buf, blen, &nwritten);
  4732. CURL_TRC_CF(data, cf, "SSL_write_early_data(len=%zu) -> %d, %zu",
  4733. blen, rc, nwritten);
  4734. if(rc <= 0) {
  4735. long sslerror;
  4736. char error_buffer[256];
  4737. int err = SSL_get_error(octx->ssl, rc);
  4738. switch(err) {
  4739. case SSL_ERROR_WANT_READ:
  4740. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  4741. result = CURLE_AGAIN;
  4742. goto out;
  4743. case SSL_ERROR_WANT_WRITE:
  4744. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  4745. result = CURLE_AGAIN;
  4746. goto out;
  4747. case SSL_ERROR_SYSCALL: {
  4748. int sockerr = SOCKERRNO;
  4749. if(octx->io_result == CURLE_AGAIN) {
  4750. result = CURLE_AGAIN;
  4751. goto out;
  4752. }
  4753. sslerror = ERR_get_error();
  4754. if(sslerror)
  4755. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
  4756. else if(sockerr)
  4757. curlx_strerror(sockerr, error_buffer, sizeof(error_buffer));
  4758. else
  4759. curl_msnprintf(error_buffer, sizeof(error_buffer), "%s",
  4760. SSL_ERROR_to_str(err));
  4761. failf(data, OSSL_PACKAGE " SSL_write:early_data: %s, errno %d",
  4762. error_buffer, sockerr);
  4763. result = CURLE_SEND_ERROR;
  4764. goto out;
  4765. }
  4766. case SSL_ERROR_SSL: {
  4767. /* A failure in the SSL library occurred, usually a protocol error.
  4768. The OpenSSL error queue contains more information on the error. */
  4769. sslerror = ERR_get_error();
  4770. failf(data, "SSL_write_early_data() error: %s",
  4771. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
  4772. result = CURLE_SEND_ERROR;
  4773. goto out;
  4774. }
  4775. default:
  4776. /* a true error */
  4777. failf(data, OSSL_PACKAGE " SSL_write_early_data: %s, errno %d",
  4778. SSL_ERROR_to_str(err), SOCKERRNO);
  4779. result = CURLE_SEND_ERROR;
  4780. goto out;
  4781. }
  4782. }
  4783. Curl_bufq_skip(&connssl->earlydata, nwritten);
  4784. }
  4785. /* sent everything there was */
  4786. infof(data, "SSL sending %zu bytes of early data", connssl->earlydata_skip);
  4787. out:
  4788. return result;
  4789. }
  4790. #endif /* HAVE_OPENSSL_EARLYDATA */
  4791. static CURLcode ossl_connect(struct Curl_cfilter *cf,
  4792. struct Curl_easy *data,
  4793. bool *done)
  4794. {
  4795. CURLcode result = CURLE_OK;
  4796. struct ssl_connect_data *connssl = cf->ctx;
  4797. /* check if the connection has already been established */
  4798. if(ssl_connection_complete == connssl->state) {
  4799. *done = TRUE;
  4800. return CURLE_OK;
  4801. }
  4802. *done = FALSE;
  4803. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  4804. if(ssl_connect_1 == connssl->connecting_state) {
  4805. CURL_TRC_CF(data, cf, "ossl_connect, step1");
  4806. result = ossl_connect_step1(cf, data);
  4807. if(result)
  4808. goto out;
  4809. }
  4810. if(ssl_connect_2 == connssl->connecting_state) {
  4811. CURL_TRC_CF(data, cf, "ossl_connect, step2");
  4812. #ifdef HAVE_OPENSSL_EARLYDATA
  4813. if(connssl->earlydata_state == ssl_earlydata_await) {
  4814. goto out;
  4815. }
  4816. else if(connssl->earlydata_state == ssl_earlydata_sending) {
  4817. result = ossl_send_earlydata(cf, data);
  4818. if(result)
  4819. goto out;
  4820. connssl->earlydata_state = ssl_earlydata_sent;
  4821. }
  4822. #endif
  4823. DEBUGASSERT((connssl->earlydata_state == ssl_earlydata_none) ||
  4824. (connssl->earlydata_state == ssl_earlydata_sent));
  4825. result = ossl_connect_step2(cf, data);
  4826. if(result)
  4827. goto out;
  4828. }
  4829. if(ssl_connect_3 == connssl->connecting_state) {
  4830. CURL_TRC_CF(data, cf, "ossl_connect, step3");
  4831. result = ossl_connect_step3(cf, data);
  4832. if(result)
  4833. goto out;
  4834. connssl->connecting_state = ssl_connect_done;
  4835. #ifdef HAVE_OPENSSL_EARLYDATA
  4836. if(connssl->earlydata_state > ssl_earlydata_none) {
  4837. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4838. /* We should be in this state by now */
  4839. DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sent);
  4840. connssl->earlydata_state =
  4841. (SSL_get_early_data_status(octx->ssl) == SSL_EARLY_DATA_ACCEPTED) ?
  4842. ssl_earlydata_accepted : ssl_earlydata_rejected;
  4843. }
  4844. #endif
  4845. }
  4846. if(ssl_connect_done == connssl->connecting_state) {
  4847. CURL_TRC_CF(data, cf, "ossl_connect, done");
  4848. connssl->state = ssl_connection_complete;
  4849. }
  4850. out:
  4851. if(result == CURLE_AGAIN) {
  4852. *done = FALSE;
  4853. return CURLE_OK;
  4854. }
  4855. *done = ((connssl->state == ssl_connection_complete) ||
  4856. (connssl->state == ssl_connection_deferred));
  4857. return result;
  4858. }
  4859. static bool ossl_data_pending(struct Curl_cfilter *cf,
  4860. const struct Curl_easy *data)
  4861. {
  4862. struct ssl_connect_data *connssl = cf->ctx;
  4863. (void)data;
  4864. return connssl->input_pending;
  4865. }
  4866. static CURLcode ossl_send(struct Curl_cfilter *cf,
  4867. struct Curl_easy *data,
  4868. const void *mem,
  4869. size_t len,
  4870. size_t *pnwritten)
  4871. {
  4872. /* SSL_write() is said to return 'int' while write() and send() returns
  4873. 'size_t' */
  4874. int err;
  4875. char error_buffer[256];
  4876. sslerr_t sslerror;
  4877. int memlen;
  4878. struct ssl_connect_data *connssl = cf->ctx;
  4879. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4880. CURLcode result = CURLE_OK;
  4881. int nwritten;
  4882. (void)data;
  4883. DEBUGASSERT(octx);
  4884. *pnwritten = 0;
  4885. ERR_clear_error();
  4886. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  4887. memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
  4888. if(octx->blocked_ssl_write_len && (octx->blocked_ssl_write_len != memlen)) {
  4889. /* The previous SSL_write() call was blocked, using that length.
  4890. * We need to use that again or OpenSSL will freak out. A shorter
  4891. * length should not happen and is a bug in libcurl. */
  4892. if(octx->blocked_ssl_write_len > memlen) {
  4893. DEBUGASSERT(0);
  4894. return CURLE_BAD_FUNCTION_ARGUMENT;
  4895. }
  4896. memlen = octx->blocked_ssl_write_len;
  4897. }
  4898. octx->blocked_ssl_write_len = 0;
  4899. nwritten = SSL_write(octx->ssl, mem, memlen);
  4900. if(nwritten > 0)
  4901. *pnwritten = (size_t)nwritten;
  4902. else {
  4903. err = SSL_get_error(octx->ssl, nwritten);
  4904. switch(err) {
  4905. case SSL_ERROR_WANT_READ:
  4906. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  4907. octx->blocked_ssl_write_len = memlen;
  4908. result = CURLE_AGAIN;
  4909. goto out;
  4910. case SSL_ERROR_WANT_WRITE:
  4911. result = CURLE_AGAIN;
  4912. octx->blocked_ssl_write_len = memlen;
  4913. goto out;
  4914. case SSL_ERROR_SYSCALL:
  4915. {
  4916. int sockerr = SOCKERRNO;
  4917. if(octx->io_result == CURLE_AGAIN) {
  4918. octx->blocked_ssl_write_len = memlen;
  4919. result = CURLE_AGAIN;
  4920. goto out;
  4921. }
  4922. sslerror = ERR_get_error();
  4923. if(sslerror)
  4924. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
  4925. else if(sockerr)
  4926. curlx_strerror(sockerr, error_buffer, sizeof(error_buffer));
  4927. else
  4928. curl_msnprintf(error_buffer, sizeof(error_buffer), "%s",
  4929. SSL_ERROR_to_str(err));
  4930. failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d",
  4931. error_buffer, sockerr);
  4932. result = CURLE_SEND_ERROR;
  4933. goto out;
  4934. }
  4935. case SSL_ERROR_SSL: {
  4936. /* A failure in the SSL library occurred, usually a protocol error.
  4937. The OpenSSL error queue contains more information on the error. */
  4938. sslerror = ERR_get_error();
  4939. failf(data, "SSL_write() error: %s",
  4940. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
  4941. result = CURLE_SEND_ERROR;
  4942. goto out;
  4943. }
  4944. default:
  4945. /* a true error */
  4946. failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d",
  4947. SSL_ERROR_to_str(err), SOCKERRNO);
  4948. result = CURLE_SEND_ERROR;
  4949. goto out;
  4950. }
  4951. }
  4952. out:
  4953. return result;
  4954. }
  4955. static CURLcode ossl_recv(struct Curl_cfilter *cf,
  4956. struct Curl_easy *data, /* transfer */
  4957. char *buf, /* store read data here */
  4958. size_t buffersize, /* max amount to read */
  4959. size_t *pnread)
  4960. {
  4961. char error_buffer[256];
  4962. unsigned long sslerror;
  4963. int buffsize;
  4964. struct connectdata *conn = cf->conn;
  4965. struct ssl_connect_data *connssl = cf->ctx;
  4966. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4967. CURLcode result = CURLE_OK;
  4968. int nread;
  4969. (void)data;
  4970. DEBUGASSERT(octx);
  4971. *pnread = 0;
  4972. ERR_clear_error();
  4973. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  4974. buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
  4975. nread = SSL_read(octx->ssl, buf, buffsize);
  4976. if(nread > 0)
  4977. *pnread = (size_t)nread;
  4978. else {
  4979. /* failed SSL_read */
  4980. int err = SSL_get_error(octx->ssl, (int)nread);
  4981. switch(err) {
  4982. case SSL_ERROR_NONE: /* this is not an error */
  4983. break;
  4984. case SSL_ERROR_ZERO_RETURN: /* no more data */
  4985. /* close_notify alert */
  4986. if(cf->sockindex == FIRSTSOCKET)
  4987. /* mark the connection for close if it is indeed the control
  4988. connection */
  4989. connclose(conn, "TLS close_notify");
  4990. break;
  4991. case SSL_ERROR_WANT_READ:
  4992. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  4993. result = CURLE_AGAIN;
  4994. goto out;
  4995. case SSL_ERROR_WANT_WRITE:
  4996. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  4997. result = CURLE_AGAIN;
  4998. goto out;
  4999. default:
  5000. /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
  5001. value/errno" */
  5002. /* https://docs.openssl.org/master/man3/ERR_get_error/ */
  5003. if(octx->io_result == CURLE_AGAIN) {
  5004. result = CURLE_AGAIN;
  5005. goto out;
  5006. }
  5007. sslerror = ERR_get_error();
  5008. if((nread < 0) || sslerror) {
  5009. /* If the return code was negative or there actually is an error in the
  5010. queue */
  5011. int sockerr = SOCKERRNO;
  5012. if(sslerror)
  5013. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
  5014. else if(sockerr && err == SSL_ERROR_SYSCALL)
  5015. curlx_strerror(sockerr, error_buffer, sizeof(error_buffer));
  5016. else
  5017. curl_msnprintf(error_buffer, sizeof(error_buffer), "%s",
  5018. SSL_ERROR_to_str(err));
  5019. failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d",
  5020. error_buffer, sockerr);
  5021. result = CURLE_RECV_ERROR;
  5022. goto out;
  5023. }
  5024. else if(err == SSL_ERROR_SYSCALL) {
  5025. if(octx->io_result) {
  5026. /* logging handling in underlying filter already */
  5027. result = octx->io_result;
  5028. }
  5029. else if(connssl->peer_closed) {
  5030. failf(data, "Connection closed abruptly");
  5031. result = CURLE_RECV_ERROR;
  5032. }
  5033. else {
  5034. /* We should no longer get here nowadays. But handle
  5035. * the error in case of some weirdness in the OSSL stack */
  5036. int sockerr = SOCKERRNO;
  5037. if(sockerr)
  5038. curlx_strerror(sockerr, error_buffer, sizeof(error_buffer));
  5039. else {
  5040. curl_msnprintf(error_buffer, sizeof(error_buffer),
  5041. "Connection closed abruptly");
  5042. }
  5043. failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d",
  5044. error_buffer, sockerr);
  5045. result = CURLE_RECV_ERROR;
  5046. }
  5047. goto out;
  5048. }
  5049. }
  5050. }
  5051. out:
  5052. if((!result && !*pnread) || (result == CURLE_AGAIN)) {
  5053. /* This happens when:
  5054. * - we read an EOF
  5055. * - OpenSSLs buffers are empty, there is no more data
  5056. * - OpenSSL read is blocked on writing something first
  5057. * - an incomplete TLS packet is buffered that cannot be read
  5058. * until more data arrives */
  5059. connssl->input_pending = FALSE;
  5060. }
  5061. CURL_TRC_CF(data, cf, "ossl_recv(len=%zu) -> %d, %zu (in_pending=%d)",
  5062. buffersize, result, *pnread, connssl->input_pending);
  5063. return result;
  5064. }
  5065. static CURLcode ossl_get_channel_binding(struct Curl_easy *data, int sockindex,
  5066. struct dynbuf *binding)
  5067. {
  5068. /* required for X509_get_signature_nid support */
  5069. #ifdef HAVE_SSL_X509_GET_SIGNATURE_NID
  5070. X509 *cert;
  5071. int algo_nid;
  5072. const EVP_MD *algo_type;
  5073. const char *algo_name;
  5074. unsigned int length;
  5075. unsigned char buf[EVP_MAX_MD_SIZE];
  5076. const char prefix[] = "tls-server-end-point:";
  5077. struct connectdata *conn = data->conn;
  5078. struct Curl_cfilter *cf = conn->cfilter[sockindex];
  5079. struct ossl_ctx *octx = NULL;
  5080. CURLcode result = CURLE_OK;
  5081. do {
  5082. const struct Curl_cftype *cft = cf->cft;
  5083. struct ssl_connect_data *connssl = cf->ctx;
  5084. if(cft->name && !strcmp(cft->name, "SSL")) {
  5085. octx = (struct ossl_ctx *)connssl->backend;
  5086. break;
  5087. }
  5088. cf = cf->next;
  5089. } while(cf);
  5090. if(!octx) {
  5091. failf(data, "Failed to find the SSL filter");
  5092. return CURLE_BAD_FUNCTION_ARGUMENT;
  5093. }
  5094. cert = SSL_get1_peer_certificate(octx->ssl);
  5095. if(!cert)
  5096. /* No server certificate, don't do channel binding */
  5097. return CURLE_OK;
  5098. if(!OBJ_find_sigid_algs(X509_get_signature_nid(cert), &algo_nid, NULL)) {
  5099. failf(data,
  5100. "Unable to find digest NID for certificate signature algorithm");
  5101. result = CURLE_SSL_INVALIDCERTSTATUS;
  5102. goto error;
  5103. }
  5104. /* https://datatracker.ietf.org/doc/html/rfc5929#section-4.1 */
  5105. if(algo_nid == NID_md5 || algo_nid == NID_sha1) {
  5106. algo_type = EVP_sha256();
  5107. }
  5108. else {
  5109. algo_type = EVP_get_digestbynid(algo_nid);
  5110. if(!algo_type) {
  5111. algo_name = OBJ_nid2sn(algo_nid);
  5112. failf(data, "Could not find digest algorithm %s (NID %d)",
  5113. algo_name ? algo_name : "(null)", algo_nid);
  5114. result = CURLE_SSL_INVALIDCERTSTATUS;
  5115. goto error;
  5116. }
  5117. }
  5118. if(!X509_digest(cert, algo_type, buf, &length)) {
  5119. failf(data, "X509_digest() failed");
  5120. result = CURLE_SSL_INVALIDCERTSTATUS;
  5121. goto error;
  5122. }
  5123. /* Append "tls-server-end-point:" */
  5124. result = curlx_dyn_addn(binding, prefix, sizeof(prefix) - 1);
  5125. if(result)
  5126. goto error;
  5127. /* Append digest */
  5128. result = curlx_dyn_addn(binding, buf, length);
  5129. error:
  5130. X509_free(cert);
  5131. return result;
  5132. #else
  5133. /* No X509_get_signature_nid support */
  5134. (void)data;
  5135. (void)sockindex;
  5136. (void)binding;
  5137. return CURLE_OK;
  5138. #endif
  5139. }
  5140. size_t Curl_ossl_version(char *buffer, size_t size)
  5141. {
  5142. #ifdef LIBRESSL_VERSION_NUMBER
  5143. char *p;
  5144. size_t count;
  5145. const char *ver = OpenSSL_version(OPENSSL_VERSION);
  5146. const char expected[] = OSSL_PACKAGE " "; /* ie "LibreSSL " */
  5147. if(curl_strnequal(ver, expected, sizeof(expected) - 1)) {
  5148. ver += sizeof(expected) - 1;
  5149. }
  5150. count = curl_msnprintf(buffer, size, "%s/%s", OSSL_PACKAGE, ver);
  5151. for(p = buffer; *p; ++p) {
  5152. if(ISBLANK(*p))
  5153. *p = '_';
  5154. }
  5155. return count;
  5156. #elif defined(OPENSSL_IS_BORINGSSL)
  5157. #ifdef CURL_BORINGSSL_VERSION
  5158. return curl_msnprintf(buffer, size, "%s/%s",
  5159. OSSL_PACKAGE, CURL_BORINGSSL_VERSION);
  5160. #else
  5161. return curl_msnprintf(buffer, size, OSSL_PACKAGE);
  5162. #endif
  5163. #elif defined(OPENSSL_IS_AWSLC)
  5164. return curl_msnprintf(buffer, size, "%s/%s",
  5165. OSSL_PACKAGE, AWSLC_VERSION_NUMBER_STRING);
  5166. #elif defined(OPENSSL_VERSION_STRING) /* OpenSSL 3+ */
  5167. return curl_msnprintf(buffer, size, "%s/%s",
  5168. OSSL_PACKAGE, OpenSSL_version(OPENSSL_VERSION_STRING));
  5169. #else
  5170. /* not LibreSSL, BoringSSL and not using OpenSSL_version */
  5171. char sub[3];
  5172. unsigned long ssleay_value;
  5173. sub[2]='\0';
  5174. sub[1]='\0';
  5175. ssleay_value = OpenSSL_version_num();
  5176. if(ssleay_value&0xff0) {
  5177. int minor_ver = (ssleay_value >> 4) & 0xff;
  5178. if(minor_ver > 26) {
  5179. /* handle extended version introduced for 0.9.8za */
  5180. sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1);
  5181. sub[0] = 'z';
  5182. }
  5183. else {
  5184. sub[0] = (char) (minor_ver + 'a' - 1);
  5185. }
  5186. }
  5187. else
  5188. sub[0]='\0';
  5189. return curl_msnprintf(buffer, size, "%s/%lx.%lx.%lx%s"
  5190. #ifdef OPENSSL_FIPS
  5191. "-fips"
  5192. #endif
  5193. ,
  5194. OSSL_PACKAGE,
  5195. (ssleay_value >> 28) & 0xf,
  5196. (ssleay_value >> 20) & 0xff,
  5197. (ssleay_value >> 12) & 0xff,
  5198. sub);
  5199. #endif
  5200. }
  5201. /* can be called with data == NULL */
  5202. static CURLcode ossl_random(struct Curl_easy *data,
  5203. unsigned char *entropy, size_t length)
  5204. {
  5205. int rc;
  5206. if(data) {
  5207. if(ossl_seed(data)) /* Initiate the seed if not already done */
  5208. return CURLE_FAILED_INIT; /* could not seed for some reason */
  5209. }
  5210. else {
  5211. if(!rand_enough())
  5212. return CURLE_FAILED_INIT;
  5213. }
  5214. /* RAND_bytes() returns 1 on success, 0 otherwise. */
  5215. rc = RAND_bytes(entropy, (ossl_valsize_t)curlx_uztosi(length));
  5216. return rc == 1 ? CURLE_OK : CURLE_FAILED_INIT;
  5217. }
  5218. #ifndef OPENSSL_NO_SHA256
  5219. static CURLcode ossl_sha256sum(const unsigned char *tmp, /* input */
  5220. size_t tmplen,
  5221. unsigned char *sha256sum /* output */,
  5222. size_t unused)
  5223. {
  5224. EVP_MD_CTX *mdctx;
  5225. unsigned int len = 0;
  5226. (void)unused;
  5227. mdctx = EVP_MD_CTX_create();
  5228. if(!mdctx)
  5229. return CURLE_OUT_OF_MEMORY;
  5230. if(!EVP_DigestInit(mdctx, EVP_sha256())) {
  5231. EVP_MD_CTX_destroy(mdctx);
  5232. return CURLE_FAILED_INIT;
  5233. }
  5234. EVP_DigestUpdate(mdctx, tmp, tmplen);
  5235. EVP_DigestFinal_ex(mdctx, sha256sum, &len);
  5236. EVP_MD_CTX_destroy(mdctx);
  5237. return CURLE_OK;
  5238. }
  5239. #endif
  5240. static bool ossl_cert_status_request(void)
  5241. {
  5242. #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_OCSP)
  5243. return TRUE;
  5244. #else
  5245. return FALSE;
  5246. #endif
  5247. }
  5248. static void *ossl_get_internals(struct ssl_connect_data *connssl,
  5249. CURLINFO info)
  5250. {
  5251. /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */
  5252. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  5253. DEBUGASSERT(octx);
  5254. return info == CURLINFO_TLS_SESSION ?
  5255. (void *)octx->ssl_ctx : (void *)octx->ssl;
  5256. }
  5257. const struct Curl_ssl Curl_ssl_openssl = {
  5258. { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */
  5259. SSLSUPP_CA_PATH |
  5260. SSLSUPP_CAINFO_BLOB |
  5261. SSLSUPP_CERTINFO |
  5262. SSLSUPP_PINNEDPUBKEY |
  5263. SSLSUPP_SSL_CTX |
  5264. #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
  5265. SSLSUPP_TLS13_CIPHERSUITES |
  5266. #endif
  5267. #ifdef HAVE_SSL_CTX_SET1_SIGALGS
  5268. SSLSUPP_SIGNATURE_ALGORITHMS |
  5269. #endif
  5270. #ifdef USE_ECH_OPENSSL
  5271. SSLSUPP_ECH |
  5272. #endif
  5273. SSLSUPP_CA_CACHE |
  5274. SSLSUPP_HTTPS_PROXY |
  5275. SSLSUPP_CIPHER_LIST,
  5276. sizeof(struct ossl_ctx),
  5277. ossl_init, /* init */
  5278. ossl_cleanup, /* cleanup */
  5279. Curl_ossl_version, /* version */
  5280. ossl_shutdown, /* shutdown */
  5281. ossl_data_pending, /* data_pending */
  5282. ossl_random, /* random */
  5283. ossl_cert_status_request, /* cert_status_request */
  5284. ossl_connect, /* connect */
  5285. Curl_ssl_adjust_pollset, /* adjust_pollset */
  5286. ossl_get_internals, /* get_internals */
  5287. ossl_close, /* close_one */
  5288. ossl_close_all, /* close_all */
  5289. ossl_set_engine, /* set_engine or provider */
  5290. ossl_set_engine_default, /* set_engine_default */
  5291. ossl_engines_list, /* engines_list */
  5292. #ifndef OPENSSL_NO_SHA256
  5293. ossl_sha256sum, /* sha256sum */
  5294. #else
  5295. NULL, /* sha256sum */
  5296. #endif
  5297. ossl_recv, /* recv decrypted data */
  5298. ossl_send, /* send data to encrypt */
  5299. ossl_get_channel_binding /* get_channel_binding */
  5300. };
  5301. #endif /* USE_OPENSSL */