openssl.c 157 KB

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