openssl.c 133 KB

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