2
0

openssl.c 159 KB

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