openssl.c 142 KB

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