openssl.c 144 KB

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