openssl.c 147 KB

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