openssl.c 133 KB

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