openssl.c 134 KB

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