openssl.c 143 KB

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