openssl.c 139 KB

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