openssl.c 122 KB

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