2
0

openssl.c 119 KB

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