openssl.c 137 KB

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