openssl.c 146 KB

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