2
0

openssl.c 159 KB

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