openssl.c 142 KB

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