openssl.c 164 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <[email protected]>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * 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. /* Wincrypt must be included before anything that could include OpenSSL. */
  31. #ifdef USE_WIN32_CRYPTO
  32. #include <wincrypt.h>
  33. /* Undefine wincrypt conflicting symbols for BoringSSL. */
  34. #undef X509_NAME
  35. #undef X509_EXTENSIONS
  36. #undef PKCS7_ISSUER_AND_SERIAL
  37. #undef PKCS7_SIGNER_INFO
  38. #undef OCSP_REQUEST
  39. #undef OCSP_RESPONSE
  40. #endif
  41. #include "../urldata.h"
  42. #include "../curl_trc.h"
  43. #include "../formdata.h" /* for the boundary function */
  44. #include "../url.h" /* for the ssl config check function */
  45. #include "../curlx/inet_pton.h"
  46. #include "openssl.h"
  47. #include "../connect.h"
  48. #include "../progress.h"
  49. #include "vtls.h"
  50. #include "vtls_int.h"
  51. #include "vtls_scache.h"
  52. #include "../vauth/vauth.h"
  53. #include "keylog.h"
  54. #include "hostcheck.h"
  55. #include "../transfer.h"
  56. #include "../multiif.h"
  57. #include "../curlx/strerr.h"
  58. #include "../curlx/strparse.h"
  59. #include "../curlx/strcopy.h"
  60. #include "../strdup.h"
  61. #include "apple.h"
  62. #include <openssl/rand.h>
  63. #include <openssl/x509v3.h>
  64. #ifndef OPENSSL_NO_DSA
  65. #include <openssl/dsa.h>
  66. #endif
  67. #include <openssl/dh.h>
  68. #include <openssl/err.h>
  69. #include <openssl/conf.h>
  70. #include <openssl/bn.h>
  71. #include <openssl/rsa.h>
  72. #include <openssl/bio.h>
  73. #include <openssl/pkcs12.h>
  74. #include <openssl/tls1.h>
  75. #include <openssl/evp.h>
  76. #if defined(HAVE_SSL_SET1_ECH_CONFIG_LIST) && !defined(HAVE_BORINGSSL_LIKE)
  77. #include <openssl/ech.h>
  78. #endif
  79. #ifndef OPENSSL_NO_OCSP
  80. #include <openssl/ocsp.h>
  81. #endif
  82. #if !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_UI_CONSOLE)
  83. #define USE_OPENSSL_ENGINE
  84. #include <openssl/engine.h>
  85. #endif
  86. #ifdef LIBRESSL_VERSION_NUMBER
  87. /* As of LibreSSL 2.0.0-4.0.0: OPENSSL_VERSION_NUMBER == 0x20000000L */
  88. # if LIBRESSL_VERSION_NUMBER < 0x2090100fL /* 2019-04-13 */
  89. # error "LibreSSL 2.9.1 or later required"
  90. # endif
  91. #elif !defined(HAVE_BORINGSSL_LIKE)
  92. # ifndef HAVE_OPENSSL3 /* 2021-09-07 */
  93. # error "OpenSSL 3.0.0 or later required"
  94. # endif
  95. #endif
  96. #if defined(HAVE_OPENSSL3) && !defined(OPENSSL_NO_UI_CONSOLE)
  97. #include <openssl/provider.h>
  98. #include <openssl/store.h>
  99. /* this is used in the following conditions to make them easier to read */
  100. #define OPENSSL_HAS_PROVIDERS
  101. static void ossl_provider_cleanup(struct Curl_easy *data);
  102. #endif
  103. /* AWS-LC fixed a bug with large buffers in v1.61.0 which also introduced
  104. * X509_V_ERR_EC_KEY_EXPLICIT_PARAMS. */
  105. #if !defined(LIBRESSL_VERSION_NUMBER) && !defined(OPENSSL_IS_BORINGSSL) && \
  106. (!defined(OPENSSL_IS_AWSLC) || defined(X509_V_ERR_EC_KEY_EXPLICIT_PARAMS))
  107. #define HAVE_SSL_CTX_SET_DEFAULT_READ_BUFFER_LEN 1
  108. #endif
  109. #if defined(USE_OPENSSL_ENGINE) || defined(OPENSSL_HAS_PROVIDERS)
  110. #include <openssl/ui.h>
  111. #endif
  112. #ifdef HAVE_OPENSSL3
  113. #define HAVE_EVP_PKEY_GET_PARAMS 1
  114. #endif
  115. #ifdef HAVE_EVP_PKEY_GET_PARAMS
  116. #include <openssl/core_names.h>
  117. #define DECLARE_PKEY_PARAM_BIGNUM(name) BIGNUM *name = NULL
  118. #define FREE_PKEY_PARAM_BIGNUM(name) BN_clear_free(name)
  119. #else
  120. #define DECLARE_PKEY_PARAM_BIGNUM(name) const BIGNUM *name
  121. #define FREE_PKEY_PARAM_BIGNUM(name)
  122. #endif
  123. /* Whether SSL_CTX_set_ciphersuites is available.
  124. * OpenSSL: supported since 1.1.1 (commit a53b5be6a05)
  125. * BoringSSL: no
  126. * LibreSSL: supported since 3.4.1 (released 2021-10-14)
  127. */
  128. #if (!defined(LIBRESSL_VERSION_NUMBER) || \
  129. (defined(LIBRESSL_VERSION_NUMBER) && \
  130. LIBRESSL_VERSION_NUMBER >= 0x3040100fL)) && \
  131. !defined(OPENSSL_IS_BORINGSSL)
  132. # define HAVE_SSL_CTX_SET_CIPHERSUITES
  133. # ifndef OPENSSL_IS_AWSLC
  134. # define HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH
  135. # endif
  136. #endif
  137. /* Whether SSL_CTX_set1_sigalgs_list is available
  138. * OpenSSL: supported since 1.0.2 (commit 0b362de5f575)
  139. * BoringSSL: supported since 0.20240913.0 (commit 826ce15)
  140. * LibreSSL: no
  141. */
  142. #ifndef LIBRESSL_VERSION_NUMBER
  143. #define HAVE_SSL_CTX_SET1_SIGALGS
  144. #endif
  145. #ifdef LIBRESSL_VERSION_NUMBER
  146. #define OSSL_PACKAGE "LibreSSL"
  147. #elif defined(OPENSSL_IS_BORINGSSL)
  148. #define OSSL_PACKAGE "BoringSSL"
  149. #elif defined(OPENSSL_IS_AWSLC)
  150. #define OSSL_PACKAGE "AWS-LC"
  151. #elif defined(USE_NGTCP2) && defined(USE_NGHTTP3) && \
  152. !defined(OPENSSL_QUIC_API2)
  153. #define OSSL_PACKAGE "quictls"
  154. #else
  155. #define OSSL_PACKAGE "OpenSSL"
  156. #endif
  157. #ifdef HAVE_BORINGSSL_LIKE
  158. typedef size_t numcert_t;
  159. typedef uint32_t sslerr_t;
  160. #else
  161. typedef int numcert_t;
  162. typedef unsigned long sslerr_t;
  163. #endif
  164. #define ossl_valsize_t numcert_t
  165. static CURLcode ossl_certchain(struct Curl_easy *data, SSL *ssl);
  166. static CURLcode push_certinfo(struct Curl_easy *data,
  167. BIO *mem, const char *label, int num)
  168. WARN_UNUSED_RESULT;
  169. static CURLcode push_certinfo(struct Curl_easy *data,
  170. BIO *mem, const char *label, int num)
  171. {
  172. char *ptr;
  173. long len = BIO_get_mem_data(mem, &ptr);
  174. CURLcode result = Curl_ssl_push_certinfo_len(data, num, label, ptr, len);
  175. (void)BIO_reset(mem);
  176. return result;
  177. }
  178. static CURLcode pubkey_show(struct Curl_easy *data,
  179. BIO *mem,
  180. int num,
  181. const char *type,
  182. const char *name,
  183. const BIGNUM *bn) WARN_UNUSED_RESULT;
  184. static CURLcode pubkey_show(struct Curl_easy *data,
  185. BIO *mem,
  186. int num,
  187. const char *type,
  188. const char *name,
  189. const BIGNUM *bn)
  190. {
  191. char namebuf[32];
  192. curl_msnprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
  193. if(bn)
  194. BN_print(mem, bn);
  195. return push_certinfo(data, mem, namebuf, num);
  196. }
  197. #define print_pubkey_BN(_type, _name, _num) \
  198. pubkey_show(data, mem, _num, #_type, #_name, _name)
  199. static int asn1_object_dump(const ASN1_OBJECT *a, char *buf, size_t len)
  200. {
  201. int i = i2t_ASN1_OBJECT(buf, (int)len, a);
  202. return (i >= (int)len); /* buffer too small */
  203. }
  204. static CURLcode X509V3_ext(struct Curl_easy *data,
  205. int certnum,
  206. const STACK_OF(X509_EXTENSION) *extsarg)
  207. {
  208. int i;
  209. CURLcode result = CURLE_OK;
  210. #ifdef LIBRESSL_VERSION_NUMBER
  211. STACK_OF(X509_EXTENSION) *exts = CURL_UNCONST(extsarg);
  212. #else
  213. const STACK_OF(X509_EXTENSION) *exts = extsarg;
  214. #endif
  215. if((int)sk_X509_EXTENSION_num(exts) <= 0)
  216. /* no extensions, bail out */
  217. return result;
  218. for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
  219. ASN1_OBJECT *obj;
  220. X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, (ossl_valsize_t)i);
  221. BUF_MEM *biomem;
  222. char namebuf[128];
  223. BIO *bio_out = BIO_new(BIO_s_mem());
  224. if(!bio_out)
  225. return result;
  226. obj = X509_EXTENSION_get_object(ext);
  227. if(asn1_object_dump(obj, namebuf, sizeof(namebuf)))
  228. /* make sure the name is null-terminated */
  229. namebuf[sizeof(namebuf) - 1] = 0;
  230. if(!X509V3_EXT_print(bio_out, ext, 0, 0))
  231. ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext));
  232. BIO_get_mem_ptr(bio_out, &biomem);
  233. result = Curl_ssl_push_certinfo_len(data, certnum, namebuf, biomem->data,
  234. biomem->length);
  235. BIO_free(bio_out);
  236. if(result)
  237. break;
  238. }
  239. return result;
  240. }
  241. static CURLcode get_pkey_rsa(struct Curl_easy *data,
  242. EVP_PKEY *pubkey, BIO *mem, int i)
  243. {
  244. CURLcode result = CURLE_OK;
  245. #ifndef HAVE_EVP_PKEY_GET_PARAMS
  246. RSA *rsa = EVP_PKEY_get0_RSA(pubkey);
  247. #endif /* !HAVE_EVP_PKEY_GET_PARAMS */
  248. DECLARE_PKEY_PARAM_BIGNUM(n);
  249. DECLARE_PKEY_PARAM_BIGNUM(e);
  250. #ifdef HAVE_EVP_PKEY_GET_PARAMS
  251. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_RSA_N, &n);
  252. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_RSA_E, &e);
  253. #else
  254. RSA_get0_key(rsa, &n, &e, NULL);
  255. #endif /* HAVE_EVP_PKEY_GET_PARAMS */
  256. BIO_printf(mem, "%d", n ? BN_num_bits(n) : 0);
  257. result = push_certinfo(data, mem, "RSA Public Key", i);
  258. if(!result) {
  259. result = print_pubkey_BN(rsa, n, i);
  260. if(!result)
  261. result = print_pubkey_BN(rsa, e, i);
  262. }
  263. FREE_PKEY_PARAM_BIGNUM(n);
  264. FREE_PKEY_PARAM_BIGNUM(e);
  265. return result;
  266. }
  267. #ifndef OPENSSL_NO_DSA
  268. static CURLcode get_pkey_dsa(struct Curl_easy *data,
  269. EVP_PKEY *pubkey, BIO *mem, int i)
  270. {
  271. CURLcode result = CURLE_OK;
  272. #ifndef HAVE_EVP_PKEY_GET_PARAMS
  273. DSA *dsa = EVP_PKEY_get0_DSA(pubkey);
  274. #endif /* !HAVE_EVP_PKEY_GET_PARAMS */
  275. DECLARE_PKEY_PARAM_BIGNUM(p);
  276. DECLARE_PKEY_PARAM_BIGNUM(q);
  277. DECLARE_PKEY_PARAM_BIGNUM(g);
  278. DECLARE_PKEY_PARAM_BIGNUM(pub_key);
  279. #ifdef HAVE_EVP_PKEY_GET_PARAMS
  280. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_P, &p);
  281. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_Q, &q);
  282. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_G, &g);
  283. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_PUB_KEY, &pub_key);
  284. #else
  285. DSA_get0_pqg(dsa, &p, &q, &g);
  286. DSA_get0_key(dsa, &pub_key, NULL);
  287. #endif /* HAVE_EVP_PKEY_GET_PARAMS */
  288. result = print_pubkey_BN(dsa, p, i);
  289. if(!result)
  290. result = print_pubkey_BN(dsa, q, i);
  291. if(!result)
  292. result = print_pubkey_BN(dsa, g, i);
  293. if(!result)
  294. result = print_pubkey_BN(dsa, pub_key, i);
  295. FREE_PKEY_PARAM_BIGNUM(p);
  296. FREE_PKEY_PARAM_BIGNUM(q);
  297. FREE_PKEY_PARAM_BIGNUM(g);
  298. FREE_PKEY_PARAM_BIGNUM(pub_key);
  299. return result;
  300. }
  301. #endif /* !OPENSSL_NO_DSA */
  302. static CURLcode get_pkey_dh(struct Curl_easy *data,
  303. EVP_PKEY *pubkey, BIO *mem, int i)
  304. {
  305. CURLcode result;
  306. #ifndef HAVE_EVP_PKEY_GET_PARAMS
  307. DH *dh = EVP_PKEY_get0_DH(pubkey);
  308. #endif /* !HAVE_EVP_PKEY_GET_PARAMS */
  309. DECLARE_PKEY_PARAM_BIGNUM(p);
  310. DECLARE_PKEY_PARAM_BIGNUM(q);
  311. DECLARE_PKEY_PARAM_BIGNUM(g);
  312. DECLARE_PKEY_PARAM_BIGNUM(pub_key);
  313. #ifdef HAVE_EVP_PKEY_GET_PARAMS
  314. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_P, &p);
  315. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_Q, &q);
  316. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_G, &g);
  317. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_PUB_KEY, &pub_key);
  318. #else
  319. DH_get0_pqg(dh, &p, &q, &g);
  320. DH_get0_key(dh, &pub_key, NULL);
  321. #endif /* HAVE_EVP_PKEY_GET_PARAMS */
  322. result = print_pubkey_BN(dh, p, i);
  323. if(!result)
  324. result = print_pubkey_BN(dh, q, i);
  325. if(!result)
  326. result = print_pubkey_BN(dh, g, i);
  327. if(!result)
  328. result = print_pubkey_BN(dh, pub_key, i);
  329. FREE_PKEY_PARAM_BIGNUM(p);
  330. FREE_PKEY_PARAM_BIGNUM(q);
  331. FREE_PKEY_PARAM_BIGNUM(g);
  332. FREE_PKEY_PARAM_BIGNUM(pub_key);
  333. return result;
  334. }
  335. static CURLcode ossl_certchain(struct Curl_easy *data, SSL *ssl)
  336. {
  337. CURLcode result;
  338. STACK_OF(X509) *sk;
  339. int i;
  340. numcert_t numcerts;
  341. BIO *mem;
  342. DEBUGASSERT(ssl);
  343. sk = SSL_get_peer_cert_chain(ssl);
  344. if(!sk)
  345. return CURLE_SSL_CONNECT_ERROR;
  346. numcerts = sk_X509_num(sk);
  347. if(numcerts > MAX_ALLOWED_CERT_AMOUNT) {
  348. failf(data, "%d certificates is more than allowed (%u)", (int)numcerts,
  349. MAX_ALLOWED_CERT_AMOUNT);
  350. return CURLE_SSL_CONNECT_ERROR;
  351. }
  352. result = Curl_ssl_init_certinfo(data, (int)numcerts);
  353. if(result)
  354. return result;
  355. mem = BIO_new(BIO_s_mem());
  356. if(!mem)
  357. result = CURLE_OUT_OF_MEMORY;
  358. for(i = 0; !result && (i < (int)numcerts); i++) {
  359. ASN1_INTEGER *num;
  360. const unsigned char *numdata;
  361. X509 *x = sk_X509_value(sk, (ossl_valsize_t)i);
  362. EVP_PKEY *pubkey = NULL;
  363. int j;
  364. const ASN1_BIT_STRING *psig = NULL;
  365. X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
  366. result = push_certinfo(data, mem, "Subject", i);
  367. if(result)
  368. break;
  369. X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
  370. result = push_certinfo(data, mem, "Issuer", i);
  371. if(result)
  372. break;
  373. BIO_printf(mem, "%lx", X509_get_version(x));
  374. result = push_certinfo(data, mem, "Version", i);
  375. if(result)
  376. break;
  377. num = X509_get_serialNumber(x);
  378. if(ASN1_STRING_type(num) == V_ASN1_NEG_INTEGER)
  379. BIO_puts(mem, "-");
  380. numdata = ASN1_STRING_get0_data(num);
  381. for(j = 0; j < ASN1_STRING_length(num); j++)
  382. BIO_printf(mem, "%02x", numdata[j]);
  383. result = push_certinfo(data, mem, "Serial Number", i);
  384. if(result)
  385. break;
  386. {
  387. const X509_ALGOR *sigalg = NULL;
  388. X509_PUBKEY *xpubkey = NULL;
  389. ASN1_OBJECT *pubkeyoid = NULL;
  390. X509_get0_signature(&psig, &sigalg, x);
  391. if(sigalg) {
  392. const ASN1_OBJECT *sigalgoid = NULL;
  393. X509_ALGOR_get0(&sigalgoid, NULL, NULL, sigalg);
  394. i2a_ASN1_OBJECT(mem, sigalgoid);
  395. result = push_certinfo(data, mem, "Signature Algorithm", i);
  396. if(result)
  397. break;
  398. }
  399. xpubkey = X509_get_X509_PUBKEY(x);
  400. if(xpubkey) {
  401. X509_PUBKEY_get0_param(&pubkeyoid, NULL, NULL, NULL, xpubkey);
  402. if(pubkeyoid) {
  403. i2a_ASN1_OBJECT(mem, pubkeyoid);
  404. result = push_certinfo(data, mem, "Public Key Algorithm", i);
  405. if(result)
  406. break;
  407. }
  408. }
  409. result = X509V3_ext(data, i, X509_get0_extensions(x));
  410. if(result)
  411. break;
  412. }
  413. ASN1_TIME_print(mem, X509_get0_notBefore(x));
  414. result = push_certinfo(data, mem, "Start date", i);
  415. if(result)
  416. break;
  417. ASN1_TIME_print(mem, X509_get0_notAfter(x));
  418. result = push_certinfo(data, mem, "Expire date", i);
  419. if(result)
  420. break;
  421. pubkey = X509_get_pubkey(x);
  422. if(!pubkey)
  423. infof(data, " Unable to load public key");
  424. else {
  425. switch(EVP_PKEY_id(pubkey)) {
  426. case EVP_PKEY_RSA:
  427. result = get_pkey_rsa(data, pubkey, mem, i);
  428. break;
  429. #ifndef OPENSSL_NO_DSA
  430. case EVP_PKEY_DSA:
  431. result = get_pkey_dsa(data, pubkey, mem, i);
  432. break;
  433. #endif
  434. case EVP_PKEY_DH:
  435. result = get_pkey_dh(data, pubkey, mem, i);
  436. break;
  437. }
  438. EVP_PKEY_free(pubkey);
  439. }
  440. if(!result && psig) {
  441. const unsigned char *psigdata = ASN1_STRING_get0_data(psig);
  442. for(j = 0; j < ASN1_STRING_length(psig); j++)
  443. BIO_printf(mem, "%02x:", psigdata[j]);
  444. result = push_certinfo(data, mem, "Signature", i);
  445. }
  446. if(!result) {
  447. PEM_write_bio_X509(mem, x);
  448. result = push_certinfo(data, mem, "Cert", i);
  449. }
  450. }
  451. BIO_free(mem);
  452. if(result)
  453. /* cleanup all leftovers */
  454. Curl_ssl_free_certinfo(data);
  455. return result;
  456. }
  457. #endif /* USE_QUICHE || USE_OPENSSL */
  458. #ifdef USE_OPENSSL
  459. static int ossl_bio_cf_create(BIO *bio)
  460. {
  461. BIO_set_shutdown(bio, 1);
  462. BIO_set_init(bio, 1);
  463. BIO_set_data(bio, NULL);
  464. return 1;
  465. }
  466. static int ossl_bio_cf_destroy(BIO *bio)
  467. {
  468. if(!bio)
  469. return 0;
  470. return 1;
  471. }
  472. static long ossl_bio_cf_ctrl(BIO *bio, int cmd, long num, void *ptr)
  473. {
  474. struct Curl_cfilter *cf = BIO_get_data(bio);
  475. long ret = 1;
  476. (void)cf;
  477. (void)ptr;
  478. switch(cmd) {
  479. case BIO_CTRL_GET_CLOSE:
  480. ret = (long)BIO_get_shutdown(bio);
  481. break;
  482. case BIO_CTRL_SET_CLOSE:
  483. BIO_set_shutdown(bio, (int)num);
  484. break;
  485. case BIO_CTRL_FLUSH:
  486. /* we do no delayed writes, but if we ever would, this
  487. * needs to trigger it. */
  488. ret = 1;
  489. break;
  490. case BIO_CTRL_DUP:
  491. ret = 1;
  492. break;
  493. case BIO_CTRL_EOF: {
  494. /* EOF has been reached on input? */
  495. struct ssl_connect_data *connssl = cf->ctx;
  496. return connssl->peer_closed;
  497. }
  498. default:
  499. ret = 0;
  500. break;
  501. }
  502. return ret;
  503. }
  504. static int ossl_bio_cf_out_write(BIO *bio, const char *buf, int blen)
  505. {
  506. struct Curl_cfilter *cf = BIO_get_data(bio);
  507. struct ssl_connect_data *connssl = cf->ctx;
  508. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  509. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  510. size_t nwritten;
  511. CURLcode result;
  512. DEBUGASSERT(data);
  513. if(blen < 0)
  514. return 0;
  515. result = Curl_conn_cf_send(cf->next, data,
  516. (const uint8_t *)buf, (size_t)blen, FALSE,
  517. &nwritten);
  518. CURL_TRC_CF(data, cf, "ossl_bio_cf_out_write(len=%d) -> %d, %zu",
  519. blen, result, nwritten);
  520. BIO_clear_retry_flags(bio);
  521. octx->io_result = result;
  522. if(result) {
  523. if(CURLE_AGAIN == result)
  524. BIO_set_retry_write(bio);
  525. return -1;
  526. }
  527. return (int)nwritten;
  528. }
  529. static int ossl_bio_cf_in_read(BIO *bio, char *buf, int blen)
  530. {
  531. struct Curl_cfilter *cf = BIO_get_data(bio);
  532. struct ssl_connect_data *connssl = cf->ctx;
  533. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  534. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  535. size_t nread;
  536. CURLcode result, r2;
  537. DEBUGASSERT(data);
  538. /* OpenSSL catches this case, so should we. */
  539. if(!buf)
  540. return 0;
  541. if(blen < 0)
  542. return 0;
  543. result = Curl_conn_cf_recv(cf->next, data, buf, (size_t)blen, &nread);
  544. CURL_TRC_CF(data, cf, "ossl_bio_cf_in_read(len=%d) -> %d, %zu",
  545. blen, result, nread);
  546. BIO_clear_retry_flags(bio);
  547. octx->io_result = result;
  548. if(result) {
  549. if(CURLE_AGAIN == result)
  550. BIO_set_retry_read(bio);
  551. }
  552. else {
  553. /* feeding data to OpenSSL means SSL_read() might succeed */
  554. connssl->input_pending = TRUE;
  555. if(nread == 0)
  556. connssl->peer_closed = TRUE;
  557. }
  558. /* Before returning server replies to the SSL instance, we need
  559. * to have setup the x509 store or verification will fail. */
  560. if(!octx->x509_store_setup) {
  561. r2 = Curl_ssl_setup_x509_store(cf, data, octx);
  562. if(r2) {
  563. BIO_clear_retry_flags(bio);
  564. octx->io_result = r2;
  565. return -1;
  566. }
  567. octx->x509_store_setup = TRUE;
  568. }
  569. return result ? -1 : (int)nread;
  570. }
  571. static BIO_METHOD *ossl_bio_cf_method_create(void)
  572. {
  573. BIO_METHOD *m = BIO_meth_new(BIO_TYPE_MEM, "OpenSSL CF BIO");
  574. if(m) {
  575. BIO_meth_set_write(m, &ossl_bio_cf_out_write);
  576. BIO_meth_set_read(m, &ossl_bio_cf_in_read);
  577. BIO_meth_set_ctrl(m, &ossl_bio_cf_ctrl);
  578. BIO_meth_set_create(m, &ossl_bio_cf_create);
  579. BIO_meth_set_destroy(m, &ossl_bio_cf_destroy);
  580. }
  581. return m;
  582. }
  583. static void ossl_bio_cf_method_free(BIO_METHOD *m)
  584. {
  585. if(m)
  586. BIO_meth_free(m);
  587. }
  588. #ifdef HAVE_KEYLOG_CALLBACK
  589. static void ossl_keylog_callback(const SSL *ssl, const char *line)
  590. {
  591. (void)ssl;
  592. Curl_tls_keylog_write_line(line);
  593. }
  594. #else
  595. /*
  596. * ossl_log_tls12_secret is called by libcurl to make the CLIENT_RANDOMs if the
  597. * OpenSSL being used does not have native support for doing that.
  598. */
  599. static void ossl_log_tls12_secret(const SSL *ssl, bool *keylog_done)
  600. {
  601. const SSL_SESSION *session;
  602. unsigned char client_random[SSL3_RANDOM_SIZE];
  603. unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
  604. int master_key_length = 0;
  605. ERR_set_mark();
  606. session = SSL_get_session(ssl);
  607. if(!session || *keylog_done) {
  608. ERR_pop_to_mark();
  609. return;
  610. }
  611. SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE);
  612. master_key_length = (int)
  613. SSL_SESSION_get_master_key(session, master_key, SSL_MAX_MASTER_KEY_LENGTH);
  614. ERR_pop_to_mark();
  615. /* The handshake has not progressed sufficiently yet, or this is a TLS 1.3
  616. * session (when curl was built with older OpenSSL headers and running with
  617. * newer OpenSSL runtime libraries). */
  618. if(master_key_length <= 0)
  619. return;
  620. *keylog_done = TRUE;
  621. Curl_tls_keylog_write("CLIENT_RANDOM", client_random,
  622. master_key, master_key_length);
  623. }
  624. #endif /* !HAVE_KEYLOG_CALLBACK */
  625. static const char *SSL_ERROR_to_str(int err)
  626. {
  627. switch(err) {
  628. case SSL_ERROR_NONE:
  629. return "SSL_ERROR_NONE";
  630. case SSL_ERROR_SSL:
  631. return "SSL_ERROR_SSL";
  632. case SSL_ERROR_WANT_READ:
  633. return "SSL_ERROR_WANT_READ";
  634. case SSL_ERROR_WANT_WRITE:
  635. return "SSL_ERROR_WANT_WRITE";
  636. case SSL_ERROR_WANT_X509_LOOKUP:
  637. return "SSL_ERROR_WANT_X509_LOOKUP";
  638. case SSL_ERROR_SYSCALL:
  639. return "SSL_ERROR_SYSCALL";
  640. case SSL_ERROR_ZERO_RETURN:
  641. return "SSL_ERROR_ZERO_RETURN";
  642. case SSL_ERROR_WANT_CONNECT:
  643. return "SSL_ERROR_WANT_CONNECT";
  644. case SSL_ERROR_WANT_ACCEPT:
  645. return "SSL_ERROR_WANT_ACCEPT";
  646. #ifdef SSL_ERROR_WANT_ASYNC /* OpenSSL 1.1.0+, LibreSSL 3.6.0+ */
  647. case SSL_ERROR_WANT_ASYNC:
  648. return "SSL_ERROR_WANT_ASYNC";
  649. #endif
  650. #ifdef SSL_ERROR_WANT_ASYNC_JOB /* OpenSSL 1.1.0+, LibreSSL 3.6.0+ */
  651. case SSL_ERROR_WANT_ASYNC_JOB:
  652. return "SSL_ERROR_WANT_ASYNC_JOB";
  653. #endif
  654. #ifdef SSL_ERROR_WANT_CLIENT_HELLO_CB /* OpenSSL 1.1.1, LibreSSL 3.6.0+ */
  655. case SSL_ERROR_WANT_CLIENT_HELLO_CB:
  656. return "SSL_ERROR_WANT_CLIENT_HELLO_CB";
  657. #endif
  658. default:
  659. return "SSL_ERROR unknown";
  660. }
  661. }
  662. /* Return error string for last OpenSSL error
  663. */
  664. static char *ossl_strerror(unsigned long error, char *buf, size_t size)
  665. {
  666. size_t len;
  667. DEBUGASSERT(size);
  668. *buf = '\0';
  669. len = Curl_ossl_version(buf, size);
  670. DEBUGASSERT(len < (size - 2));
  671. if(len < (size - 2)) {
  672. buf += len;
  673. size -= (len + 2);
  674. *buf++ = ':';
  675. *buf++ = ' ';
  676. *buf = '\0';
  677. }
  678. #ifdef HAVE_BORINGSSL_LIKE
  679. ERR_error_string_n((uint32_t)error, buf, size);
  680. #else
  681. ERR_error_string_n(error, buf, size);
  682. #endif
  683. if(!*buf) {
  684. const char *msg = error ? "Unknown error" : "No error";
  685. curlx_strcopy(buf, size, msg, strlen(msg));
  686. }
  687. return buf;
  688. }
  689. static int passwd_callback(char *buf, int num, int encrypting, void *password)
  690. {
  691. DEBUGASSERT(encrypting == 0);
  692. if(!encrypting && num >= 0 && password) {
  693. int klen = curlx_uztosi(strlen((char *)password));
  694. if(num > klen) {
  695. memcpy(buf, password, klen + 1);
  696. return klen;
  697. }
  698. }
  699. return 0;
  700. }
  701. /*
  702. * rand_enough() returns TRUE if we have seeded the random engine properly.
  703. */
  704. static bool rand_enough(void)
  705. {
  706. return RAND_status() != 0;
  707. }
  708. static CURLcode ossl_seed(struct Curl_easy *data)
  709. {
  710. /* This might get called before it has been added to a multi handle */
  711. if(data->multi && data->multi->ssl_seeded)
  712. return CURLE_OK;
  713. if(rand_enough()) {
  714. /* OpenSSL 1.1.0+ should return here */
  715. if(data->multi)
  716. data->multi->ssl_seeded = TRUE;
  717. return CURLE_OK;
  718. }
  719. failf(data, "Insufficient randomness");
  720. return CURLE_SSL_CONNECT_ERROR;
  721. }
  722. #ifndef SSL_FILETYPE_ENGINE
  723. #define SSL_FILETYPE_ENGINE 42
  724. #endif
  725. #ifndef SSL_FILETYPE_PKCS12
  726. #define SSL_FILETYPE_PKCS12 43
  727. #endif
  728. #ifndef SSL_FILETYPE_PROVIDER
  729. #define SSL_FILETYPE_PROVIDER 44
  730. #endif
  731. static int ossl_do_file_type(const char *type)
  732. {
  733. if(!type || !type[0])
  734. return SSL_FILETYPE_PEM;
  735. if(curl_strequal(type, "PEM"))
  736. return SSL_FILETYPE_PEM;
  737. if(curl_strequal(type, "DER"))
  738. return SSL_FILETYPE_ASN1;
  739. if(curl_strequal(type, "PROV"))
  740. return SSL_FILETYPE_PROVIDER;
  741. if(curl_strequal(type, "ENG"))
  742. return SSL_FILETYPE_ENGINE;
  743. if(curl_strequal(type, "P12"))
  744. return SSL_FILETYPE_PKCS12;
  745. return -1;
  746. }
  747. #if defined(USE_OPENSSL_ENGINE) || defined(OPENSSL_HAS_PROVIDERS)
  748. /*
  749. * Supply default password to the engine user interface conversation.
  750. * The password is passed by OpenSSL engine from ENGINE_load_private_key()
  751. * last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
  752. */
  753. static int ssl_ui_reader(UI *ui, UI_STRING *uis)
  754. {
  755. const char *password;
  756. switch(UI_get_string_type(uis)) {
  757. case UIT_PROMPT:
  758. case UIT_VERIFY:
  759. password = (const char *)UI_get0_user_data(ui);
  760. if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
  761. UI_set_result(ui, uis, password);
  762. return 1;
  763. }
  764. FALLTHROUGH();
  765. default:
  766. break;
  767. }
  768. return (UI_method_get_reader(UI_OpenSSL()))(ui, uis);
  769. }
  770. /*
  771. * Suppress interactive request for a default password if available.
  772. */
  773. static int ssl_ui_writer(UI *ui, UI_STRING *uis)
  774. {
  775. switch(UI_get_string_type(uis)) {
  776. case UIT_PROMPT:
  777. case UIT_VERIFY:
  778. if(UI_get0_user_data(ui) &&
  779. (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
  780. return 1;
  781. }
  782. FALLTHROUGH();
  783. default:
  784. break;
  785. }
  786. return (UI_method_get_writer(UI_OpenSSL()))(ui, uis);
  787. }
  788. /*
  789. * Check if a given string is a PKCS#11 URI
  790. */
  791. static bool is_pkcs11_uri(const char *string)
  792. {
  793. return string && curl_strnequal(string, "pkcs11:", 7);
  794. }
  795. #endif
  796. static CURLcode ossl_set_engine(struct Curl_easy *data, const char *engine);
  797. #ifdef OPENSSL_HAS_PROVIDERS
  798. static CURLcode ossl_set_provider(struct Curl_easy *data,
  799. const char *provider);
  800. #endif
  801. static int use_certificate_blob(SSL_CTX *ctx, const struct curl_blob *blob,
  802. int type, const char *key_passwd)
  803. {
  804. int ret = 0;
  805. X509 *x = NULL;
  806. /* the typecast of blob->len is fine since it is guaranteed to never be
  807. larger than CURL_MAX_INPUT_LENGTH */
  808. BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len));
  809. if(!in)
  810. return CURLE_OUT_OF_MEMORY;
  811. if(type == SSL_FILETYPE_ASN1) {
  812. /* j = ERR_R_ASN1_LIB; */
  813. x = d2i_X509_bio(in, NULL);
  814. }
  815. else if(type == SSL_FILETYPE_PEM) {
  816. /* ERR_R_PEM_LIB; */
  817. x = PEM_read_bio_X509(in, NULL, passwd_callback, CURL_UNCONST(key_passwd));
  818. }
  819. else {
  820. ret = 0;
  821. goto end;
  822. }
  823. if(!x) {
  824. ret = 0;
  825. goto end;
  826. }
  827. ret = SSL_CTX_use_certificate(ctx, x);
  828. end:
  829. X509_free(x);
  830. BIO_free(in);
  831. return ret;
  832. }
  833. static int use_privatekey_blob(SSL_CTX *ctx, const struct curl_blob *blob,
  834. int type, const char *key_passwd)
  835. {
  836. int ret = 0;
  837. EVP_PKEY *pkey = NULL;
  838. BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len));
  839. if(!in)
  840. return CURLE_OUT_OF_MEMORY;
  841. if(type == SSL_FILETYPE_PEM)
  842. pkey = PEM_read_bio_PrivateKey(in, NULL, passwd_callback,
  843. CURL_UNCONST(key_passwd));
  844. else if(type == SSL_FILETYPE_ASN1)
  845. pkey = d2i_PrivateKey_bio(in, NULL);
  846. else
  847. goto end;
  848. if(!pkey)
  849. goto end;
  850. ret = SSL_CTX_use_PrivateKey(ctx, pkey);
  851. EVP_PKEY_free(pkey);
  852. end:
  853. BIO_free(in);
  854. return ret;
  855. }
  856. static int use_certificate_chain_blob(SSL_CTX *ctx,
  857. const struct curl_blob *blob,
  858. const char *key_passwd)
  859. {
  860. int ret = 0;
  861. X509 *x = NULL;
  862. BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len));
  863. if(!in)
  864. return CURLE_OUT_OF_MEMORY;
  865. ERR_clear_error();
  866. x = PEM_read_bio_X509_AUX(in, NULL,
  867. passwd_callback, CURL_UNCONST(key_passwd));
  868. if(!x)
  869. goto end;
  870. ret = SSL_CTX_use_certificate(ctx, x);
  871. if(ERR_peek_error() != 0)
  872. ret = 0;
  873. if(ret) {
  874. X509 *ca;
  875. sslerr_t err;
  876. if(!SSL_CTX_clear_chain_certs(ctx)) {
  877. ret = 0;
  878. goto end;
  879. }
  880. while((ca = PEM_read_bio_X509(in, NULL, passwd_callback,
  881. CURL_UNCONST(key_passwd))) != NULL) {
  882. if(!SSL_CTX_add0_chain_cert(ctx, ca)) {
  883. X509_free(ca);
  884. ret = 0;
  885. goto end;
  886. }
  887. }
  888. err = ERR_peek_last_error();
  889. if((ERR_GET_LIB(err) == ERR_LIB_PEM) &&
  890. (ERR_GET_REASON(err) == PEM_R_NO_START_LINE))
  891. ERR_clear_error();
  892. else
  893. ret = 0;
  894. }
  895. end:
  896. X509_free(x);
  897. BIO_free(in);
  898. return ret;
  899. }
  900. static int enginecheck(struct Curl_easy *data,
  901. SSL_CTX* ctx,
  902. const char *key_file,
  903. const char *key_passwd)
  904. #ifdef USE_OPENSSL_ENGINE
  905. {
  906. EVP_PKEY *priv_key = NULL;
  907. /* Implicitly use pkcs11 engine if none was provided and the
  908. * key_file is a PKCS#11 URI */
  909. if(!data->state.engine) {
  910. if(is_pkcs11_uri(key_file)) {
  911. if(ossl_set_engine(data, "pkcs11") != CURLE_OK) {
  912. return 0;
  913. }
  914. }
  915. }
  916. if(data->state.engine) {
  917. UI_METHOD *ui_method = UI_create_method("curl user interface");
  918. if(!ui_method) {
  919. failf(data, "unable to create " OSSL_PACKAGE " user-interface method");
  920. return 0;
  921. }
  922. UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
  923. UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
  924. UI_method_set_reader(ui_method, ssl_ui_reader);
  925. UI_method_set_writer(ui_method, ssl_ui_writer);
  926. priv_key = ENGINE_load_private_key(data->state.engine, key_file,
  927. ui_method,
  928. CURL_UNCONST(key_passwd));
  929. UI_destroy_method(ui_method);
  930. if(!priv_key) {
  931. failf(data, "failed to load private key from crypto engine");
  932. return 0;
  933. }
  934. if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
  935. failf(data, "unable to set private key");
  936. EVP_PKEY_free(priv_key);
  937. return 0;
  938. }
  939. EVP_PKEY_free(priv_key); /* we do not need the handle any more... */
  940. }
  941. else {
  942. failf(data, "crypto engine not set, cannot load private key");
  943. return 0;
  944. }
  945. return 1;
  946. }
  947. #else
  948. {
  949. (void)ctx;
  950. (void)key_file;
  951. (void)key_passwd;
  952. failf(data, "SSL_FILETYPE_ENGINE not supported for private key");
  953. return 0;
  954. }
  955. #endif
  956. static int providercheck(struct Curl_easy *data,
  957. SSL_CTX* ctx,
  958. const char *key_file)
  959. #ifdef OPENSSL_HAS_PROVIDERS
  960. {
  961. char error_buffer[256];
  962. /* Implicitly use pkcs11 provider if none was provided and the
  963. * key_file is a PKCS#11 URI */
  964. if(!data->state.provider_loaded) {
  965. if(is_pkcs11_uri(key_file)) {
  966. if(ossl_set_provider(data, "pkcs11") != CURLE_OK) {
  967. return 0;
  968. }
  969. }
  970. }
  971. if(data->state.provider_loaded) {
  972. /* Load the private key from the provider */
  973. EVP_PKEY *priv_key = NULL;
  974. OSSL_STORE_CTX *store = NULL;
  975. OSSL_STORE_INFO *info = NULL;
  976. UI_METHOD *ui_method = UI_create_method("curl user interface");
  977. if(!ui_method) {
  978. failf(data, "unable to create " OSSL_PACKAGE " user-interface method");
  979. return 0;
  980. }
  981. UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
  982. UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
  983. UI_method_set_reader(ui_method, ssl_ui_reader);
  984. UI_method_set_writer(ui_method, ssl_ui_writer);
  985. store = OSSL_STORE_open_ex(key_file, data->state.libctx,
  986. data->state.propq, ui_method, NULL, NULL,
  987. NULL, NULL);
  988. if(!store) {
  989. failf(data, "Failed to open OpenSSL store: %s",
  990. ossl_strerror(ERR_get_error(), error_buffer,
  991. sizeof(error_buffer)));
  992. UI_destroy_method(ui_method);
  993. return 0;
  994. }
  995. if(OSSL_STORE_expect(store, OSSL_STORE_INFO_PKEY) != 1) {
  996. failf(data, "Failed to set store preference. Ignoring the error: %s",
  997. ossl_strerror(ERR_get_error(), error_buffer,
  998. sizeof(error_buffer)));
  999. }
  1000. info = OSSL_STORE_load(store);
  1001. if(info) {
  1002. int ossl_type = OSSL_STORE_INFO_get_type(info);
  1003. if(ossl_type == OSSL_STORE_INFO_PKEY)
  1004. priv_key = OSSL_STORE_INFO_get1_PKEY(info);
  1005. OSSL_STORE_INFO_free(info);
  1006. }
  1007. OSSL_STORE_close(store);
  1008. UI_destroy_method(ui_method);
  1009. if(!priv_key) {
  1010. failf(data, "No private key found in the openssl store: %s",
  1011. ossl_strerror(ERR_get_error(), error_buffer,
  1012. sizeof(error_buffer)));
  1013. return 0;
  1014. }
  1015. if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
  1016. failf(data, "unable to set private key [%s]",
  1017. ossl_strerror(ERR_get_error(), error_buffer,
  1018. sizeof(error_buffer)));
  1019. EVP_PKEY_free(priv_key);
  1020. return 0;
  1021. }
  1022. EVP_PKEY_free(priv_key); /* we do not need the handle any more... */
  1023. }
  1024. else {
  1025. failf(data, "crypto provider not set, cannot load private key");
  1026. return 0;
  1027. }
  1028. return 1;
  1029. }
  1030. #else
  1031. {
  1032. (void)ctx;
  1033. (void)key_file;
  1034. failf(data, "SSL_FILETYPE_PROVIDER not supported for private key");
  1035. return 0;
  1036. }
  1037. #endif
  1038. static int engineload(struct Curl_easy *data,
  1039. SSL_CTX* ctx,
  1040. const char *cert_file)
  1041. /* ENGINE_CTRL_GET_CMD_FROM_NAME supported by OpenSSL, LibreSSL <=3.8.3 */
  1042. #if defined(USE_OPENSSL_ENGINE) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
  1043. {
  1044. char error_buffer[256];
  1045. /* Implicitly use pkcs11 engine if none was provided and the
  1046. * cert_file is a PKCS#11 URI */
  1047. if(!data->state.engine) {
  1048. if(is_pkcs11_uri(cert_file)) {
  1049. if(ossl_set_engine(data, "pkcs11") != CURLE_OK) {
  1050. return 0;
  1051. }
  1052. }
  1053. }
  1054. if(data->state.engine) {
  1055. const char *cmd_name = "LOAD_CERT_CTRL";
  1056. struct {
  1057. const char *cert_id;
  1058. X509 *cert;
  1059. } params;
  1060. params.cert_id = cert_file;
  1061. params.cert = NULL;
  1062. /* Does the engine supports LOAD_CERT_CTRL ? */
  1063. if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
  1064. 0, CURL_UNCONST(cmd_name), NULL)) {
  1065. failf(data, "ssl engine does not support loading certificates");
  1066. return 0;
  1067. }
  1068. /* Load the certificate from the engine */
  1069. if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
  1070. 0, &params, NULL, 1)) {
  1071. failf(data, "ssl engine cannot load client cert with id '%s' [%s]",
  1072. cert_file,
  1073. ossl_strerror(ERR_get_error(), error_buffer,
  1074. sizeof(error_buffer)));
  1075. return 0;
  1076. }
  1077. if(!params.cert) {
  1078. failf(data, "ssl engine did not initialized the certificate properly.");
  1079. return 0;
  1080. }
  1081. if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
  1082. failf(data, "unable to set client certificate [%s]",
  1083. ossl_strerror(ERR_get_error(), error_buffer,
  1084. sizeof(error_buffer)));
  1085. X509_free(params.cert);
  1086. return 0;
  1087. }
  1088. X509_free(params.cert); /* we do not need the handle any more... */
  1089. }
  1090. else {
  1091. failf(data, "crypto engine not set, cannot load certificate");
  1092. return 0;
  1093. }
  1094. return 1;
  1095. }
  1096. #else
  1097. {
  1098. (void)ctx;
  1099. (void)cert_file;
  1100. failf(data, "SSL_FILETYPE_ENGINE not supported for certificate");
  1101. return 0;
  1102. }
  1103. #endif
  1104. static int providerload(struct Curl_easy *data,
  1105. SSL_CTX* ctx,
  1106. const char *cert_file)
  1107. #ifdef OPENSSL_HAS_PROVIDERS
  1108. {
  1109. char error_buffer[256];
  1110. /* Implicitly use pkcs11 provider if none was provided and the
  1111. * cert_file is a PKCS#11 URI */
  1112. if(!data->state.provider_loaded) {
  1113. if(is_pkcs11_uri(cert_file)) {
  1114. if(ossl_set_provider(data, "pkcs11") != CURLE_OK) {
  1115. return 0;
  1116. }
  1117. }
  1118. }
  1119. if(data->state.provider_loaded) {
  1120. /* Load the certificate from the provider */
  1121. OSSL_STORE_INFO *info = NULL;
  1122. X509 *cert = NULL;
  1123. OSSL_STORE_CTX *store =
  1124. OSSL_STORE_open_ex(cert_file, data->state.libctx,
  1125. NULL, NULL, NULL, NULL, NULL, NULL);
  1126. int rc;
  1127. if(!store) {
  1128. failf(data, "Failed to open OpenSSL store: %s",
  1129. ossl_strerror(ERR_get_error(), error_buffer,
  1130. sizeof(error_buffer)));
  1131. return 0;
  1132. }
  1133. if(OSSL_STORE_expect(store, OSSL_STORE_INFO_CERT) != 1) {
  1134. failf(data, "Failed to set store preference. Ignoring the error: %s",
  1135. ossl_strerror(ERR_get_error(), error_buffer,
  1136. sizeof(error_buffer)));
  1137. }
  1138. info = OSSL_STORE_load(store);
  1139. if(info) {
  1140. int ossl_type = OSSL_STORE_INFO_get_type(info);
  1141. if(ossl_type == OSSL_STORE_INFO_CERT)
  1142. cert = OSSL_STORE_INFO_get1_CERT(info);
  1143. OSSL_STORE_INFO_free(info);
  1144. }
  1145. OSSL_STORE_close(store);
  1146. if(!cert) {
  1147. failf(data, "No cert found in the openssl store: %s",
  1148. ossl_strerror(ERR_get_error(), error_buffer,
  1149. sizeof(error_buffer)));
  1150. return 0;
  1151. }
  1152. rc = SSL_CTX_use_certificate(ctx, cert);
  1153. X509_free(cert); /* we do not need the handle any more... */
  1154. if(rc != 1) {
  1155. failf(data, "unable to set client certificate [%s]",
  1156. ossl_strerror(ERR_get_error(), error_buffer,
  1157. sizeof(error_buffer)));
  1158. return 0;
  1159. }
  1160. }
  1161. else {
  1162. failf(data, "crypto provider not set, cannot load certificate");
  1163. return 0;
  1164. }
  1165. return 1;
  1166. }
  1167. #else
  1168. {
  1169. (void)ctx;
  1170. (void)cert_file;
  1171. failf(data, "SSL_FILETYPE_PROVIDER not supported for certificate");
  1172. return 0;
  1173. }
  1174. #endif
  1175. static int pkcs12load(struct Curl_easy *data,
  1176. SSL_CTX* ctx,
  1177. const struct curl_blob *cert_blob,
  1178. const char *cert_file,
  1179. const char *key_passwd)
  1180. {
  1181. char error_buffer[256];
  1182. BIO *cert_bio = NULL;
  1183. PKCS12 *p12 = NULL;
  1184. EVP_PKEY *pri;
  1185. X509 *x509;
  1186. int cert_done = 0;
  1187. STACK_OF(X509) *ca = NULL;
  1188. if(cert_blob) {
  1189. cert_bio = BIO_new_mem_buf(cert_blob->data, (int)(cert_blob->len));
  1190. if(!cert_bio) {
  1191. failf(data, "BIO_new_mem_buf NULL, " OSSL_PACKAGE " error %s",
  1192. ossl_strerror(ERR_get_error(), error_buffer,
  1193. sizeof(error_buffer)) );
  1194. return 0;
  1195. }
  1196. }
  1197. else {
  1198. cert_bio = BIO_new(BIO_s_file());
  1199. if(!cert_bio) {
  1200. failf(data, "BIO_new return NULL, " OSSL_PACKAGE " error %s",
  1201. ossl_strerror(ERR_get_error(), error_buffer,
  1202. sizeof(error_buffer)) );
  1203. return 0;
  1204. }
  1205. if(BIO_read_filename(cert_bio, CURL_UNCONST(cert_file)) <= 0) {
  1206. failf(data, "could not open PKCS12 file '%s'", cert_file);
  1207. BIO_free(cert_bio);
  1208. return 0;
  1209. }
  1210. }
  1211. p12 = d2i_PKCS12_bio(cert_bio, NULL);
  1212. BIO_free(cert_bio);
  1213. if(!p12) {
  1214. failf(data, "error reading PKCS12 file '%s'",
  1215. cert_blob ? "(memory blob)" : cert_file);
  1216. return 0;
  1217. }
  1218. if(!PKCS12_parse(p12, key_passwd, &pri, &x509, &ca)) {
  1219. failf(data, "could not parse PKCS12 file, check password, " OSSL_PACKAGE
  1220. " error %s",
  1221. ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)));
  1222. PKCS12_free(p12);
  1223. return 0;
  1224. }
  1225. PKCS12_free(p12);
  1226. if(SSL_CTX_use_certificate(ctx, x509) != 1) {
  1227. failf(data, "could not load PKCS12 client certificate, " OSSL_PACKAGE
  1228. " error %s",
  1229. ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)));
  1230. goto fail;
  1231. }
  1232. if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
  1233. failf(data, "unable to use private key from PKCS12 file '%s'", cert_file);
  1234. goto fail;
  1235. }
  1236. if(!SSL_CTX_check_private_key(ctx)) {
  1237. failf(data, "private key from PKCS12 file '%s' "
  1238. "does not match certificate in same file", cert_file);
  1239. goto fail;
  1240. }
  1241. /* Set Certificate Verification chain */
  1242. if(ca) {
  1243. while(sk_X509_num(ca)) {
  1244. /*
  1245. * Note that sk_X509_pop() is used below to make sure the cert is
  1246. * removed from the stack properly before getting passed to
  1247. * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously
  1248. * we used sk_X509_value() instead, but then we would clean it in the
  1249. * subsequent sk_X509_pop_free() call.
  1250. */
  1251. X509 *x = sk_X509_pop(ca);
  1252. if(!SSL_CTX_add_client_CA(ctx, x)) {
  1253. X509_free(x);
  1254. failf(data, "cannot add certificate to client CA list");
  1255. goto fail;
  1256. }
  1257. if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
  1258. X509_free(x);
  1259. failf(data, "cannot add certificate to certificate chain");
  1260. goto fail;
  1261. }
  1262. }
  1263. }
  1264. cert_done = 1;
  1265. fail:
  1266. EVP_PKEY_free(pri);
  1267. X509_free(x509);
  1268. #if defined(__clang__) && __clang_major__ >= 16
  1269. #pragma clang diagnostic push
  1270. #pragma clang diagnostic ignored "-Wcast-function-type-strict"
  1271. #endif
  1272. sk_X509_pop_free(ca, X509_free);
  1273. #if defined(__clang__) && __clang_major__ >= 16
  1274. #pragma clang diagnostic pop
  1275. #endif
  1276. if(!cert_done)
  1277. return 0; /* failure! */
  1278. return 1;
  1279. }
  1280. static CURLcode client_cert(struct Curl_easy *data,
  1281. SSL_CTX* ctx,
  1282. char *cert_file,
  1283. const struct curl_blob *cert_blob,
  1284. const char *cert_type,
  1285. char *key_file,
  1286. const struct curl_blob *key_blob,
  1287. const char *key_type,
  1288. char *key_passwd)
  1289. {
  1290. char error_buffer[256];
  1291. bool check_privkey = TRUE;
  1292. int file_type = ossl_do_file_type(cert_type);
  1293. if(cert_file || cert_blob || (file_type == SSL_FILETYPE_ENGINE) ||
  1294. (file_type == SSL_FILETYPE_PROVIDER)) {
  1295. SSL *ssl;
  1296. X509 *x509;
  1297. bool pcks12_done = FALSE;
  1298. int cert_use_result;
  1299. if(key_passwd) {
  1300. /* set the password in the callback userdata */
  1301. SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd);
  1302. /* Set passwd callback: */
  1303. SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
  1304. }
  1305. switch(file_type) {
  1306. case SSL_FILETYPE_PEM:
  1307. /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
  1308. cert_use_result = cert_blob ?
  1309. use_certificate_chain_blob(ctx, cert_blob, key_passwd) :
  1310. SSL_CTX_use_certificate_chain_file(ctx, cert_file);
  1311. if(cert_use_result != 1) {
  1312. failf(data,
  1313. "could not load PEM client certificate from %s, " OSSL_PACKAGE
  1314. " error %s, "
  1315. "(no key found, wrong passphrase, or wrong file format?)",
  1316. (cert_blob ? "CURLOPT_SSLCERT_BLOB" : cert_file),
  1317. ossl_strerror(ERR_get_error(), error_buffer,
  1318. sizeof(error_buffer)));
  1319. return CURLE_SSL_CERTPROBLEM;
  1320. }
  1321. break;
  1322. case SSL_FILETYPE_ASN1:
  1323. /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
  1324. we use the case above for PEM so this can only be performed with
  1325. ASN1 files. */
  1326. cert_use_result = cert_blob ?
  1327. use_certificate_blob(ctx, cert_blob, file_type, key_passwd) :
  1328. SSL_CTX_use_certificate_file(ctx, cert_file, file_type);
  1329. if(cert_use_result != 1) {
  1330. failf(data,
  1331. "could not load ASN1 client certificate from %s, " OSSL_PACKAGE
  1332. " error %s, "
  1333. "(no key found, wrong passphrase, or wrong file format?)",
  1334. (cert_blob ? "CURLOPT_SSLCERT_BLOB" : cert_file),
  1335. ossl_strerror(ERR_get_error(), error_buffer,
  1336. sizeof(error_buffer)));
  1337. return CURLE_SSL_CERTPROBLEM;
  1338. }
  1339. break;
  1340. case SSL_FILETYPE_ENGINE:
  1341. if(!cert_file || !engineload(data, ctx, cert_file))
  1342. return CURLE_SSL_CERTPROBLEM;
  1343. break;
  1344. case SSL_FILETYPE_PROVIDER:
  1345. if(!cert_file || !providerload(data, ctx, cert_file))
  1346. return CURLE_SSL_CERTPROBLEM;
  1347. break;
  1348. case SSL_FILETYPE_PKCS12:
  1349. if(!pkcs12load(data, ctx, cert_blob, cert_file, key_passwd))
  1350. return CURLE_SSL_CERTPROBLEM;
  1351. pcks12_done = TRUE;
  1352. break;
  1353. default:
  1354. failf(data, "not supported file type '%s' for certificate", cert_type);
  1355. return CURLE_BAD_FUNCTION_ARGUMENT;
  1356. }
  1357. if((!key_file) && (!key_blob)) {
  1358. key_file = cert_file;
  1359. key_blob = cert_blob;
  1360. }
  1361. else
  1362. file_type = ossl_do_file_type(key_type);
  1363. switch(file_type) {
  1364. case SSL_FILETYPE_PEM:
  1365. case SSL_FILETYPE_ASN1:
  1366. cert_use_result = key_blob ?
  1367. use_privatekey_blob(ctx, key_blob, file_type, key_passwd) :
  1368. SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type);
  1369. if(cert_use_result != 1) {
  1370. failf(data, "unable to set private key file: '%s' type %s",
  1371. key_file ? key_file : "(memory blob)",
  1372. key_type ? key_type : "PEM");
  1373. return CURLE_BAD_FUNCTION_ARGUMENT;
  1374. }
  1375. break;
  1376. case SSL_FILETYPE_ENGINE:
  1377. if(!enginecheck(data, ctx, key_file, key_passwd))
  1378. return CURLE_SSL_CERTPROBLEM;
  1379. break;
  1380. case SSL_FILETYPE_PROVIDER:
  1381. if(!providercheck(data, ctx, key_file))
  1382. return CURLE_SSL_CERTPROBLEM;
  1383. break;
  1384. case SSL_FILETYPE_PKCS12:
  1385. if(!pcks12_done) {
  1386. failf(data, "file type P12 for private key not supported");
  1387. return CURLE_SSL_CERTPROBLEM;
  1388. }
  1389. break;
  1390. default:
  1391. failf(data, "not supported file type for private key");
  1392. return CURLE_BAD_FUNCTION_ARGUMENT;
  1393. }
  1394. ssl = SSL_new(ctx);
  1395. if(!ssl) {
  1396. failf(data, "unable to create an SSL structure");
  1397. return CURLE_OUT_OF_MEMORY;
  1398. }
  1399. x509 = SSL_get_certificate(ssl);
  1400. if(x509) {
  1401. EVP_PKEY *pktmp = X509_get_pubkey(x509);
  1402. EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl));
  1403. EVP_PKEY_free(pktmp);
  1404. }
  1405. #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
  1406. {
  1407. /* If RSA is used, do not check the private key if its flags indicate
  1408. * it does not support it. */
  1409. EVP_PKEY *priv_key = SSL_get_privatekey(ssl);
  1410. if(EVP_PKEY_id(priv_key) == EVP_PKEY_RSA) {
  1411. RSA *rsa = EVP_PKEY_get1_RSA(priv_key);
  1412. if(RSA_flags(rsa) & RSA_METHOD_FLAG_NO_CHECK)
  1413. check_privkey = FALSE;
  1414. RSA_free(rsa); /* Decrement reference count */
  1415. }
  1416. }
  1417. #endif
  1418. SSL_free(ssl);
  1419. /* If we are using DSA, we can copy the parameters from
  1420. * the private key */
  1421. if(check_privkey == TRUE) {
  1422. /* Now we know that a key and cert have been set against
  1423. * the SSL context */
  1424. if(!SSL_CTX_check_private_key(ctx)) {
  1425. failf(data, "Private key does not match the certificate public key");
  1426. return CURLE_SSL_CERTPROBLEM;
  1427. }
  1428. }
  1429. }
  1430. return CURLE_OK;
  1431. }
  1432. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1433. /* returns non-zero on failure */
  1434. static CURLcode x509_name_oneline(X509_NAME *a, struct dynbuf *d)
  1435. {
  1436. BIO *bio_out = BIO_new(BIO_s_mem());
  1437. BUF_MEM *biomem;
  1438. int rc;
  1439. CURLcode result = CURLE_OUT_OF_MEMORY;
  1440. if(bio_out) {
  1441. unsigned long flags = XN_FLAG_SEP_SPLUS_SPC |
  1442. (XN_FLAG_ONELINE & ~ASN1_STRFLGS_ESC_MSB & ~XN_FLAG_SPC_EQ);
  1443. curlx_dyn_reset(d);
  1444. rc = X509_NAME_print_ex(bio_out, a, 0, flags);
  1445. if(rc != -1) {
  1446. BIO_get_mem_ptr(bio_out, &biomem);
  1447. result = curlx_dyn_addn(d, biomem->data, biomem->length);
  1448. }
  1449. BIO_free(bio_out);
  1450. }
  1451. return result;
  1452. }
  1453. #endif
  1454. /**
  1455. * Global SSL init
  1456. *
  1457. * @retval 0 error initializing SSL
  1458. * @retval 1 SSL initialized successfully
  1459. */
  1460. static int ossl_init(void)
  1461. {
  1462. const uint64_t flags =
  1463. #ifdef OPENSSL_INIT_ENGINE_ALL_BUILTIN
  1464. /* not present in BoringSSL */
  1465. OPENSSL_INIT_ENGINE_ALL_BUILTIN |
  1466. #endif
  1467. #ifdef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG
  1468. OPENSSL_INIT_NO_LOAD_CONFIG |
  1469. #else
  1470. OPENSSL_INIT_LOAD_CONFIG |
  1471. #endif
  1472. 0;
  1473. OPENSSL_init_ssl(flags, NULL);
  1474. Curl_tls_keylog_open();
  1475. return 1;
  1476. }
  1477. /* Global cleanup */
  1478. static void ossl_cleanup(void)
  1479. {
  1480. Curl_tls_keylog_close();
  1481. }
  1482. /* Selects an OpenSSL crypto engine or provider.
  1483. */
  1484. static CURLcode ossl_set_engine(struct Curl_easy *data, const char *name)
  1485. {
  1486. #ifdef USE_OPENSSL_ENGINE
  1487. CURLcode result = CURLE_SSL_ENGINE_NOTFOUND;
  1488. ENGINE *e = ENGINE_by_id(name);
  1489. if(e) {
  1490. if(data->state.engine) {
  1491. ENGINE_finish(data->state.engine);
  1492. ENGINE_free(data->state.engine);
  1493. data->state.engine = NULL;
  1494. }
  1495. if(!ENGINE_init(e)) {
  1496. char buf[256];
  1497. ENGINE_free(e);
  1498. failf(data, "Failed to initialise SSL Engine '%s': %s",
  1499. name, ossl_strerror(ERR_get_error(), buf, sizeof(buf)));
  1500. result = CURLE_SSL_ENGINE_INITFAILED;
  1501. e = NULL;
  1502. }
  1503. else {
  1504. result = CURLE_OK;
  1505. }
  1506. data->state.engine = e;
  1507. return result;
  1508. }
  1509. #endif
  1510. #ifdef OPENSSL_HAS_PROVIDERS
  1511. return ossl_set_provider(data, name);
  1512. #else
  1513. (void)name;
  1514. failf(data, "OpenSSL engine not found");
  1515. return CURLE_SSL_ENGINE_NOTFOUND;
  1516. #endif
  1517. }
  1518. /* Sets engine as default for all SSL operations
  1519. */
  1520. static CURLcode ossl_set_engine_default(struct Curl_easy *data)
  1521. {
  1522. #ifdef USE_OPENSSL_ENGINE
  1523. if(data->state.engine) {
  1524. if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
  1525. infof(data, "set default crypto engine '%s'",
  1526. ENGINE_get_id(data->state.engine));
  1527. }
  1528. else {
  1529. failf(data, "set default crypto engine '%s' failed",
  1530. ENGINE_get_id(data->state.engine));
  1531. return CURLE_SSL_ENGINE_SETFAILED;
  1532. }
  1533. }
  1534. #else
  1535. (void)data;
  1536. #endif
  1537. return CURLE_OK;
  1538. }
  1539. /* Return list of OpenSSL crypto engine names.
  1540. */
  1541. static struct curl_slist *ossl_engines_list(struct Curl_easy *data)
  1542. {
  1543. struct curl_slist *list = NULL;
  1544. #ifdef USE_OPENSSL_ENGINE
  1545. struct curl_slist *beg;
  1546. ENGINE *e;
  1547. for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
  1548. beg = curl_slist_append(list, ENGINE_get_id(e));
  1549. if(!beg) {
  1550. curl_slist_free_all(list);
  1551. return NULL;
  1552. }
  1553. list = beg;
  1554. }
  1555. #endif
  1556. (void)data;
  1557. return list;
  1558. }
  1559. #ifdef OPENSSL_HAS_PROVIDERS
  1560. static void ossl_provider_cleanup(struct Curl_easy *data)
  1561. {
  1562. if(data->state.baseprov) {
  1563. OSSL_PROVIDER_unload(data->state.baseprov);
  1564. data->state.baseprov = NULL;
  1565. }
  1566. if(data->state.provider) {
  1567. OSSL_PROVIDER_unload(data->state.provider);
  1568. data->state.provider = NULL;
  1569. }
  1570. OSSL_LIB_CTX_free(data->state.libctx);
  1571. data->state.libctx = NULL;
  1572. Curl_safefree(data->state.propq);
  1573. data->state.provider_loaded = FALSE;
  1574. }
  1575. #define MAX_PROVIDER_LEN 128 /* reasonable */
  1576. /* Selects an OpenSSL crypto provider.
  1577. *
  1578. * A provider might need an associated property, a string passed on to
  1579. * OpenSSL. Specify this as [PROVIDER][:PROPERTY]: separate the name and the
  1580. * property with a colon. No colon means no property is set.
  1581. *
  1582. * An example provider + property looks like "tpm2:?provider=tpm2".
  1583. */
  1584. static CURLcode ossl_set_provider(struct Curl_easy *data, const char *iname)
  1585. {
  1586. char name[MAX_PROVIDER_LEN + 1];
  1587. struct Curl_str prov;
  1588. const char *propq = NULL;
  1589. if(!iname) {
  1590. /* clear and cleanup provider use */
  1591. ossl_provider_cleanup(data);
  1592. return CURLE_OK;
  1593. }
  1594. if(curlx_str_until(&iname, &prov, MAX_PROVIDER_LEN, ':'))
  1595. return CURLE_BAD_FUNCTION_ARGUMENT;
  1596. if(!curlx_str_single(&iname, ':'))
  1597. /* there was a colon, get the propq until the end of string */
  1598. propq = iname;
  1599. /* we need the name in a buffer, null-terminated */
  1600. memcpy(name, curlx_str(&prov), curlx_strlen(&prov));
  1601. name[curlx_strlen(&prov)] = 0;
  1602. if(!data->state.libctx) {
  1603. OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new();
  1604. if(!libctx)
  1605. return CURLE_OUT_OF_MEMORY;
  1606. if(propq) {
  1607. data->state.propq = curlx_strdup(propq);
  1608. if(!data->state.propq) {
  1609. OSSL_LIB_CTX_free(libctx);
  1610. return CURLE_OUT_OF_MEMORY;
  1611. }
  1612. }
  1613. data->state.libctx = libctx;
  1614. }
  1615. #ifndef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG
  1616. /* load the configuration file into the library context before checking the
  1617. * provider availability */
  1618. if(!OSSL_LIB_CTX_load_config(data->state.libctx, NULL)) {
  1619. infof(data, "Failed to load default openssl config. Proceeding.");
  1620. }
  1621. #endif
  1622. if(OSSL_PROVIDER_available(data->state.libctx, name)) {
  1623. /* already loaded through the configuration - no action needed */
  1624. data->state.provider_loaded = TRUE;
  1625. return CURLE_OK;
  1626. }
  1627. data->state.provider = OSSL_PROVIDER_try_load(data->state.libctx, name, 1);
  1628. if(!data->state.provider) {
  1629. char error_buffer[256];
  1630. failf(data, "Failed to initialize provider: %s",
  1631. ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)));
  1632. ossl_provider_cleanup(data);
  1633. return CURLE_SSL_ENGINE_NOTFOUND;
  1634. }
  1635. /* load the base provider as well */
  1636. data->state.baseprov = OSSL_PROVIDER_try_load(data->state.libctx, "base", 1);
  1637. if(!data->state.baseprov) {
  1638. ossl_provider_cleanup(data);
  1639. failf(data, "Failed to load base");
  1640. return CURLE_SSL_ENGINE_NOTFOUND;
  1641. }
  1642. else
  1643. data->state.provider_loaded = TRUE;
  1644. return CURLE_OK;
  1645. }
  1646. #endif
  1647. static CURLcode ossl_shutdown(struct Curl_cfilter *cf,
  1648. struct Curl_easy *data,
  1649. bool send_shutdown, bool *done)
  1650. {
  1651. struct ssl_connect_data *connssl = cf->ctx;
  1652. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  1653. CURLcode result = CURLE_OK;
  1654. char buf[1024];
  1655. int nread = -1, err;
  1656. unsigned long sslerr;
  1657. size_t i;
  1658. DEBUGASSERT(octx);
  1659. if(!octx->ssl || cf->shutdown) {
  1660. *done = TRUE;
  1661. goto out;
  1662. }
  1663. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  1664. *done = FALSE;
  1665. if(!(SSL_get_shutdown(octx->ssl) & SSL_SENT_SHUTDOWN)) {
  1666. /* We have not started the shutdown from our side yet. Check
  1667. * if the server already sent us one. */
  1668. ERR_clear_error();
  1669. for(i = 0; i < 10; ++i) {
  1670. nread = SSL_read(octx->ssl, buf, (int)sizeof(buf));
  1671. CURL_TRC_CF(data, cf, "SSL shutdown not sent, read -> %d", nread);
  1672. if(nread <= 0)
  1673. break;
  1674. }
  1675. err = SSL_get_error(octx->ssl, nread);
  1676. if(!nread && err == SSL_ERROR_ZERO_RETURN) {
  1677. bool input_pending;
  1678. /* Yes, it did. */
  1679. if(!send_shutdown) {
  1680. CURL_TRC_CF(data, cf, "SSL shutdown received, not sending");
  1681. *done = TRUE;
  1682. goto out;
  1683. }
  1684. else if(!cf->next->cft->is_alive(cf->next, data, &input_pending)) {
  1685. /* Server closed the connection after its closy notify. It
  1686. * seems not interested to see our close notify, so do not
  1687. * send it. We are done. */
  1688. connssl->peer_closed = TRUE;
  1689. CURL_TRC_CF(data, cf, "peer closed connection");
  1690. *done = TRUE;
  1691. goto out;
  1692. }
  1693. }
  1694. }
  1695. /* SSL should now have started the shutdown from our side. Since it
  1696. * was not complete, we are lacking the close notify from the server. */
  1697. if(send_shutdown && !(SSL_get_shutdown(octx->ssl) & SSL_SENT_SHUTDOWN)) {
  1698. int rc;
  1699. ERR_clear_error();
  1700. CURL_TRC_CF(data, cf, "send SSL close notify");
  1701. rc = SSL_shutdown(octx->ssl);
  1702. if(rc == 1) {
  1703. CURL_TRC_CF(data, cf, "SSL shutdown finished");
  1704. *done = TRUE;
  1705. goto out;
  1706. }
  1707. if(SSL_ERROR_WANT_WRITE == SSL_get_error(octx->ssl, rc)) {
  1708. CURL_TRC_CF(data, cf, "SSL shutdown still wants to send");
  1709. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  1710. goto out;
  1711. }
  1712. /* Having sent the close notify, we use SSL_read() to get the
  1713. * missing close notify from the server. */
  1714. }
  1715. for(i = 0; i < 10; ++i) {
  1716. ERR_clear_error();
  1717. nread = SSL_read(octx->ssl, buf, (int)sizeof(buf));
  1718. CURL_TRC_CF(data, cf, "SSL shutdown read -> %d", nread);
  1719. if(nread <= 0)
  1720. break;
  1721. }
  1722. err = SSL_get_error(octx->ssl, nread);
  1723. switch(err) {
  1724. case SSL_ERROR_ZERO_RETURN: /* no more data */
  1725. if(SSL_shutdown(octx->ssl) == 1)
  1726. CURL_TRC_CF(data, cf, "SSL shutdown finished");
  1727. else
  1728. CURL_TRC_CF(data, cf, "SSL shutdown not received, but closed");
  1729. *done = TRUE;
  1730. break;
  1731. case SSL_ERROR_NONE: /* just did not get anything */
  1732. case SSL_ERROR_WANT_READ:
  1733. /* SSL has send its notify and now wants to read the reply
  1734. * from the server. We are not really interested in that. */
  1735. CURL_TRC_CF(data, cf, "SSL shutdown sent, want receive");
  1736. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  1737. break;
  1738. case SSL_ERROR_WANT_WRITE:
  1739. CURL_TRC_CF(data, cf, "SSL shutdown send blocked");
  1740. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  1741. break;
  1742. default:
  1743. /* Server seems to have closed the connection without sending us
  1744. * a close notify. */
  1745. sslerr = ERR_get_error();
  1746. CURL_TRC_CF(data, cf, "SSL shutdown, ignore recv error: '%s', errno %d",
  1747. (sslerr ?
  1748. ossl_strerror(sslerr, buf, sizeof(buf)) :
  1749. SSL_ERROR_to_str(err)),
  1750. SOCKERRNO);
  1751. *done = TRUE;
  1752. result = CURLE_OK;
  1753. break;
  1754. }
  1755. out:
  1756. cf->shutdown = (result || *done);
  1757. if(cf->shutdown || (connssl->io_need != CURL_SSL_IO_NEED_NONE))
  1758. connssl->input_pending = FALSE;
  1759. return result;
  1760. }
  1761. static void ossl_close(struct Curl_cfilter *cf, struct Curl_easy *data)
  1762. {
  1763. struct ssl_connect_data *connssl = cf->ctx;
  1764. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  1765. (void)data;
  1766. DEBUGASSERT(octx);
  1767. connssl->input_pending = FALSE;
  1768. if(octx->ssl) {
  1769. SSL_free(octx->ssl);
  1770. octx->ssl = NULL;
  1771. }
  1772. if(octx->ssl_ctx) {
  1773. SSL_CTX_free(octx->ssl_ctx);
  1774. octx->ssl_ctx = NULL;
  1775. octx->x509_store_setup = FALSE;
  1776. }
  1777. if(octx->bio_method) {
  1778. ossl_bio_cf_method_free(octx->bio_method);
  1779. octx->bio_method = NULL;
  1780. }
  1781. }
  1782. /*
  1783. * This function is called when the 'data' struct is going away. Close
  1784. * down everything and free all resources!
  1785. */
  1786. static void ossl_close_all(struct Curl_easy *data)
  1787. {
  1788. #ifdef USE_OPENSSL_ENGINE
  1789. if(data->state.engine) {
  1790. ENGINE_finish(data->state.engine);
  1791. ENGINE_free(data->state.engine);
  1792. data->state.engine = NULL;
  1793. }
  1794. #else
  1795. (void)data;
  1796. #endif
  1797. #ifdef OPENSSL_HAS_PROVIDERS
  1798. ossl_provider_cleanup(data);
  1799. #endif
  1800. }
  1801. /* ====================================================== */
  1802. /* Quote from RFC2818 section 3.1 "Server Identity"
  1803. If a subjectAltName extension of type dNSName is present, that MUST
  1804. be used as the identity. Otherwise, the (most specific) Common Name
  1805. field in the Subject field of the certificate MUST be used. Although
  1806. the use of the Common Name is existing practice, it is deprecated and
  1807. Certification Authorities are encouraged to use the dNSName instead.
  1808. Matching is performed using the matching rules specified by
  1809. [RFC2459]. If more than one identity of a given type is present in
  1810. the certificate (e.g., more than one dNSName name, a match in any one
  1811. of the set is considered acceptable.) Names may contain the wildcard
  1812. character * which is considered to match any single domain name
  1813. component or component fragment. E.g., *.a.com matches foo.a.com but
  1814. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  1815. In some cases, the URI is specified as an IP address rather than a
  1816. hostname. In this case, the iPAddress subjectAltName must be present
  1817. in the certificate and must exactly match the IP in the URI.
  1818. This function is now used from ngtcp2 (QUIC) as well.
  1819. */
  1820. static CURLcode ossl_verifyhost(struct Curl_easy *data,
  1821. struct connectdata *conn,
  1822. struct ssl_peer *peer,
  1823. X509 *server_cert)
  1824. {
  1825. bool matched = FALSE;
  1826. int target; /* target type, GEN_DNS or GEN_IPADD */
  1827. size_t addrlen = 0;
  1828. STACK_OF(GENERAL_NAME) *altnames;
  1829. #ifdef USE_IPV6
  1830. struct in6_addr addr;
  1831. #else
  1832. struct in_addr addr;
  1833. #endif
  1834. CURLcode result = CURLE_OK;
  1835. bool dNSName = FALSE; /* if a dNSName field exists in the cert */
  1836. bool iPAddress = FALSE; /* if an iPAddress field exists in the cert */
  1837. size_t hostlen = strlen(peer->hostname);
  1838. (void)conn;
  1839. switch(peer->type) {
  1840. case CURL_SSL_PEER_IPV4:
  1841. if(!curlx_inet_pton(AF_INET, peer->hostname, &addr))
  1842. return CURLE_PEER_FAILED_VERIFICATION;
  1843. target = GEN_IPADD;
  1844. addrlen = sizeof(struct in_addr);
  1845. break;
  1846. #ifdef USE_IPV6
  1847. case CURL_SSL_PEER_IPV6:
  1848. if(!curlx_inet_pton(AF_INET6, peer->hostname, &addr))
  1849. return CURLE_PEER_FAILED_VERIFICATION;
  1850. target = GEN_IPADD;
  1851. addrlen = sizeof(struct in6_addr);
  1852. break;
  1853. #endif
  1854. case CURL_SSL_PEER_DNS:
  1855. target = GEN_DNS;
  1856. break;
  1857. default:
  1858. DEBUGASSERT(0);
  1859. failf(data, "unexpected ssl peer type: %d", peer->type);
  1860. return CURLE_PEER_FAILED_VERIFICATION;
  1861. }
  1862. /* get a "list" of alternative names */
  1863. altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
  1864. if(altnames) {
  1865. #ifdef HAVE_BORINGSSL_LIKE
  1866. size_t numalts;
  1867. size_t i;
  1868. #else
  1869. int numalts;
  1870. int i;
  1871. #endif
  1872. /* get amount of alternatives, RFC2459 claims there MUST be at least
  1873. one, but we do not depend on it... */
  1874. numalts = sk_GENERAL_NAME_num(altnames);
  1875. /* loop through all alternatives - until a dnsmatch */
  1876. for(i = 0; (i < numalts) && !matched; i++) {
  1877. /* get a handle to alternative name number i */
  1878. const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
  1879. if(check->type == GEN_DNS)
  1880. dNSName = TRUE;
  1881. else if(check->type == GEN_IPADD)
  1882. iPAddress = TRUE;
  1883. /* only check alternatives of the same type the target is */
  1884. if(check->type == target) {
  1885. /* get data and length */
  1886. const char *altptr = (const char *)ASN1_STRING_get0_data(check->d.ia5);
  1887. size_t altlen = (size_t)ASN1_STRING_length(check->d.ia5);
  1888. switch(target) {
  1889. case GEN_DNS: /* name/pattern comparison */
  1890. /* The OpenSSL man page explicitly says: "In general it cannot be
  1891. assumed that the data returned by ASN1_STRING_data() is null
  1892. terminated or does not contain embedded nulls." But also that
  1893. "The actual format of the data will depend on the actual string
  1894. type itself: for example for an IA5String the data will be ASCII"
  1895. It has been however verified that in 0.9.6 and 0.9.7, IA5String
  1896. is always null-terminated.
  1897. */
  1898. if((altlen == strlen(altptr)) &&
  1899. /* if this is not true, there was an embedded zero in the name
  1900. string and we cannot match it. */
  1901. Curl_cert_hostcheck(altptr, altlen, peer->hostname, hostlen)) {
  1902. matched = TRUE;
  1903. infof(data, " subjectAltName: \"%s\" matches cert's \"%.*s\"",
  1904. peer->dispname, (int)altlen, altptr);
  1905. }
  1906. break;
  1907. case GEN_IPADD: /* IP address comparison */
  1908. /* compare alternative IP address if the data chunk is the same size
  1909. our server IP address is */
  1910. if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
  1911. matched = TRUE;
  1912. infof(data, " subjectAltName: \"%s\" matches cert's IP address!",
  1913. peer->dispname);
  1914. }
  1915. break;
  1916. }
  1917. }
  1918. }
  1919. GENERAL_NAMES_free(altnames);
  1920. }
  1921. if(matched)
  1922. /* an alternative name matched */
  1923. ;
  1924. else if(dNSName || iPAddress) {
  1925. const char *tname = (peer->type == CURL_SSL_PEER_DNS) ? "hostname" :
  1926. (peer->type == CURL_SSL_PEER_IPV4) ?
  1927. "ipv4 address" : "ipv6 address";
  1928. infof(data, " subjectAltName does not match %s %s", tname, peer->dispname);
  1929. failf(data, "SSL: no alternative certificate subject name matches "
  1930. "target %s '%s'", tname, peer->dispname);
  1931. result = CURLE_PEER_FAILED_VERIFICATION;
  1932. }
  1933. else {
  1934. /* we have to look to the last occurrence of a commonName in the
  1935. distinguished one to get the most significant one. */
  1936. int i = -1;
  1937. unsigned char *cn = NULL;
  1938. int cnlen = 0;
  1939. bool free_cn = FALSE;
  1940. /* The following is done because of a bug in 0.9.6b */
  1941. X509_NAME *name = X509_get_subject_name(server_cert);
  1942. if(name) {
  1943. int j;
  1944. while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0)
  1945. i = j;
  1946. }
  1947. /* we have the name entry and we will now convert this to a string
  1948. that we can use for comparison. Doing this we support BMPstring,
  1949. UTF8, etc. */
  1950. if(i >= 0) {
  1951. ASN1_STRING *tmp =
  1952. X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
  1953. /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
  1954. is already UTF-8 encoded. We check for this case and copy the raw
  1955. string manually to avoid the problem. This code can be made
  1956. conditional in the future when OpenSSL has been fixed. */
  1957. if(tmp) {
  1958. if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
  1959. cnlen = ASN1_STRING_length(tmp);
  1960. cn = (unsigned char *)CURL_UNCONST(ASN1_STRING_get0_data(tmp));
  1961. }
  1962. else { /* not a UTF8 name */
  1963. cnlen = ASN1_STRING_to_UTF8(&cn, tmp);
  1964. free_cn = TRUE;
  1965. }
  1966. if((cnlen <= 0) || !cn)
  1967. result = CURLE_OUT_OF_MEMORY;
  1968. else if((size_t)cnlen != strlen((char *)cn)) {
  1969. /* there was a terminating zero before the end of string, this
  1970. cannot match and we return failure! */
  1971. failf(data, "SSL: illegal cert name field");
  1972. result = CURLE_PEER_FAILED_VERIFICATION;
  1973. }
  1974. }
  1975. }
  1976. if(result)
  1977. /* error already detected, pass through */
  1978. ;
  1979. else if(!cn) {
  1980. failf(data, "SSL: unable to obtain common name from peer certificate");
  1981. result = CURLE_PEER_FAILED_VERIFICATION;
  1982. }
  1983. else if(!Curl_cert_hostcheck((const char *)cn, cnlen,
  1984. peer->hostname, hostlen)) {
  1985. failf(data, "SSL: certificate subject name '%s' does not match "
  1986. "target hostname '%s'", cn, peer->dispname);
  1987. result = CURLE_PEER_FAILED_VERIFICATION;
  1988. }
  1989. else {
  1990. infof(data, " common name: %s (matched)", cn);
  1991. }
  1992. if(free_cn)
  1993. OPENSSL_free(cn);
  1994. }
  1995. return result;
  1996. }
  1997. #ifndef OPENSSL_NO_OCSP
  1998. static CURLcode verifystatus(struct Curl_cfilter *cf,
  1999. struct Curl_easy *data,
  2000. struct ossl_ctx *octx)
  2001. {
  2002. int i, ocsp_status;
  2003. #ifdef HAVE_BORINGSSL_LIKE
  2004. const uint8_t *status;
  2005. #else
  2006. unsigned char *status;
  2007. #endif
  2008. const unsigned char *p;
  2009. CURLcode result = CURLE_OK;
  2010. OCSP_RESPONSE *rsp = NULL;
  2011. OCSP_BASICRESP *br = NULL;
  2012. X509_STORE *st = NULL;
  2013. STACK_OF(X509) *ch = NULL;
  2014. X509 *cert;
  2015. OCSP_CERTID *id = NULL;
  2016. int cert_status, crl_reason;
  2017. ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
  2018. int ret;
  2019. long len;
  2020. (void)cf;
  2021. DEBUGASSERT(octx);
  2022. len = (long)SSL_get_tlsext_status_ocsp_resp(octx->ssl, &status);
  2023. if(!status) {
  2024. failf(data, "No OCSP response received");
  2025. result = CURLE_SSL_INVALIDCERTSTATUS;
  2026. goto end;
  2027. }
  2028. p = status;
  2029. rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
  2030. if(!rsp) {
  2031. failf(data, "Invalid OCSP response");
  2032. result = CURLE_SSL_INVALIDCERTSTATUS;
  2033. goto end;
  2034. }
  2035. ocsp_status = OCSP_response_status(rsp);
  2036. if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
  2037. failf(data, "Invalid OCSP response status: %s (%d)",
  2038. OCSP_response_status_str(ocsp_status), ocsp_status);
  2039. result = CURLE_SSL_INVALIDCERTSTATUS;
  2040. goto end;
  2041. }
  2042. br = OCSP_response_get1_basic(rsp);
  2043. if(!br) {
  2044. failf(data, "Invalid OCSP response");
  2045. result = CURLE_SSL_INVALIDCERTSTATUS;
  2046. goto end;
  2047. }
  2048. ch = SSL_get_peer_cert_chain(octx->ssl);
  2049. if(!ch) {
  2050. failf(data, "Could not get peer certificate chain");
  2051. result = CURLE_SSL_INVALIDCERTSTATUS;
  2052. goto end;
  2053. }
  2054. st = SSL_CTX_get_cert_store(octx->ssl_ctx);
  2055. if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
  2056. failf(data, "OCSP response verification failed");
  2057. result = CURLE_SSL_INVALIDCERTSTATUS;
  2058. goto end;
  2059. }
  2060. /* Compute the certificate's ID */
  2061. cert = SSL_get1_peer_certificate(octx->ssl);
  2062. if(!cert) {
  2063. failf(data, "Error getting peer certificate");
  2064. result = CURLE_SSL_INVALIDCERTSTATUS;
  2065. goto end;
  2066. }
  2067. for(i = 0; i < (int)sk_X509_num(ch); i++) {
  2068. X509 *issuer = sk_X509_value(ch, (ossl_valsize_t)i);
  2069. if(X509_check_issued(issuer, cert) == X509_V_OK) {
  2070. /* Note to analysis tools: using SHA1 here is fine. The `id`
  2071. * generated is used as a hash lookup key, not as a verifier
  2072. * of the OCSP data itself. This all according to RFC 5019. */
  2073. id = OCSP_cert_to_id(EVP_sha1(), cert, issuer);
  2074. break;
  2075. }
  2076. }
  2077. X509_free(cert);
  2078. if(!id) {
  2079. failf(data, "Error computing OCSP ID");
  2080. result = CURLE_SSL_INVALIDCERTSTATUS;
  2081. goto end;
  2082. }
  2083. /* Find the single OCSP response corresponding to the certificate ID */
  2084. ret = OCSP_resp_find_status(br, id, &cert_status, &crl_reason, &rev,
  2085. &thisupd, &nextupd);
  2086. OCSP_CERTID_free(id);
  2087. if(ret != 1) {
  2088. failf(data, "Could not find certificate ID in OCSP response");
  2089. result = CURLE_SSL_INVALIDCERTSTATUS;
  2090. goto end;
  2091. }
  2092. /* Validate the OCSP response issuing and update times.
  2093. * - `thisupd` is the time the OCSP response was issued
  2094. * - `nextupd` is the time the OCSP response should be updated
  2095. * (valid life time assigned by the OCSP responder)
  2096. * - 3rd param: how many seconds of clock skew we allow between
  2097. * our clock and the instance that issued the OCSP response
  2098. * - 4th param: how many seconds in the past `thisupd` may be, with
  2099. * -1 meaning there is no limit. */
  2100. if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
  2101. failf(data, "OCSP response has expired");
  2102. result = CURLE_SSL_INVALIDCERTSTATUS;
  2103. goto end;
  2104. }
  2105. infof(data, "SSL certificate status: %s (%d)",
  2106. OCSP_cert_status_str(cert_status), cert_status);
  2107. switch(cert_status) {
  2108. case V_OCSP_CERTSTATUS_GOOD:
  2109. break;
  2110. case V_OCSP_CERTSTATUS_REVOKED:
  2111. result = CURLE_SSL_INVALIDCERTSTATUS;
  2112. failf(data, "SSL certificate revocation reason: %s (%d)",
  2113. OCSP_crl_reason_str(crl_reason), crl_reason);
  2114. goto end;
  2115. case V_OCSP_CERTSTATUS_UNKNOWN:
  2116. default:
  2117. result = CURLE_SSL_INVALIDCERTSTATUS;
  2118. goto end;
  2119. }
  2120. end:
  2121. if(br)
  2122. OCSP_BASICRESP_free(br);
  2123. OCSP_RESPONSE_free(rsp);
  2124. return result;
  2125. }
  2126. #endif
  2127. static const char *ssl_msg_type(int ssl_ver, int msg)
  2128. {
  2129. #ifdef SSL2_VERSION_MAJOR /* OpenSSL 1.0.2, LibreSSL <=3.9.2 */
  2130. if(ssl_ver == SSL2_VERSION_MAJOR) {
  2131. switch(msg) {
  2132. case SSL2_MT_ERROR:
  2133. return "Error";
  2134. case SSL2_MT_CLIENT_HELLO:
  2135. return "Client hello";
  2136. case SSL2_MT_CLIENT_MASTER_KEY:
  2137. return "Client key";
  2138. case SSL2_MT_CLIENT_FINISHED:
  2139. return "Client finished";
  2140. case SSL2_MT_SERVER_HELLO:
  2141. return "Server hello";
  2142. case SSL2_MT_SERVER_VERIFY:
  2143. return "Server verify";
  2144. case SSL2_MT_SERVER_FINISHED:
  2145. return "Server finished";
  2146. case SSL2_MT_REQUEST_CERTIFICATE:
  2147. return "Request CERT";
  2148. case SSL2_MT_CLIENT_CERTIFICATE:
  2149. return "Client CERT";
  2150. }
  2151. }
  2152. else
  2153. #endif
  2154. if(ssl_ver == SSL3_VERSION_MAJOR) {
  2155. switch(msg) {
  2156. case SSL3_MT_HELLO_REQUEST:
  2157. return "Hello request";
  2158. case SSL3_MT_CLIENT_HELLO:
  2159. return "Client hello";
  2160. case SSL3_MT_SERVER_HELLO:
  2161. return "Server hello";
  2162. #ifdef SSL3_MT_NEWSESSION_TICKET
  2163. case SSL3_MT_NEWSESSION_TICKET:
  2164. return "Newsession Ticket";
  2165. #endif
  2166. case SSL3_MT_CERTIFICATE:
  2167. return "Certificate";
  2168. case SSL3_MT_SERVER_KEY_EXCHANGE:
  2169. return "Server key exchange";
  2170. case SSL3_MT_CLIENT_KEY_EXCHANGE:
  2171. return "Client key exchange";
  2172. case SSL3_MT_CERTIFICATE_REQUEST:
  2173. return "Request CERT";
  2174. case SSL3_MT_SERVER_DONE:
  2175. return "Server finished";
  2176. case SSL3_MT_CERTIFICATE_VERIFY:
  2177. return "CERT verify";
  2178. case SSL3_MT_FINISHED:
  2179. return "Finished";
  2180. #ifdef SSL3_MT_CERTIFICATE_STATUS
  2181. case SSL3_MT_CERTIFICATE_STATUS:
  2182. return "Certificate Status";
  2183. #endif
  2184. #ifdef SSL3_MT_ENCRYPTED_EXTENSIONS
  2185. case SSL3_MT_ENCRYPTED_EXTENSIONS:
  2186. return "Encrypted Extensions";
  2187. #endif
  2188. #ifdef SSL3_MT_SUPPLEMENTAL_DATA
  2189. case SSL3_MT_SUPPLEMENTAL_DATA:
  2190. return "Supplemental data";
  2191. #endif
  2192. #ifdef SSL3_MT_END_OF_EARLY_DATA
  2193. case SSL3_MT_END_OF_EARLY_DATA:
  2194. return "End of early data";
  2195. #endif
  2196. #ifdef SSL3_MT_KEY_UPDATE
  2197. case SSL3_MT_KEY_UPDATE:
  2198. return "Key update";
  2199. #endif
  2200. #ifdef SSL3_MT_NEXT_PROTO
  2201. case SSL3_MT_NEXT_PROTO:
  2202. return "Next protocol";
  2203. #endif
  2204. #ifdef SSL3_MT_MESSAGE_HASH
  2205. case SSL3_MT_MESSAGE_HASH:
  2206. return "Message hash";
  2207. #endif
  2208. }
  2209. }
  2210. return "Unknown";
  2211. }
  2212. static const char *tls_rt_type(int type)
  2213. {
  2214. switch(type) {
  2215. #ifdef SSL3_RT_HEADER
  2216. case SSL3_RT_HEADER:
  2217. return "TLS header";
  2218. #endif
  2219. case SSL3_RT_CHANGE_CIPHER_SPEC:
  2220. return "TLS change cipher";
  2221. case SSL3_RT_ALERT:
  2222. return "TLS alert";
  2223. case SSL3_RT_HANDSHAKE:
  2224. return "TLS handshake";
  2225. case SSL3_RT_APPLICATION_DATA:
  2226. return "TLS app data";
  2227. default:
  2228. return "TLS Unknown";
  2229. }
  2230. }
  2231. /*
  2232. * Our callback from the SSL/TLS layers.
  2233. */
  2234. static void ossl_trace(int direction, int ssl_ver, int content_type,
  2235. const void *buf, size_t len, SSL *ssl,
  2236. void *userp)
  2237. {
  2238. const char *verstr;
  2239. struct Curl_cfilter *cf = userp;
  2240. struct Curl_easy *data = NULL;
  2241. char unknown[32];
  2242. if(!cf)
  2243. return;
  2244. data = CF_DATA_CURRENT(cf);
  2245. if(!data || !data->set.fdebug || (direction && direction != 1))
  2246. return;
  2247. switch(ssl_ver) {
  2248. #ifdef SSL2_VERSION /* removed in recent versions */
  2249. case SSL2_VERSION:
  2250. verstr = "SSLv2";
  2251. break;
  2252. #endif
  2253. #ifdef SSL3_VERSION
  2254. case SSL3_VERSION:
  2255. verstr = "SSLv3";
  2256. break;
  2257. #endif
  2258. case TLS1_VERSION:
  2259. verstr = "TLSv1.0";
  2260. break;
  2261. #ifdef TLS1_1_VERSION
  2262. case TLS1_1_VERSION:
  2263. verstr = "TLSv1.1";
  2264. break;
  2265. #endif
  2266. #ifdef TLS1_2_VERSION
  2267. case TLS1_2_VERSION:
  2268. verstr = "TLSv1.2";
  2269. break;
  2270. #endif
  2271. case TLS1_3_VERSION:
  2272. verstr = "TLSv1.3";
  2273. break;
  2274. default:
  2275. curl_msnprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
  2276. verstr = unknown;
  2277. break;
  2278. }
  2279. /* Log progress for interesting records only (like Handshake or Alert), skip
  2280. * all raw record headers (content_type == SSL3_RT_HEADER or ssl_ver == 0).
  2281. * For TLS 1.3, skip notification of the decrypted inner Content-Type.
  2282. */
  2283. if(ssl_ver
  2284. #ifdef SSL3_RT_HEADER
  2285. && content_type != SSL3_RT_HEADER
  2286. #endif
  2287. #ifdef SSL3_RT_INNER_CONTENT_TYPE
  2288. && content_type != SSL3_RT_INNER_CONTENT_TYPE
  2289. #endif
  2290. ) {
  2291. const char *msg_name, *tls_rt_name;
  2292. char ssl_buf[1024];
  2293. int msg_type, txt_len;
  2294. /* the info given when the version is zero is not that useful for us */
  2295. ssl_ver >>= 8; /* check the upper 8 bits only below */
  2296. /* SSLv2 does not seem to have TLS record-type headers, so OpenSSL
  2297. * always pass-up content-type as 0. But the interesting message-type
  2298. * is at 'buf[0]'.
  2299. */
  2300. if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
  2301. tls_rt_name = tls_rt_type(content_type);
  2302. else
  2303. tls_rt_name = "";
  2304. if(content_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  2305. msg_type = *(const char *)buf;
  2306. msg_name = "Change cipher spec";
  2307. }
  2308. else if(content_type == SSL3_RT_ALERT) {
  2309. msg_type = (((const char *)buf)[0] << 8) + ((const char *)buf)[1];
  2310. msg_name = SSL_alert_desc_string_long(msg_type);
  2311. }
  2312. else {
  2313. msg_type = *(const char *)buf;
  2314. msg_name = ssl_msg_type(ssl_ver, msg_type);
  2315. }
  2316. txt_len = curl_msnprintf(ssl_buf, sizeof(ssl_buf),
  2317. "%s (%s), %s, %s (%d):\n",
  2318. verstr, direction ? "OUT" : "IN",
  2319. tls_rt_name, msg_name, msg_type);
  2320. Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len);
  2321. }
  2322. Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
  2323. CURLINFO_SSL_DATA_IN, (const char *)buf, len);
  2324. (void)ssl;
  2325. }
  2326. static CURLcode
  2327. ossl_set_ssl_version_min_max(struct Curl_cfilter *cf, SSL_CTX *ctx,
  2328. unsigned int ssl_version_min)
  2329. {
  2330. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2331. /* first, TLS min version... */
  2332. long curl_ssl_version_min = (long)ssl_version_min;
  2333. long curl_ssl_version_max;
  2334. /* convert curl min SSL version option to OpenSSL constant */
  2335. #if defined(HAVE_BORINGSSL_LIKE) || defined(LIBRESSL_VERSION_NUMBER)
  2336. uint16_t ossl_ssl_version_min = 0;
  2337. uint16_t ossl_ssl_version_max = 0;
  2338. #else
  2339. long ossl_ssl_version_min = 0;
  2340. long ossl_ssl_version_max = 0;
  2341. #endif
  2342. /* it cannot be default here */
  2343. DEBUGASSERT(curl_ssl_version_min != CURL_SSLVERSION_DEFAULT);
  2344. switch(curl_ssl_version_min) {
  2345. case CURL_SSLVERSION_TLSv1: /* TLS 1.x */
  2346. case CURL_SSLVERSION_TLSv1_0:
  2347. ossl_ssl_version_min = TLS1_VERSION;
  2348. break;
  2349. case CURL_SSLVERSION_TLSv1_1:
  2350. ossl_ssl_version_min = TLS1_1_VERSION;
  2351. break;
  2352. case CURL_SSLVERSION_TLSv1_2:
  2353. ossl_ssl_version_min = TLS1_2_VERSION;
  2354. break;
  2355. case CURL_SSLVERSION_TLSv1_3:
  2356. ossl_ssl_version_min = TLS1_3_VERSION;
  2357. break;
  2358. }
  2359. /* ... then, TLS max version */
  2360. curl_ssl_version_max = (long)conn_config->version_max;
  2361. /* convert curl max SSL version option to OpenSSL constant */
  2362. switch(curl_ssl_version_max) {
  2363. case CURL_SSLVERSION_MAX_TLSv1_0:
  2364. ossl_ssl_version_max = TLS1_VERSION;
  2365. break;
  2366. case CURL_SSLVERSION_MAX_TLSv1_1:
  2367. ossl_ssl_version_max = TLS1_1_VERSION;
  2368. break;
  2369. case CURL_SSLVERSION_MAX_TLSv1_2:
  2370. ossl_ssl_version_max = TLS1_2_VERSION;
  2371. break;
  2372. case CURL_SSLVERSION_MAX_TLSv1_3:
  2373. ossl_ssl_version_max = TLS1_3_VERSION;
  2374. break;
  2375. case CURL_SSLVERSION_MAX_NONE: /* none selected */
  2376. case CURL_SSLVERSION_MAX_DEFAULT: /* max selected */
  2377. default:
  2378. /* SSL_CTX_set_max_proto_version states that: setting the maximum to 0
  2379. will enable protocol versions up to the highest version supported by
  2380. the library */
  2381. ossl_ssl_version_max = 0;
  2382. break;
  2383. }
  2384. if(!SSL_CTX_set_min_proto_version(ctx, ossl_ssl_version_min) ||
  2385. !SSL_CTX_set_max_proto_version(ctx, ossl_ssl_version_max))
  2386. return CURLE_SSL_CONNECT_ERROR;
  2387. return CURLE_OK;
  2388. }
  2389. #ifdef HAVE_BORINGSSL_LIKE
  2390. typedef uint32_t ctx_option_t;
  2391. #elif defined(HAVE_OPENSSL3)
  2392. typedef uint64_t ctx_option_t;
  2393. #elif defined(LIBRESSL_VERSION_NUMBER)
  2394. typedef long ctx_option_t;
  2395. #else
  2396. typedef unsigned long ctx_option_t;
  2397. #endif
  2398. CURLcode Curl_ossl_add_session(struct Curl_cfilter *cf,
  2399. struct Curl_easy *data,
  2400. const char *ssl_peer_key,
  2401. SSL_SESSION *session,
  2402. int ietf_tls_id,
  2403. const char *alpn,
  2404. unsigned char *quic_tp,
  2405. size_t quic_tp_len)
  2406. {
  2407. unsigned char *der_session_buf = NULL;
  2408. unsigned char *qtp_clone = NULL;
  2409. CURLcode result = CURLE_OK;
  2410. if(!cf || !data)
  2411. goto out;
  2412. if(Curl_ssl_scache_use(cf, data)) {
  2413. struct Curl_ssl_session *sc_session = NULL;
  2414. size_t der_session_size;
  2415. unsigned char *der_session_ptr;
  2416. size_t earlydata_max = 0;
  2417. der_session_size = i2d_SSL_SESSION(session, NULL);
  2418. if(der_session_size == 0) {
  2419. result = CURLE_OUT_OF_MEMORY;
  2420. goto out;
  2421. }
  2422. der_session_buf = der_session_ptr = curlx_malloc(der_session_size);
  2423. if(!der_session_buf) {
  2424. result = CURLE_OUT_OF_MEMORY;
  2425. goto out;
  2426. }
  2427. der_session_size = i2d_SSL_SESSION(session, &der_session_ptr);
  2428. if(der_session_size == 0) {
  2429. result = CURLE_OUT_OF_MEMORY;
  2430. goto out;
  2431. }
  2432. #ifdef HAVE_OPENSSL_EARLYDATA
  2433. earlydata_max = SSL_SESSION_get_max_early_data(session);
  2434. #endif
  2435. if(quic_tp && quic_tp_len) {
  2436. qtp_clone = Curl_memdup0((char *)quic_tp, quic_tp_len);
  2437. if(!qtp_clone) {
  2438. result = CURLE_OUT_OF_MEMORY;
  2439. goto out;
  2440. }
  2441. }
  2442. result = Curl_ssl_session_create2(der_session_buf, der_session_size,
  2443. ietf_tls_id, alpn,
  2444. (curl_off_t)time(NULL) +
  2445. SSL_SESSION_get_timeout(session),
  2446. earlydata_max, qtp_clone, quic_tp_len,
  2447. &sc_session);
  2448. der_session_buf = NULL; /* took ownership of sdata */
  2449. if(!result) {
  2450. result = Curl_ssl_scache_put(cf, data, ssl_peer_key, sc_session);
  2451. /* took ownership of `sc_session` */
  2452. }
  2453. }
  2454. out:
  2455. curlx_free(der_session_buf);
  2456. return result;
  2457. }
  2458. /* The "new session" callback must return zero if the session can be removed
  2459. * or non-zero if the session has been put into the session cache.
  2460. */
  2461. static int ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid)
  2462. {
  2463. struct Curl_cfilter *cf = (struct Curl_cfilter *)SSL_get_app_data(ssl);
  2464. if(cf) {
  2465. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  2466. struct ssl_connect_data *connssl = cf->ctx;
  2467. Curl_ossl_add_session(cf, data, connssl->peer.scache_key, ssl_sessionid,
  2468. SSL_version(ssl), connssl->negotiated.alpn,
  2469. NULL, 0);
  2470. }
  2471. return 0;
  2472. }
  2473. static CURLcode load_cacert_from_memory(X509_STORE *store,
  2474. const struct curl_blob *ca_info_blob)
  2475. {
  2476. /* these need to be freed at the end */
  2477. BIO *cbio = NULL;
  2478. STACK_OF(X509_INFO) *inf = NULL;
  2479. /* everything else is just a reference */
  2480. int i, count = 0;
  2481. X509_INFO *itmp = NULL;
  2482. if(ca_info_blob->len > (size_t)INT_MAX)
  2483. return CURLE_SSL_CACERT_BADFILE;
  2484. cbio = BIO_new_mem_buf(ca_info_blob->data, (int)ca_info_blob->len);
  2485. if(!cbio)
  2486. return CURLE_OUT_OF_MEMORY;
  2487. inf = PEM_X509_INFO_read_bio(cbio, NULL, NULL, NULL);
  2488. if(!inf) {
  2489. BIO_free(cbio);
  2490. return CURLE_SSL_CACERT_BADFILE;
  2491. }
  2492. /* add each entry from PEM file to x509_store */
  2493. for(i = 0; i < (int)sk_X509_INFO_num(inf); ++i) {
  2494. itmp = sk_X509_INFO_value(inf, (ossl_valsize_t)i);
  2495. if(itmp->x509) {
  2496. if(X509_STORE_add_cert(store, itmp->x509)) {
  2497. ++count;
  2498. }
  2499. else {
  2500. /* set count to 0 to return an error */
  2501. count = 0;
  2502. break;
  2503. }
  2504. }
  2505. if(itmp->crl) {
  2506. if(X509_STORE_add_crl(store, itmp->crl)) {
  2507. ++count;
  2508. }
  2509. else {
  2510. /* set count to 0 to return an error */
  2511. count = 0;
  2512. break;
  2513. }
  2514. }
  2515. }
  2516. #if defined(__clang__) && __clang_major__ >= 16
  2517. #pragma clang diagnostic push
  2518. #pragma clang diagnostic ignored "-Wcast-function-type-strict"
  2519. #endif
  2520. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  2521. #if defined(__clang__) && __clang_major__ >= 16
  2522. #pragma clang diagnostic pop
  2523. #endif
  2524. BIO_free(cbio);
  2525. /* if we did not end up importing anything, treat that as an error */
  2526. return (count > 0) ? CURLE_OK : CURLE_SSL_CACERT_BADFILE;
  2527. }
  2528. #ifdef USE_WIN32_CRYPTO
  2529. static CURLcode ossl_win_load_store(struct Curl_easy *data,
  2530. const char *win_store,
  2531. X509_STORE *store,
  2532. bool *padded)
  2533. {
  2534. CURLcode result = CURLE_OK;
  2535. HCERTSTORE hStore;
  2536. *padded = FALSE;
  2537. hStore = CertOpenSystemStoreA(0, win_store);
  2538. if(hStore) {
  2539. PCCERT_CONTEXT pContext = NULL;
  2540. /* The array of enhanced key usage OIDs will vary per certificate and
  2541. is declared outside of the loop so that rather than malloc/free each
  2542. iteration we can grow it with realloc, when necessary. */
  2543. CERT_ENHKEY_USAGE *enhkey_usage = NULL;
  2544. DWORD enhkey_usage_size = 0;
  2545. /* This loop makes a best effort to import all valid certificates from
  2546. the MS root store. If a certificate cannot be imported it is
  2547. skipped. 'result' is used to store only hard-fail conditions (such
  2548. as out of memory) that cause an early break. */
  2549. result = CURLE_OK;
  2550. for(;;) {
  2551. X509 *x509;
  2552. FILETIME now;
  2553. BYTE key_usage[2];
  2554. DWORD req_size;
  2555. const unsigned char *encoded_cert;
  2556. pContext = CertEnumCertificatesInStore(hStore, pContext);
  2557. if(!pContext)
  2558. break;
  2559. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  2560. else {
  2561. char cert_name[256];
  2562. if(!CertGetNameStringA(pContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0,
  2563. NULL, cert_name, sizeof(cert_name)))
  2564. infof(data, "SSL: unknown cert name");
  2565. else
  2566. infof(data, "SSL: Checking cert \"%s\"", cert_name);
  2567. }
  2568. #endif
  2569. encoded_cert = (const unsigned char *)pContext->pbCertEncoded;
  2570. if(!encoded_cert)
  2571. continue;
  2572. GetSystemTimeAsFileTime(&now);
  2573. if(CompareFileTime(&pContext->pCertInfo->NotBefore, &now) > 0 ||
  2574. CompareFileTime(&now, &pContext->pCertInfo->NotAfter) > 0)
  2575. continue;
  2576. /* If key usage exists check for signing attribute */
  2577. if(CertGetIntendedKeyUsage(pContext->dwCertEncodingType,
  2578. pContext->pCertInfo,
  2579. key_usage, sizeof(key_usage))) {
  2580. if(!(key_usage[0] & CERT_KEY_CERT_SIGN_KEY_USAGE))
  2581. continue;
  2582. }
  2583. else if(GetLastError())
  2584. continue;
  2585. /* If enhanced key usage exists check for server auth attribute.
  2586. *
  2587. * Note "In a Microsoft environment, a certificate might also have
  2588. * EKU extended properties that specify valid uses for the
  2589. * certificate." The call below checks both, and behavior varies
  2590. * depending on what is found. For more details see
  2591. * CertGetEnhancedKeyUsage doc.
  2592. */
  2593. if(CertGetEnhancedKeyUsage(pContext, 0, NULL, &req_size)) {
  2594. if(req_size && req_size > enhkey_usage_size) {
  2595. void *tmp = curlx_realloc(enhkey_usage, req_size);
  2596. if(!tmp) {
  2597. failf(data, "SSL: Out of memory allocating for OID list");
  2598. result = CURLE_OUT_OF_MEMORY;
  2599. break;
  2600. }
  2601. enhkey_usage = (CERT_ENHKEY_USAGE *)tmp;
  2602. enhkey_usage_size = req_size;
  2603. }
  2604. if(CertGetEnhancedKeyUsage(pContext, 0, enhkey_usage, &req_size)) {
  2605. if(!enhkey_usage->cUsageIdentifier) {
  2606. /* "If GetLastError returns CRYPT_E_NOT_FOUND, the certificate
  2607. is good for all uses. If it returns zero, the certificate
  2608. has no valid uses." */
  2609. if((HRESULT)GetLastError() != CRYPT_E_NOT_FOUND)
  2610. continue;
  2611. }
  2612. else {
  2613. DWORD i;
  2614. bool found = FALSE;
  2615. for(i = 0; i < enhkey_usage->cUsageIdentifier; ++i) {
  2616. if(!strcmp("1.3.6.1.5.5.7.3.1" /* OID server auth */,
  2617. enhkey_usage->rgpszUsageIdentifier[i])) {
  2618. found = TRUE;
  2619. break;
  2620. }
  2621. }
  2622. if(!found)
  2623. continue;
  2624. }
  2625. }
  2626. else
  2627. continue;
  2628. }
  2629. else
  2630. continue;
  2631. x509 = d2i_X509(NULL, &encoded_cert, (long)pContext->cbCertEncoded);
  2632. if(!x509)
  2633. continue;
  2634. /* Try to import the certificate. This may fail for legitimate reasons
  2635. such as duplicate certificate, which is allowed by MS but not
  2636. OpenSSL. */
  2637. if(X509_STORE_add_cert(store, x509) == 1) {
  2638. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  2639. infof(data, "SSL: Imported cert");
  2640. #endif
  2641. *padded = TRUE;
  2642. }
  2643. X509_free(x509);
  2644. }
  2645. curlx_free(enhkey_usage);
  2646. CertFreeCertificateContext(pContext);
  2647. CertCloseStore(hStore, 0);
  2648. if(result)
  2649. return result;
  2650. }
  2651. return result;
  2652. }
  2653. static CURLcode ossl_windows_load_anchors(struct Curl_cfilter *cf,
  2654. struct Curl_easy *data,
  2655. X509_STORE *store,
  2656. bool *padded)
  2657. {
  2658. /* Import certificates from the Windows root certificate store if
  2659. requested.
  2660. https://stackoverflow.com/questions/9507184/
  2661. https://github.com/d3x0r/SACK/blob/master/src/netlib/ssl_layer.c#L1037
  2662. https://datatracker.ietf.org/doc/html/rfc5280 */
  2663. const char *win_stores[] = {
  2664. "ROOT", /* Trusted Root Certification Authorities */
  2665. "CA" /* Intermediate Certification Authorities */
  2666. };
  2667. size_t i;
  2668. CURLcode result = CURLE_OK;
  2669. *padded = FALSE;
  2670. for(i = 0; i < CURL_ARRAYSIZE(win_stores); ++i) {
  2671. bool store_added = FALSE;
  2672. result = ossl_win_load_store(data, win_stores[i], store, &store_added);
  2673. if(result)
  2674. return result;
  2675. if(store_added) {
  2676. CURL_TRC_CF(data, cf, "added trust anchors from Windows %s store",
  2677. win_stores[i]);
  2678. *padded = TRUE;
  2679. }
  2680. else
  2681. infof(data, "error importing Windows %s store, continuing anyway",
  2682. win_stores[i]);
  2683. }
  2684. return result;
  2685. }
  2686. #endif /* USE_WIN32_CRYPTO */
  2687. static CURLcode ossl_load_trust_anchors(struct Curl_cfilter *cf,
  2688. struct Curl_easy *data,
  2689. struct ossl_ctx *octx,
  2690. X509_STORE *store)
  2691. {
  2692. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2693. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  2694. CURLcode result = CURLE_OK;
  2695. const char * const ssl_cafile =
  2696. /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
  2697. (conn_config->ca_info_blob ? NULL : conn_config->CAfile);
  2698. const char * const ssl_capath = conn_config->CApath;
  2699. bool have_native_check = FALSE;
  2700. octx->store_is_empty = TRUE;
  2701. if(ssl_config->native_ca_store) {
  2702. #ifdef USE_WIN32_CRYPTO
  2703. bool added = FALSE;
  2704. result = ossl_windows_load_anchors(cf, data, store, &added);
  2705. if(result)
  2706. return result;
  2707. if(added) {
  2708. infof(data, " Native: Windows System Stores ROOT+CA");
  2709. octx->store_is_empty = FALSE;
  2710. }
  2711. #elif defined(USE_APPLE_SECTRUST)
  2712. infof(data, " Native: Apple SecTrust");
  2713. have_native_check = TRUE;
  2714. #endif
  2715. }
  2716. if(conn_config->ca_info_blob) {
  2717. result = load_cacert_from_memory(store, conn_config->ca_info_blob);
  2718. if(result) {
  2719. failf(data, "error adding trust anchors from certificate blob: %d",
  2720. result);
  2721. return result;
  2722. }
  2723. infof(data, " CA Blob from configuration");
  2724. octx->store_is_empty = FALSE;
  2725. }
  2726. if(ssl_cafile || ssl_capath) {
  2727. #ifdef HAVE_OPENSSL3
  2728. /* OpenSSL 3.0.0 has deprecated SSL_CTX_load_verify_locations */
  2729. if(ssl_cafile) {
  2730. if(!X509_STORE_load_file(store, ssl_cafile)) {
  2731. if(octx->store_is_empty && !have_native_check) {
  2732. /* Fail if we insist on successfully verifying the server. */
  2733. failf(data, "error adding trust anchors from file: %s", ssl_cafile);
  2734. return CURLE_SSL_CACERT_BADFILE;
  2735. }
  2736. else
  2737. infof(data, "error setting certificate file, continuing anyway");
  2738. }
  2739. infof(data, " CAfile: %s", ssl_cafile);
  2740. octx->store_is_empty = FALSE;
  2741. }
  2742. if(ssl_capath) {
  2743. if(!X509_STORE_load_path(store, ssl_capath)) {
  2744. if(octx->store_is_empty && !have_native_check) {
  2745. /* Fail if we insist on successfully verifying the server. */
  2746. failf(data, "error adding trust anchors from path: %s", ssl_capath);
  2747. return CURLE_SSL_CACERT_BADFILE;
  2748. }
  2749. else
  2750. infof(data, "error setting certificate path, continuing anyway");
  2751. }
  2752. infof(data, " CApath: %s", ssl_capath);
  2753. octx->store_is_empty = FALSE;
  2754. }
  2755. #else
  2756. /* tell OpenSSL where to find CA certificates that are used to verify the
  2757. server's certificate. */
  2758. if(!X509_STORE_load_locations(store, ssl_cafile, ssl_capath)) {
  2759. if(octx->store_is_empty && !have_native_check) {
  2760. /* Fail if we insist on successfully verifying the server. */
  2761. failf(data, "error adding trust anchors from locations:"
  2762. " CAfile: %s CApath: %s",
  2763. ssl_cafile ? ssl_cafile : "none",
  2764. ssl_capath ? ssl_capath : "none");
  2765. return CURLE_SSL_CACERT_BADFILE;
  2766. }
  2767. else {
  2768. infof(data, "error setting certificate verify locations,"
  2769. " continuing anyway");
  2770. }
  2771. }
  2772. if(ssl_cafile)
  2773. infof(data, " CAfile: %s", ssl_cafile);
  2774. if(ssl_capath)
  2775. infof(data, " CApath: %s", ssl_capath);
  2776. octx->store_is_empty = FALSE;
  2777. #endif
  2778. }
  2779. #ifdef CURL_CA_FALLBACK
  2780. if(octx->store_is_empty) {
  2781. /* verifying the peer without any CA certificates will not
  2782. work so use OpenSSL's built-in default as fallback */
  2783. X509_STORE_set_default_paths(store);
  2784. infof(data, " OpenSSL default paths (fallback)");
  2785. octx->store_is_empty = FALSE;
  2786. }
  2787. #endif
  2788. if(octx->store_is_empty && !have_native_check)
  2789. infof(data, " no trust anchors configured");
  2790. return result;
  2791. }
  2792. static CURLcode ossl_populate_x509_store(struct Curl_cfilter *cf,
  2793. struct Curl_easy *data,
  2794. struct ossl_ctx *octx,
  2795. X509_STORE *store)
  2796. {
  2797. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2798. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  2799. CURLcode result = CURLE_OK;
  2800. X509_LOOKUP *lookup = NULL;
  2801. const char * const ssl_crlfile = ssl_config->primary.CRLfile;
  2802. unsigned long x509flags = 0;
  2803. CURL_TRC_CF(data, cf, "configuring OpenSSL's x509 trust store");
  2804. if(!store)
  2805. return CURLE_OUT_OF_MEMORY;
  2806. if(!conn_config->verifypeer) {
  2807. infof(data, "SSL Trust: peer verification disabled");
  2808. return CURLE_OK;
  2809. }
  2810. infof(data, "SSL Trust Anchors:");
  2811. result = ossl_load_trust_anchors(cf, data, octx, store);
  2812. if(result)
  2813. return result;
  2814. /* Does not make sense to load a CRL file without peer verification */
  2815. if(ssl_crlfile) {
  2816. /* tell OpenSSL where to find CRL file that is used to check certificate
  2817. * revocation */
  2818. lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
  2819. if(!lookup ||
  2820. (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
  2821. failf(data, "error loading CRL file: %s", ssl_crlfile);
  2822. return CURLE_SSL_CRL_BADFILE;
  2823. }
  2824. x509flags = X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL;
  2825. infof(data, " CRLfile: %s", ssl_crlfile);
  2826. }
  2827. /* Try building a chain using issuers in the trusted store first to avoid
  2828. problems with server-sent legacy intermediates. Newer versions of
  2829. OpenSSL do alternate chain checking by default but we do not know how to
  2830. determine that in a reliable manner.
  2831. https://web.archive.org/web/20190422050538/rt.openssl.org/Ticket/Display.html?id=3621
  2832. */
  2833. x509flags |= X509_V_FLAG_TRUSTED_FIRST;
  2834. if(!ssl_config->no_partialchain && !ssl_crlfile) {
  2835. /* Have intermediate certificates in the trust store be treated as
  2836. trust-anchors, in the same way as self-signed root CA certificates are.
  2837. This allows users to verify servers using the intermediate cert only,
  2838. instead of needing the whole chain.
  2839. Due to OpenSSL bug https://github.com/openssl/openssl/issues/5081 we
  2840. cannot do partial chains with a CRL check.
  2841. */
  2842. x509flags |= X509_V_FLAG_PARTIAL_CHAIN;
  2843. }
  2844. (void)X509_STORE_set_flags(store, x509flags);
  2845. return result;
  2846. }
  2847. /* key to use at `multi->proto_hash` */
  2848. #define MPROTO_OSSL_X509_KEY "tls:ossl:x509:share"
  2849. struct ossl_x509_share {
  2850. char *CAfile; /* CAfile path used to generate X509 store */
  2851. X509_STORE *store; /* cached X509 store or NULL if none */
  2852. struct curltime time; /* when the cached store was created */
  2853. BIT(store_is_empty); /* no certs/paths/blobs are in the store */
  2854. BIT(no_partialchain); /* keep partial chain state */
  2855. };
  2856. static void oss_x509_share_free(void *key, size_t key_len, void *p)
  2857. {
  2858. struct ossl_x509_share *share = p;
  2859. DEBUGASSERT(key_len == (sizeof(MPROTO_OSSL_X509_KEY) - 1));
  2860. DEBUGASSERT(!memcmp(MPROTO_OSSL_X509_KEY, key, key_len));
  2861. (void)key;
  2862. (void)key_len;
  2863. if(share->store) {
  2864. X509_STORE_free(share->store);
  2865. }
  2866. curlx_free(share->CAfile);
  2867. curlx_free(share);
  2868. }
  2869. static bool ossl_cached_x509_store_expired(struct Curl_easy *data,
  2870. const struct ossl_x509_share *mb)
  2871. {
  2872. const struct ssl_general_config *cfg = &data->set.general_ssl;
  2873. if(cfg->ca_cache_timeout < 0)
  2874. return FALSE;
  2875. else {
  2876. timediff_t elapsed_ms = curlx_ptimediff_ms(Curl_pgrs_now(data), &mb->time);
  2877. timediff_t timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000;
  2878. return elapsed_ms >= timeout_ms;
  2879. }
  2880. }
  2881. static bool ossl_cached_x509_store_different(struct Curl_cfilter *cf,
  2882. const struct Curl_easy *data,
  2883. const struct ossl_x509_share *mb)
  2884. {
  2885. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2886. struct ssl_config_data *ssl_config =
  2887. Curl_ssl_cf_get_config(cf, CURL_UNCONST(data));
  2888. if(mb->no_partialchain != ssl_config->no_partialchain)
  2889. return TRUE;
  2890. if(!mb->CAfile || !conn_config->CAfile)
  2891. return mb->CAfile != conn_config->CAfile;
  2892. return strcmp(mb->CAfile, conn_config->CAfile);
  2893. }
  2894. static X509_STORE *ossl_get_cached_x509_store(struct Curl_cfilter *cf,
  2895. struct Curl_easy *data,
  2896. bool *pempty)
  2897. {
  2898. struct Curl_multi *multi = data->multi;
  2899. struct ossl_x509_share *share;
  2900. X509_STORE *store = NULL;
  2901. DEBUGASSERT(multi);
  2902. *pempty = TRUE;
  2903. share = multi ? Curl_hash_pick(&multi->proto_hash,
  2904. CURL_UNCONST(MPROTO_OSSL_X509_KEY),
  2905. sizeof(MPROTO_OSSL_X509_KEY) - 1) : NULL;
  2906. if(share && share->store &&
  2907. !ossl_cached_x509_store_expired(data, share) &&
  2908. !ossl_cached_x509_store_different(cf, data, share)) {
  2909. store = share->store;
  2910. *pempty = share->store_is_empty;
  2911. }
  2912. return store;
  2913. }
  2914. static void ossl_set_cached_x509_store(struct Curl_cfilter *cf,
  2915. struct Curl_easy *data,
  2916. X509_STORE *store,
  2917. bool is_empty)
  2918. {
  2919. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2920. struct Curl_multi *multi = data->multi;
  2921. struct ossl_x509_share *share;
  2922. DEBUGASSERT(multi);
  2923. if(!multi)
  2924. return;
  2925. share = Curl_hash_pick(&multi->proto_hash,
  2926. CURL_UNCONST(MPROTO_OSSL_X509_KEY),
  2927. sizeof(MPROTO_OSSL_X509_KEY) - 1);
  2928. if(!share) {
  2929. share = curlx_calloc(1, sizeof(*share));
  2930. if(!share)
  2931. return;
  2932. if(!Curl_hash_add2(&multi->proto_hash,
  2933. CURL_UNCONST(MPROTO_OSSL_X509_KEY),
  2934. sizeof(MPROTO_OSSL_X509_KEY) - 1,
  2935. share, oss_x509_share_free)) {
  2936. curlx_free(share);
  2937. return;
  2938. }
  2939. }
  2940. if(X509_STORE_up_ref(store)) {
  2941. char *CAfile = NULL;
  2942. struct ssl_config_data *ssl_config =
  2943. Curl_ssl_cf_get_config(cf, CURL_UNCONST(data));
  2944. if(conn_config->CAfile) {
  2945. CAfile = curlx_strdup(conn_config->CAfile);
  2946. if(!CAfile) {
  2947. X509_STORE_free(store);
  2948. return;
  2949. }
  2950. }
  2951. if(share->store) {
  2952. X509_STORE_free(share->store);
  2953. curlx_free(share->CAfile);
  2954. }
  2955. share->time = *Curl_pgrs_now(data);
  2956. share->store = store;
  2957. share->store_is_empty = is_empty;
  2958. share->CAfile = CAfile;
  2959. share->no_partialchain = ssl_config->no_partialchain;
  2960. }
  2961. }
  2962. CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf,
  2963. struct Curl_easy *data,
  2964. struct ossl_ctx *octx)
  2965. {
  2966. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2967. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  2968. CURLcode result = CURLE_OK;
  2969. X509_STORE *cached_store;
  2970. bool cache_criteria_met, is_empty;
  2971. /* Consider the X509 store cacheable if it comes exclusively from a CAfile,
  2972. or no source is provided and we are falling back to OpenSSL's built-in
  2973. default. */
  2974. cache_criteria_met = (data->set.general_ssl.ca_cache_timeout != 0) &&
  2975. conn_config->verifypeer &&
  2976. !conn_config->CApath &&
  2977. !conn_config->ca_info_blob &&
  2978. !ssl_config->primary.CRLfile &&
  2979. !ssl_config->native_ca_store;
  2980. ERR_set_mark();
  2981. cached_store = ossl_get_cached_x509_store(cf, data, &is_empty);
  2982. if(cached_store && cache_criteria_met && X509_STORE_up_ref(cached_store)) {
  2983. SSL_CTX_set_cert_store(octx->ssl_ctx, cached_store);
  2984. octx->store_is_empty = is_empty;
  2985. }
  2986. else {
  2987. X509_STORE *store = SSL_CTX_get_cert_store(octx->ssl_ctx);
  2988. result = ossl_populate_x509_store(cf, data, octx, store);
  2989. if(result == CURLE_OK && cache_criteria_met) {
  2990. ossl_set_cached_x509_store(cf, data, store, octx->store_is_empty);
  2991. }
  2992. }
  2993. ERR_pop_to_mark();
  2994. return result;
  2995. }
  2996. static CURLcode
  2997. ossl_init_session_and_alpns(struct ossl_ctx *octx,
  2998. struct Curl_cfilter *cf,
  2999. struct Curl_easy *data,
  3000. struct ssl_peer *peer,
  3001. const struct alpn_spec *alpns_requested,
  3002. Curl_ossl_init_session_reuse_cb *sess_reuse_cb)
  3003. {
  3004. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  3005. struct ssl_primary_config *conn_cfg = Curl_ssl_cf_get_primary_config(cf);
  3006. struct alpn_spec alpns;
  3007. char error_buffer[256];
  3008. CURLcode result;
  3009. Curl_alpn_copy(&alpns, alpns_requested);
  3010. octx->reused_session = FALSE;
  3011. if(Curl_ssl_scache_use(cf, data) && !conn_cfg->verifystatus) {
  3012. struct Curl_ssl_session *scs = NULL;
  3013. result = Curl_ssl_scache_take(cf, data, peer->scache_key, &scs);
  3014. if(!result && scs && scs->sdata && scs->sdata_len) {
  3015. const unsigned char *der_sessionid = scs->sdata;
  3016. size_t der_sessionid_size = scs->sdata_len;
  3017. SSL_SESSION *ssl_session = NULL;
  3018. /* If OpenSSL does not accept the session from the cache, this
  3019. * is not an error. We just continue without it. */
  3020. ssl_session = d2i_SSL_SESSION(NULL, &der_sessionid,
  3021. (long)der_sessionid_size);
  3022. if(ssl_session) {
  3023. if(!SSL_set_session(octx->ssl, ssl_session)) {
  3024. infof(data, "SSL: SSL_set_session not accepted, "
  3025. "continuing without: %s",
  3026. ossl_strerror(ERR_get_error(), error_buffer,
  3027. sizeof(error_buffer)));
  3028. }
  3029. else {
  3030. infof(data, "SSL reusing session with ALPN '%s'",
  3031. scs->alpn ? scs->alpn : "-");
  3032. octx->reused_session = TRUE;
  3033. #ifdef HAVE_OPENSSL_EARLYDATA
  3034. if(ssl_config->earlydata && scs->alpn &&
  3035. SSL_SESSION_get_max_early_data(ssl_session) &&
  3036. !cf->conn->connect_only &&
  3037. (SSL_version(octx->ssl) == TLS1_3_VERSION)) {
  3038. bool do_early_data = FALSE;
  3039. if(sess_reuse_cb) {
  3040. result = sess_reuse_cb(cf, data, &alpns, scs, &do_early_data);
  3041. if(result) {
  3042. SSL_SESSION_free(ssl_session);
  3043. return result;
  3044. }
  3045. }
  3046. if(do_early_data) {
  3047. /* We only try the ALPN protocol the session used before,
  3048. * otherwise we might send early data for the wrong protocol */
  3049. Curl_alpn_restrict_to(&alpns, scs->alpn);
  3050. }
  3051. }
  3052. #else
  3053. (void)ssl_config;
  3054. (void)sess_reuse_cb;
  3055. #endif
  3056. }
  3057. SSL_SESSION_free(ssl_session);
  3058. }
  3059. else {
  3060. infof(data, "SSL session not accepted by OpenSSL, continuing without");
  3061. }
  3062. }
  3063. Curl_ssl_scache_return(cf, data, peer->scache_key, scs);
  3064. }
  3065. if(alpns.count) {
  3066. struct alpn_proto_buf proto;
  3067. memset(&proto, 0, sizeof(proto));
  3068. result = Curl_alpn_to_proto_buf(&proto, &alpns);
  3069. if(result) {
  3070. failf(data, "Error determining ALPN");
  3071. return CURLE_SSL_CONNECT_ERROR;
  3072. }
  3073. if(SSL_set_alpn_protos(octx->ssl, proto.data, (int)proto.len)) {
  3074. failf(data, "Error setting ALPN");
  3075. return CURLE_SSL_CONNECT_ERROR;
  3076. }
  3077. }
  3078. return CURLE_OK;
  3079. }
  3080. #ifdef HAVE_SSL_SET1_ECH_CONFIG_LIST
  3081. static CURLcode ossl_init_ech(struct ossl_ctx *octx,
  3082. struct Curl_cfilter *cf,
  3083. struct Curl_easy *data,
  3084. struct ssl_peer *peer)
  3085. {
  3086. unsigned char *ech_config = NULL;
  3087. size_t ech_config_len = 0;
  3088. char *outername = data->set.str[STRING_ECH_PUBLIC];
  3089. int trying_ech_now = 0;
  3090. CURLcode result;
  3091. if(!ECH_ENABLED(data))
  3092. return CURLE_OK;
  3093. if(data->set.tls_ech & CURLECH_GREASE) {
  3094. infof(data, "ECH: will GREASE ClientHello");
  3095. # ifdef HAVE_BORINGSSL_LIKE
  3096. SSL_set_enable_ech_grease(octx->ssl, 1);
  3097. # else
  3098. SSL_set_options(octx->ssl, SSL_OP_ECH_GREASE);
  3099. # endif
  3100. }
  3101. else if(data->set.tls_ech & CURLECH_CLA_CFG) {
  3102. # ifdef HAVE_BORINGSSL_LIKE
  3103. /* have to do base64 decode here for BoringSSL */
  3104. const char *b64 = data->set.str[STRING_ECH_CONFIG];
  3105. if(!b64) {
  3106. infof(data, "ECH: ECHConfig from command line empty");
  3107. return CURLE_SSL_CONNECT_ERROR;
  3108. }
  3109. ech_config_len = 2 * strlen(b64);
  3110. result = curlx_base64_decode(b64, &ech_config, &ech_config_len);
  3111. if(result || !ech_config) {
  3112. infof(data, "ECH: cannot base64 decode ECHConfig from command line");
  3113. if(data->set.tls_ech & CURLECH_HARD)
  3114. return result;
  3115. }
  3116. if(SSL_set1_ech_config_list(octx->ssl, ech_config, ech_config_len) != 1) {
  3117. infof(data, "ECH: SSL_ECH_set1_ech_config_list failed");
  3118. if(data->set.tls_ech & CURLECH_HARD) {
  3119. curlx_free(ech_config);
  3120. return CURLE_SSL_CONNECT_ERROR;
  3121. }
  3122. }
  3123. curlx_free(ech_config);
  3124. trying_ech_now = 1;
  3125. # else
  3126. ech_config = (unsigned char *)data->set.str[STRING_ECH_CONFIG];
  3127. if(!ech_config) {
  3128. infof(data, "ECH: ECHConfig from command line empty");
  3129. return CURLE_SSL_CONNECT_ERROR;
  3130. }
  3131. ech_config_len = strlen(data->set.str[STRING_ECH_CONFIG]);
  3132. if(SSL_set1_ech_config_list(octx->ssl, ech_config, ech_config_len) != 1) {
  3133. infof(data, "ECH: SSL_ECH_set1_ech_config_list failed");
  3134. if(data->set.tls_ech & CURLECH_HARD)
  3135. return CURLE_SSL_CONNECT_ERROR;
  3136. }
  3137. else
  3138. trying_ech_now = 1;
  3139. # endif
  3140. infof(data, "ECH: ECHConfig from command line");
  3141. }
  3142. else {
  3143. struct Curl_dns_entry *dns = NULL;
  3144. if(peer->hostname)
  3145. dns = Curl_dnscache_get(data, peer->hostname, peer->port,
  3146. cf->conn->ip_version);
  3147. if(!dns) {
  3148. infof(data, "ECH: requested but no DNS info available");
  3149. if(data->set.tls_ech & CURLECH_HARD)
  3150. return CURLE_SSL_CONNECT_ERROR;
  3151. }
  3152. else {
  3153. struct Curl_https_rrinfo *rinfo = NULL;
  3154. rinfo = dns->hinfo;
  3155. if(rinfo && rinfo->echconfiglist) {
  3156. unsigned char *ecl = rinfo->echconfiglist;
  3157. size_t elen = rinfo->echconfiglist_len;
  3158. infof(data, "ECH: ECHConfig from DoH HTTPS RR");
  3159. if(SSL_set1_ech_config_list(octx->ssl, ecl, elen) != 1) {
  3160. infof(data, "ECH: SSL_set1_ech_config_list failed");
  3161. if(data->set.tls_ech & CURLECH_HARD)
  3162. return CURLE_SSL_CONNECT_ERROR;
  3163. }
  3164. else {
  3165. trying_ech_now = 1;
  3166. infof(data, "ECH: imported ECHConfigList of length %zu", elen);
  3167. }
  3168. }
  3169. else {
  3170. infof(data, "ECH: requested but no ECHConfig available");
  3171. if(data->set.tls_ech & CURLECH_HARD)
  3172. return CURLE_SSL_CONNECT_ERROR;
  3173. }
  3174. Curl_resolv_unlink(data, &dns);
  3175. }
  3176. }
  3177. # ifdef HAVE_BORINGSSL_LIKE
  3178. if(trying_ech_now && outername) {
  3179. infof(data, "ECH: setting public_name not supported with BoringSSL");
  3180. return CURLE_SSL_CONNECT_ERROR;
  3181. }
  3182. # else
  3183. if(trying_ech_now && outername) {
  3184. infof(data, "ECH: inner: '%s', outer: '%s'",
  3185. peer->hostname ? peer->hostname : "NULL", outername);
  3186. result = SSL_ech_set1_server_names(octx->ssl,
  3187. peer->hostname, outername,
  3188. 0 /* do send outer */);
  3189. if(result != 1) {
  3190. infof(data, "ECH: rv failed to set server name(s) %d [ERROR]", result);
  3191. return CURLE_SSL_CONNECT_ERROR;
  3192. }
  3193. }
  3194. # endif /* HAVE_BORINGSSL_LIKE */
  3195. if(trying_ech_now &&
  3196. SSL_set_min_proto_version(octx->ssl, TLS1_3_VERSION) != 1) {
  3197. infof(data, "ECH: cannot force TLSv1.3 [ERROR]");
  3198. return CURLE_SSL_CONNECT_ERROR;
  3199. }
  3200. return CURLE_OK;
  3201. }
  3202. #endif /* HAVE_SSL_SET1_ECH_CONFIG_LIST */
  3203. static CURLcode ossl_init_ssl(struct ossl_ctx *octx,
  3204. struct Curl_cfilter *cf,
  3205. struct Curl_easy *data,
  3206. struct ssl_peer *peer,
  3207. const struct alpn_spec *alpns_requested,
  3208. void *ssl_user_data,
  3209. Curl_ossl_init_session_reuse_cb *sess_reuse_cb)
  3210. {
  3211. /* Let's make an SSL structure */
  3212. if(octx->ssl)
  3213. SSL_free(octx->ssl);
  3214. octx->ssl = SSL_new(octx->ssl_ctx);
  3215. if(!octx->ssl) {
  3216. failf(data, "SSL: could not create a context (handle)");
  3217. return CURLE_OUT_OF_MEMORY;
  3218. }
  3219. SSL_set_app_data(octx->ssl, ssl_user_data);
  3220. #ifndef OPENSSL_NO_OCSP
  3221. if(Curl_ssl_cf_get_primary_config(cf)->verifystatus)
  3222. SSL_set_tlsext_status_type(octx->ssl, TLSEXT_STATUSTYPE_ocsp);
  3223. #endif
  3224. SSL_set_connect_state(octx->ssl);
  3225. if(peer->sni) {
  3226. if(!SSL_set_tlsext_host_name(octx->ssl, peer->sni)) {
  3227. failf(data, "Failed set SNI");
  3228. return CURLE_SSL_CONNECT_ERROR;
  3229. }
  3230. }
  3231. #ifdef HAVE_SSL_SET1_ECH_CONFIG_LIST
  3232. {
  3233. CURLcode result = ossl_init_ech(octx, cf, data, peer);
  3234. if(result)
  3235. return result;
  3236. }
  3237. #endif /* HAVE_SSL_SET1_ECH_CONFIG_LIST */
  3238. return ossl_init_session_and_alpns(octx, cf, data, peer,
  3239. alpns_requested, sess_reuse_cb);
  3240. }
  3241. static CURLcode ossl_init_method(struct Curl_cfilter *cf,
  3242. struct Curl_easy *data,
  3243. struct ssl_peer *peer,
  3244. const SSL_METHOD **pmethod,
  3245. unsigned int *pssl_version_min)
  3246. {
  3247. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  3248. *pmethod = NULL;
  3249. *pssl_version_min = conn_config->version;
  3250. switch(peer->transport) {
  3251. case TRNSPRT_TCP:
  3252. /* check to see if we have been told to use an explicit SSL/TLS version */
  3253. switch(*pssl_version_min) {
  3254. case CURL_SSLVERSION_DEFAULT:
  3255. case CURL_SSLVERSION_TLSv1:
  3256. case CURL_SSLVERSION_TLSv1_0:
  3257. case CURL_SSLVERSION_TLSv1_1:
  3258. case CURL_SSLVERSION_TLSv1_2:
  3259. case CURL_SSLVERSION_TLSv1_3:
  3260. /* it will be handled later with the context options */
  3261. *pmethod = TLS_client_method();
  3262. break;
  3263. case CURL_SSLVERSION_SSLv2:
  3264. failf(data, "No SSLv2 support");
  3265. return CURLE_NOT_BUILT_IN;
  3266. case CURL_SSLVERSION_SSLv3:
  3267. failf(data, "No SSLv3 support");
  3268. return CURLE_NOT_BUILT_IN;
  3269. default:
  3270. failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
  3271. return CURLE_SSL_CONNECT_ERROR;
  3272. }
  3273. break;
  3274. case TRNSPRT_QUIC:
  3275. *pssl_version_min = CURL_SSLVERSION_TLSv1_3;
  3276. if(conn_config->version_max &&
  3277. (conn_config->version_max != CURL_SSLVERSION_MAX_DEFAULT) &&
  3278. (conn_config->version_max != CURL_SSLVERSION_MAX_TLSv1_3)) {
  3279. failf(data, "QUIC needs at least TLS version 1.3");
  3280. return CURLE_SSL_CONNECT_ERROR;
  3281. }
  3282. #ifdef USE_OPENSSL_QUIC
  3283. *pmethod = OSSL_QUIC_client_method();
  3284. #else
  3285. *pmethod = TLS_method();
  3286. #endif
  3287. break;
  3288. default:
  3289. failf(data, "unsupported transport %d in SSL init", peer->transport);
  3290. return CURLE_SSL_CONNECT_ERROR;
  3291. }
  3292. return *pmethod ? CURLE_OK : CURLE_SSL_CONNECT_ERROR;
  3293. }
  3294. CURLcode Curl_ossl_ctx_init(struct ossl_ctx *octx,
  3295. struct Curl_cfilter *cf,
  3296. struct Curl_easy *data,
  3297. struct ssl_peer *peer,
  3298. const struct alpn_spec *alpns_requested,
  3299. Curl_ossl_ctx_setup_cb *cb_setup,
  3300. void *cb_user_data,
  3301. Curl_ossl_new_session_cb *cb_new_session,
  3302. void *ssl_user_data,
  3303. Curl_ossl_init_session_reuse_cb *sess_reuse_cb)
  3304. {
  3305. CURLcode result = CURLE_OK;
  3306. const char *ciphers;
  3307. const SSL_METHOD *req_method = NULL;
  3308. ctx_option_t ctx_options = 0;
  3309. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  3310. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  3311. char * const ssl_cert = ssl_config->primary.clientcert;
  3312. const struct curl_blob *ssl_cert_blob = ssl_config->primary.cert_blob;
  3313. const char * const ssl_cert_type = ssl_config->cert_type;
  3314. unsigned int ssl_version_min;
  3315. char error_buffer[256];
  3316. /* Make funny stuff to get random input */
  3317. result = ossl_seed(data);
  3318. if(result)
  3319. return result;
  3320. ssl_config->certverifyresult = !X509_V_OK;
  3321. result = ossl_init_method(cf, data, peer, &req_method, &ssl_version_min);
  3322. if(result)
  3323. return result;
  3324. DEBUGASSERT(req_method);
  3325. DEBUGASSERT(!octx->ssl_ctx);
  3326. octx->ssl_ctx =
  3327. #ifdef OPENSSL_HAS_PROVIDERS
  3328. data->state.libctx ?
  3329. SSL_CTX_new_ex(data->state.libctx, data->state.propq, req_method):
  3330. #endif
  3331. SSL_CTX_new(req_method);
  3332. if(!octx->ssl_ctx) {
  3333. failf(data, "SSL: could not create a context: %s",
  3334. ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer)));
  3335. return CURLE_OUT_OF_MEMORY;
  3336. }
  3337. if(cb_setup) {
  3338. result = cb_setup(cf, data, cb_user_data);
  3339. if(result)
  3340. return result;
  3341. }
  3342. if(data->set.fdebug && data->set.verbose) {
  3343. /* the SSL trace callback is only used for verbose logging */
  3344. SSL_CTX_set_msg_callback(octx->ssl_ctx, ossl_trace);
  3345. SSL_CTX_set_msg_callback_arg(octx->ssl_ctx, cf);
  3346. }
  3347. /* OpenSSL contains code to work around lots of bugs and flaws in various
  3348. SSL-implementations. SSL_CTX_set_options() is used to enabled those
  3349. work-arounds. The man page for this option states that SSL_OP_ALL enables
  3350. all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
  3351. enable the bug workaround options if compatibility with somewhat broken
  3352. implementations is desired."
  3353. The "-no_ticket" option was introduced in OpenSSL 0.9.8j. it is a flag to
  3354. disable "rfc4507bis session ticket support". rfc4507bis was later turned
  3355. into the proper RFC5077: https://datatracker.ietf.org/doc/html/rfc5077
  3356. The enabled extension concerns the session management. I wonder how often
  3357. libcurl stops a connection and then resumes a TLS session. Also, sending
  3358. the session data is some overhead. I suggest that you just use your
  3359. proposed patch (which explicitly disables TICKET).
  3360. If someone writes an application with libcurl and OpenSSL who wants to
  3361. enable the feature, one can do this in the SSL callback.
  3362. SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
  3363. interoperability with web server Netscape Enterprise Server 2.0.1 which
  3364. was released back in 1996.
  3365. Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
  3366. become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
  3367. CVE-2010-4180 when using previous OpenSSL versions we no longer enable
  3368. this option regardless of OpenSSL version and SSL_OP_ALL definition.
  3369. OpenSSL added a work-around for an SSL 3.0/TLS 1.0 CBC vulnerability:
  3370. https://web.archive.org/web/20240114184648/openssl.org/~bodo/tls-cbc.txt.
  3371. In 0.9.6e they added a bit to SSL_OP_ALL that _disables_ that work-around
  3372. despite the fact that SSL_OP_ALL is documented to do "rather harmless"
  3373. workarounds. In order to keep the secure work-around, the
  3374. SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit must not be set.
  3375. */
  3376. ctx_options = SSL_OP_ALL | SSL_OP_NO_TICKET | SSL_OP_NO_COMPRESSION;
  3377. /* mitigate CVE-2010-4180 */
  3378. ctx_options &= ~(ctx_option_t)SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
  3379. /* unless the user explicitly asks to allow the protocol vulnerability we
  3380. use the work-around */
  3381. if(!ssl_config->enable_beast)
  3382. ctx_options &= ~(ctx_option_t)SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
  3383. switch(ssl_version_min) {
  3384. case CURL_SSLVERSION_SSLv2:
  3385. case CURL_SSLVERSION_SSLv3:
  3386. return CURLE_NOT_BUILT_IN;
  3387. /* "--tlsv<x.y>" options mean TLS >= version <x.y> */
  3388. case CURL_SSLVERSION_DEFAULT:
  3389. case CURL_SSLVERSION_TLSv1: /* TLS >= version 1.0 */
  3390. case CURL_SSLVERSION_TLSv1_0: /* TLS >= version 1.0 */
  3391. case CURL_SSLVERSION_TLSv1_1: /* TLS >= version 1.1 */
  3392. case CURL_SSLVERSION_TLSv1_2: /* TLS >= version 1.2 */
  3393. case CURL_SSLVERSION_TLSv1_3: /* TLS >= version 1.3 */
  3394. /* asking for any TLS version as the minimum, means no SSL versions
  3395. allowed */
  3396. ctx_options |= SSL_OP_NO_SSLv2;
  3397. ctx_options |= SSL_OP_NO_SSLv3;
  3398. result = ossl_set_ssl_version_min_max(cf, octx->ssl_ctx, ssl_version_min);
  3399. if(result)
  3400. return result;
  3401. break;
  3402. default:
  3403. failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
  3404. return CURLE_SSL_CONNECT_ERROR;
  3405. }
  3406. SSL_CTX_set_options(octx->ssl_ctx, ctx_options);
  3407. SSL_CTX_set_read_ahead(octx->ssl_ctx, 1);
  3408. /* Max TLS1.2 record size 0x4000 + 0x800.
  3409. OpenSSL supports processing "jumbo TLS record" (8 TLS records) in one go
  3410. for some algorithms, so match that here.
  3411. Experimentation shows that a slightly larger buffer is needed
  3412. to avoid short reads.
  3413. However using a large buffer (8 packets) actually decreases performance.
  3414. 4 packets is better.
  3415. */
  3416. #ifdef HAVE_SSL_CTX_SET_DEFAULT_READ_BUFFER_LEN
  3417. SSL_CTX_set_default_read_buffer_len(octx->ssl_ctx, 0x401e * 4);
  3418. #endif
  3419. /* We do retry writes sometimes from another buffer address */
  3420. SSL_CTX_set_mode(octx->ssl_ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  3421. ciphers = conn_config->cipher_list;
  3422. if(!ciphers && (peer->transport != TRNSPRT_QUIC))
  3423. ciphers = NULL;
  3424. if(ciphers && (ssl_version_min < CURL_SSLVERSION_TLSv1_3)) {
  3425. if(!SSL_CTX_set_cipher_list(octx->ssl_ctx, ciphers)) {
  3426. failf(data, "failed setting cipher list: %s", ciphers);
  3427. return CURLE_SSL_CIPHER;
  3428. }
  3429. infof(data, "Cipher selection: %s", ciphers);
  3430. }
  3431. #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
  3432. {
  3433. const char *ciphers13 = conn_config->cipher_list13;
  3434. if(ciphers13 &&
  3435. (!conn_config->version_max ||
  3436. (conn_config->version_max == CURL_SSLVERSION_MAX_DEFAULT) ||
  3437. (conn_config->version_max >= CURL_SSLVERSION_MAX_TLSv1_3))) {
  3438. if(!SSL_CTX_set_ciphersuites(octx->ssl_ctx, ciphers13)) {
  3439. failf(data, "failed setting TLS 1.3 cipher suite: %s", ciphers13);
  3440. return CURLE_SSL_CIPHER;
  3441. }
  3442. infof(data, "TLS 1.3 cipher selection: %s", ciphers13);
  3443. }
  3444. }
  3445. #endif
  3446. if(ssl_cert || ssl_cert_blob || ssl_cert_type) {
  3447. result = client_cert(data, octx->ssl_ctx,
  3448. ssl_cert, ssl_cert_blob, ssl_cert_type,
  3449. ssl_config->key, ssl_config->key_blob,
  3450. ssl_config->key_type, ssl_config->key_passwd);
  3451. if(result)
  3452. /* failf() is already done in client_cert() */
  3453. return result;
  3454. }
  3455. #ifdef HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH
  3456. /* OpenSSL 1.1.1 requires clients to opt-in for PHA */
  3457. SSL_CTX_set_post_handshake_auth(octx->ssl_ctx, 1);
  3458. #endif
  3459. {
  3460. const char *curves = conn_config->curves;
  3461. if(curves) {
  3462. #ifdef HAVE_BORINGSSL_LIKE
  3463. #define OSSL_CURVE_CAST(x) (x)
  3464. #else
  3465. #define OSSL_CURVE_CAST(x) (char *)CURL_UNCONST(x)
  3466. #endif
  3467. if(!SSL_CTX_set1_curves_list(octx->ssl_ctx, OSSL_CURVE_CAST(curves))) {
  3468. failf(data, "failed setting curves list: '%s'", curves);
  3469. return CURLE_SSL_CIPHER;
  3470. }
  3471. }
  3472. }
  3473. #ifdef HAVE_SSL_CTX_SET1_SIGALGS
  3474. #define OSSL_SIGALG_CAST(x) OSSL_CURVE_CAST(x)
  3475. {
  3476. const char *signature_algorithms = conn_config->signature_algorithms;
  3477. if(signature_algorithms) {
  3478. if(!SSL_CTX_set1_sigalgs_list(octx->ssl_ctx,
  3479. OSSL_SIGALG_CAST(signature_algorithms))) {
  3480. failf(data, "failed setting signature algorithms: '%s'",
  3481. signature_algorithms);
  3482. return CURLE_SSL_CIPHER;
  3483. }
  3484. }
  3485. }
  3486. #endif
  3487. #if defined(HAVE_OPENSSL_SRP) && defined(USE_TLS_SRP)
  3488. if(ssl_config->primary.username && Curl_auth_allowed_to_host(data)) {
  3489. char * const ssl_username = ssl_config->primary.username;
  3490. char * const ssl_password = ssl_config->primary.password;
  3491. infof(data, "Using TLS-SRP username: %s", ssl_username);
  3492. if(!SSL_CTX_set_srp_username(octx->ssl_ctx, ssl_username)) {
  3493. failf(data, "Unable to set SRP username");
  3494. return CURLE_BAD_FUNCTION_ARGUMENT;
  3495. }
  3496. if(!SSL_CTX_set_srp_password(octx->ssl_ctx, ssl_password)) {
  3497. failf(data, "failed setting SRP password");
  3498. return CURLE_BAD_FUNCTION_ARGUMENT;
  3499. }
  3500. if(!conn_config->cipher_list) {
  3501. infof(data, "Setting cipher list SRP");
  3502. if(!SSL_CTX_set_cipher_list(octx->ssl_ctx, "SRP")) {
  3503. failf(data, "failed setting SRP cipher list");
  3504. return CURLE_SSL_CIPHER;
  3505. }
  3506. }
  3507. }
  3508. #endif /* HAVE_OPENSSL_SRP && USE_TLS_SRP */
  3509. /* OpenSSL always tries to verify the peer. By setting the failure mode
  3510. * to NONE, we allow the connect to complete, regardless of the outcome.
  3511. * We then explicitly check the result and may try alternatives like
  3512. * Apple's SecTrust for verification. */
  3513. SSL_CTX_set_verify(octx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  3514. /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */
  3515. #ifdef HAVE_KEYLOG_CALLBACK
  3516. if(Curl_tls_keylog_enabled()) {
  3517. SSL_CTX_set_keylog_callback(octx->ssl_ctx, ossl_keylog_callback);
  3518. }
  3519. #endif
  3520. if(cb_new_session) {
  3521. /* Enable the session cache because it is a prerequisite for the
  3522. * "new session" callback. Use the "external storage" mode to prevent
  3523. * OpenSSL from creating an internal session cache.
  3524. */
  3525. SSL_CTX_set_session_cache_mode(octx->ssl_ctx,
  3526. SSL_SESS_CACHE_CLIENT |
  3527. SSL_SESS_CACHE_NO_INTERNAL);
  3528. SSL_CTX_sess_set_new_cb(octx->ssl_ctx, cb_new_session);
  3529. }
  3530. /* give application a chance to interfere with SSL set up. */
  3531. if(data->set.ssl.fsslctx) {
  3532. /* When a user callback is installed to modify the SSL_CTX,
  3533. * we need to do the full initialization before calling it.
  3534. * See: #11800 */
  3535. if(!octx->x509_store_setup) {
  3536. result = Curl_ssl_setup_x509_store(cf, data, octx);
  3537. if(result)
  3538. return result;
  3539. octx->x509_store_setup = TRUE;
  3540. }
  3541. Curl_set_in_callback(data, TRUE);
  3542. result = (*data->set.ssl.fsslctx)(data, octx->ssl_ctx,
  3543. data->set.ssl.fsslctxp);
  3544. Curl_set_in_callback(data, FALSE);
  3545. if(result) {
  3546. failf(data, "error signaled by ssl ctx callback");
  3547. return result;
  3548. }
  3549. }
  3550. return ossl_init_ssl(octx, cf, data, peer, alpns_requested,
  3551. ssl_user_data, sess_reuse_cb);
  3552. }
  3553. static CURLcode ossl_on_session_reuse(struct Curl_cfilter *cf,
  3554. struct Curl_easy *data,
  3555. struct alpn_spec *alpns,
  3556. struct Curl_ssl_session *scs,
  3557. bool *do_early_data)
  3558. {
  3559. struct ssl_connect_data *connssl = cf->ctx;
  3560. CURLcode result = CURLE_OK;
  3561. *do_early_data = FALSE;
  3562. connssl->earlydata_max = scs->earlydata_max;
  3563. if(!connssl->earlydata_max) {
  3564. CURL_TRC_CF(data, cf, "SSL session does not allow earlydata");
  3565. }
  3566. else if(!Curl_alpn_contains_proto(alpns, scs->alpn)) {
  3567. CURL_TRC_CF(data, cf, "SSL session has different ALPN, no early data");
  3568. }
  3569. else {
  3570. infof(data, "SSL session allows %zu bytes of early data, "
  3571. "reusing ALPN '%s'", connssl->earlydata_max, scs->alpn);
  3572. connssl->earlydata_state = ssl_earlydata_await;
  3573. connssl->state = ssl_connection_deferred;
  3574. result = Curl_alpn_set_negotiated(cf, data, connssl,
  3575. (const unsigned char *)scs->alpn,
  3576. scs->alpn ? strlen(scs->alpn) : 0);
  3577. *do_early_data = !result;
  3578. }
  3579. return result;
  3580. }
  3581. void Curl_ossl_report_handshake(struct Curl_easy *data, struct ossl_ctx *octx)
  3582. {
  3583. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  3584. if(Curl_trc_is_verbose(data)) {
  3585. int psigtype_nid = NID_undef;
  3586. const char *negotiated_group_name = NULL;
  3587. #ifdef HAVE_OPENSSL3
  3588. SSL_get_peer_signature_type_nid(octx->ssl, &psigtype_nid);
  3589. #if OPENSSL_VERSION_NUMBER >= 0x30200000L
  3590. negotiated_group_name = SSL_get0_group_name(octx->ssl);
  3591. #else
  3592. negotiated_group_name =
  3593. OBJ_nid2sn(SSL_get_negotiated_group(octx->ssl) & 0x0000FFFF);
  3594. #endif
  3595. #endif
  3596. /* Informational message */
  3597. infof(data, "SSL connection using %s / %s / %s / %s",
  3598. SSL_get_version(octx->ssl),
  3599. SSL_get_cipher(octx->ssl),
  3600. negotiated_group_name ? negotiated_group_name : "[blank]",
  3601. OBJ_nid2sn(psigtype_nid));
  3602. }
  3603. #else
  3604. (void)data;
  3605. (void)octx;
  3606. #endif /* CURL_DISABLE_VERBOSE_STRINGS */
  3607. }
  3608. static CURLcode ossl_connect_step1(struct Curl_cfilter *cf,
  3609. struct Curl_easy *data)
  3610. {
  3611. struct ssl_connect_data *connssl = cf->ctx;
  3612. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  3613. BIO *bio;
  3614. CURLcode result;
  3615. DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
  3616. DEBUGASSERT(octx);
  3617. result = Curl_ossl_ctx_init(octx, cf, data, &connssl->peer,
  3618. connssl->alpn, NULL, NULL,
  3619. ossl_new_session_cb, cf,
  3620. ossl_on_session_reuse);
  3621. if(result)
  3622. return result;
  3623. octx->bio_method = ossl_bio_cf_method_create();
  3624. if(!octx->bio_method)
  3625. return CURLE_OUT_OF_MEMORY;
  3626. bio = BIO_new(octx->bio_method);
  3627. if(!bio)
  3628. return CURLE_OUT_OF_MEMORY;
  3629. BIO_set_data(bio, cf);
  3630. #ifdef HAVE_SSL_SET0_WBIO
  3631. /* with OpenSSL v1.1.1 we get an alternative to SSL_set_bio() that works
  3632. * without backward compat quirks. Every call takes one reference, so we
  3633. * up it and pass. SSL* then owns it and will free.
  3634. * We check on the function in configure, since LibreSSL and friends
  3635. * each have their own versions to add support for this. */
  3636. BIO_up_ref(bio);
  3637. SSL_set0_rbio(octx->ssl, bio);
  3638. SSL_set0_wbio(octx->ssl, bio);
  3639. #else
  3640. SSL_set_bio(octx->ssl, bio, bio);
  3641. #endif
  3642. if(connssl->alpn && (connssl->state != ssl_connection_deferred)) {
  3643. struct alpn_proto_buf proto;
  3644. memset(&proto, 0, sizeof(proto));
  3645. Curl_alpn_to_proto_str(&proto, connssl->alpn);
  3646. infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
  3647. }
  3648. connssl->connecting_state = ssl_connect_2;
  3649. return CURLE_OK;
  3650. }
  3651. #ifdef HAVE_SSL_SET1_ECH_CONFIG_LIST
  3652. /* If we have retry configs, then trace those out */
  3653. static void ossl_trace_ech_retry_configs(struct Curl_easy *data, SSL *ssl,
  3654. int reason)
  3655. {
  3656. CURLcode result = CURLE_OK;
  3657. size_t rcl = 0;
  3658. int rv = 1;
  3659. # ifndef HAVE_BORINGSSL_LIKE
  3660. char *inner = NULL;
  3661. uint8_t *rcs = NULL;
  3662. char *outer = NULL;
  3663. # else
  3664. const char *inner = NULL;
  3665. const uint8_t *rcs = NULL;
  3666. const char *outer = NULL;
  3667. size_t out_name_len = 0;
  3668. int servername_type = 0;
  3669. # endif
  3670. /* nothing to trace if not doing ECH */
  3671. if(!ECH_ENABLED(data))
  3672. return;
  3673. # ifndef HAVE_BORINGSSL_LIKE
  3674. rv = SSL_ech_get1_retry_config(ssl, &rcs, &rcl);
  3675. # else
  3676. SSL_get0_ech_retry_configs(ssl, &rcs, &rcl);
  3677. rv = (int)rcl;
  3678. # endif
  3679. if(rv && rcs) {
  3680. char *b64str = NULL;
  3681. size_t blen = 0;
  3682. result = curlx_base64_encode(rcs, rcl, &b64str, &blen);
  3683. if(!result && b64str) {
  3684. infof(data, "ECH: retry_configs %s", b64str);
  3685. curlx_free(b64str);
  3686. #ifndef HAVE_BORINGSSL_LIKE
  3687. rv = SSL_ech_get1_status(ssl, &inner, &outer);
  3688. infof(data, "ECH: retry_configs for %s from %s, %d %d",
  3689. inner ? inner : "NULL", outer ? outer : "NULL", reason, rv);
  3690. #else
  3691. rv = SSL_ech_accepted(ssl);
  3692. servername_type = SSL_get_servername_type(ssl);
  3693. inner = SSL_get_servername(ssl, servername_type);
  3694. SSL_get0_ech_name_override(ssl, &outer, &out_name_len);
  3695. infof(data, "ECH: retry_configs for %s from %s, %d %d",
  3696. inner ? inner : "NULL", outer ? outer : "NULL", reason, rv);
  3697. #endif
  3698. }
  3699. }
  3700. else
  3701. infof(data, "ECH: no retry_configs (rv = %d)", rv);
  3702. # ifndef HAVE_BORINGSSL_LIKE
  3703. OPENSSL_free((void *)rcs);
  3704. # endif
  3705. return;
  3706. }
  3707. #endif
  3708. static CURLcode ossl_connect_step2(struct Curl_cfilter *cf,
  3709. struct Curl_easy *data)
  3710. {
  3711. int err;
  3712. struct ssl_connect_data *connssl = cf->ctx;
  3713. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  3714. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  3715. DEBUGASSERT(ssl_connect_2 == connssl->connecting_state);
  3716. DEBUGASSERT(octx);
  3717. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  3718. ERR_clear_error();
  3719. err = SSL_connect(octx->ssl);
  3720. if(!octx->x509_store_setup) {
  3721. /* After having send off the ClientHello, we prepare the x509
  3722. * store to verify the coming certificate from the server */
  3723. CURLcode result = Curl_ssl_setup_x509_store(cf, data, octx);
  3724. if(result)
  3725. return result;
  3726. octx->x509_store_setup = TRUE;
  3727. }
  3728. #ifndef HAVE_KEYLOG_CALLBACK
  3729. /* If key logging is enabled, wait for the handshake to complete and then
  3730. * proceed with logging secrets (for TLS 1.2 or older).
  3731. */
  3732. if(Curl_tls_keylog_enabled() && !octx->keylog_done)
  3733. ossl_log_tls12_secret(octx->ssl, &octx->keylog_done);
  3734. #endif
  3735. /* 1 is fine
  3736. 0 is "not successful but was shut down controlled"
  3737. <0 is "handshake was not successful, because a fatal error occurred" */
  3738. if(err != 1) {
  3739. int detail = SSL_get_error(octx->ssl, err);
  3740. CURL_TRC_CF(data, cf, "SSL_connect() -> err=%d, detail=%d", err, detail);
  3741. if(SSL_ERROR_WANT_READ == detail) {
  3742. CURL_TRC_CF(data, cf, "SSL_connect() -> want recv");
  3743. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  3744. return CURLE_AGAIN;
  3745. }
  3746. if(SSL_ERROR_WANT_WRITE == detail) {
  3747. CURL_TRC_CF(data, cf, "SSL_connect() -> want send");
  3748. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  3749. return CURLE_AGAIN;
  3750. }
  3751. #ifdef SSL_ERROR_WANT_ASYNC
  3752. if(SSL_ERROR_WANT_ASYNC == detail) {
  3753. CURL_TRC_CF(data, cf, "SSL_connect() -> want async");
  3754. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  3755. return CURLE_AGAIN;
  3756. }
  3757. #endif
  3758. #ifdef SSL_ERROR_WANT_RETRY_VERIFY
  3759. if(SSL_ERROR_WANT_RETRY_VERIFY == detail) {
  3760. CURL_TRC_CF(data, cf, "SSL_connect() -> want retry_verify");
  3761. Curl_xfer_pause_recv(data, TRUE);
  3762. return CURLE_AGAIN;
  3763. }
  3764. #endif
  3765. else {
  3766. /* untreated error */
  3767. sslerr_t errdetail;
  3768. char error_buffer[256] = "";
  3769. CURLcode result;
  3770. long lerr;
  3771. int lib;
  3772. int reason;
  3773. /* the connection failed, we are not waiting for anything else. */
  3774. connssl->connecting_state = ssl_connect_2;
  3775. /* Get the earliest error code from the thread's error queue and remove
  3776. the entry. */
  3777. errdetail = ERR_get_error();
  3778. /* Extract which lib and reason */
  3779. lib = ERR_GET_LIB(errdetail);
  3780. reason = ERR_GET_REASON(errdetail);
  3781. if((lib == ERR_LIB_SSL) &&
  3782. ((reason == SSL_R_CERTIFICATE_VERIFY_FAILED) ||
  3783. (reason == SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED))) {
  3784. result = CURLE_PEER_FAILED_VERIFICATION;
  3785. lerr = SSL_get_verify_result(octx->ssl);
  3786. if(lerr != X509_V_OK) {
  3787. ssl_config->certverifyresult = lerr;
  3788. failf(data, "SSL certificate problem: %s",
  3789. X509_verify_cert_error_string(lerr));
  3790. }
  3791. else
  3792. failf(data, "%s", "SSL certificate verification failed");
  3793. }
  3794. #ifdef SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED
  3795. /* SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED is only available on
  3796. OpenSSL version above v1.1.1, not LibreSSL, BoringSSL, or AWS-LC */
  3797. else if((lib == ERR_LIB_SSL) &&
  3798. (reason == SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED)) {
  3799. /* If client certificate is required, communicate the
  3800. error to client */
  3801. result = CURLE_SSL_CLIENTCERT;
  3802. failf(data, "TLS cert problem: %s",
  3803. ossl_strerror(errdetail, error_buffer, sizeof(error_buffer)));
  3804. }
  3805. #endif
  3806. #ifdef HAVE_SSL_SET1_ECH_CONFIG_LIST
  3807. else if((lib == ERR_LIB_SSL) &&
  3808. # ifndef HAVE_BORINGSSL_LIKE
  3809. (reason == SSL_R_ECH_REQUIRED)) {
  3810. # else
  3811. (reason == SSL_R_ECH_REJECTED)) {
  3812. # endif
  3813. /* trace retry_configs if we got some */
  3814. ossl_trace_ech_retry_configs(data, octx->ssl, reason);
  3815. result = CURLE_ECH_REQUIRED;
  3816. failf(data, "ECH required: %s",
  3817. ossl_strerror(errdetail, error_buffer, sizeof(error_buffer)));
  3818. }
  3819. #endif
  3820. else {
  3821. result = CURLE_SSL_CONNECT_ERROR;
  3822. failf(data, "TLS connect error: %s",
  3823. ossl_strerror(errdetail, error_buffer, sizeof(error_buffer)));
  3824. }
  3825. /* detail is already set to the SSL error above */
  3826. /* If we e.g. use SSLv2 request-method and the server does not like us
  3827. * (RST connection, etc.), OpenSSL gives no explanation whatsoever and
  3828. * the SO_ERROR is also lost.
  3829. */
  3830. if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
  3831. char extramsg[80] = "";
  3832. int sockerr = SOCKERRNO;
  3833. if(sockerr && detail == SSL_ERROR_SYSCALL)
  3834. curlx_strerror(sockerr, extramsg, sizeof(extramsg));
  3835. failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%d ",
  3836. extramsg[0] ? extramsg : SSL_ERROR_to_str(detail),
  3837. connssl->peer.hostname, connssl->peer.port);
  3838. }
  3839. return result;
  3840. }
  3841. }
  3842. else {
  3843. /* we connected fine, we are not waiting for anything else. */
  3844. connssl->connecting_state = ssl_connect_3;
  3845. Curl_ossl_report_handshake(data, octx);
  3846. #if defined(HAVE_SSL_SET1_ECH_CONFIG_LIST) && !defined(HAVE_BORINGSSL_LIKE)
  3847. if(ECH_ENABLED(data)) {
  3848. char *inner = NULL, *outer = NULL;
  3849. const char *status = NULL;
  3850. int rv;
  3851. rv = SSL_ech_get1_status(octx->ssl, &inner, &outer);
  3852. switch(rv) {
  3853. case SSL_ECH_STATUS_SUCCESS:
  3854. status = "succeeded";
  3855. break;
  3856. case SSL_ECH_STATUS_GREASE_ECH:
  3857. status = "sent GREASE, got retry-configs";
  3858. break;
  3859. case SSL_ECH_STATUS_GREASE:
  3860. status = "sent GREASE";
  3861. break;
  3862. case SSL_ECH_STATUS_NOT_TRIED:
  3863. status = "not attempted";
  3864. break;
  3865. case SSL_ECH_STATUS_NOT_CONFIGURED:
  3866. status = "not configured";
  3867. break;
  3868. case SSL_ECH_STATUS_BACKEND:
  3869. status = "backend (unexpected)";
  3870. break;
  3871. case SSL_ECH_STATUS_FAILED:
  3872. status = "failed";
  3873. break;
  3874. case SSL_ECH_STATUS_BAD_CALL:
  3875. status = "bad call (unexpected)";
  3876. break;
  3877. case SSL_ECH_STATUS_BAD_NAME:
  3878. status = "bad name (unexpected)";
  3879. break;
  3880. default:
  3881. status = "unexpected status";
  3882. infof(data, "ECH: unexpected status %d", rv);
  3883. }
  3884. infof(data, "ECH: result: status is %s, inner is %s, outer is %s",
  3885. (status ? status : "NULL"),
  3886. (inner ? inner : "NULL"),
  3887. (outer ? outer : "NULL"));
  3888. OPENSSL_free(inner);
  3889. OPENSSL_free(outer);
  3890. if(rv == SSL_ECH_STATUS_GREASE_ECH) {
  3891. /* trace retry_configs if we got some */
  3892. ossl_trace_ech_retry_configs(data, octx->ssl, 0);
  3893. }
  3894. if(rv != SSL_ECH_STATUS_SUCCESS
  3895. && data->set.tls_ech & CURLECH_HARD) {
  3896. infof(data, "ECH: ech-hard failed");
  3897. return CURLE_SSL_CONNECT_ERROR;
  3898. }
  3899. }
  3900. else {
  3901. infof(data, "ECH: result: status is not attempted");
  3902. }
  3903. #endif /* HAVE_SSL_SET1_ECH_CONFIG_LIST && !HAVE_BORINGSSL_LIKE */
  3904. /* Sets data and len to negotiated protocol, len is 0 if no protocol was
  3905. * negotiated
  3906. */
  3907. if(connssl->alpn) {
  3908. const unsigned char *neg_protocol;
  3909. unsigned int len;
  3910. SSL_get0_alpn_selected(octx->ssl, &neg_protocol, &len);
  3911. return Curl_alpn_set_negotiated(cf, data, connssl, neg_protocol, len);
  3912. }
  3913. return CURLE_OK;
  3914. }
  3915. }
  3916. /*
  3917. * Heavily modified from:
  3918. * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
  3919. */
  3920. static CURLcode ossl_pkp_pin_peer_pubkey(struct Curl_easy *data, X509 *cert,
  3921. const char *pinnedpubkey)
  3922. {
  3923. /* Scratch */
  3924. int len1 = 0, len2 = 0;
  3925. unsigned char *buff1 = NULL, *temp = NULL;
  3926. /* Result is returned to caller */
  3927. CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  3928. /* if a path was not specified, do not pin */
  3929. if(!pinnedpubkey)
  3930. return CURLE_OK;
  3931. if(!cert)
  3932. return result;
  3933. do {
  3934. /* Get the subjectPublicKeyInfo */
  3935. /* https://groups.google.com/group/mailing.openssl.users/browse_thread/thread/d61858dae102c6c7 */
  3936. len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
  3937. if(len1 < 1)
  3938. break; /* failed */
  3939. buff1 = temp = curlx_malloc(len1);
  3940. if(!buff1)
  3941. break; /* failed */
  3942. /* https://docs.openssl.org/master/man3/d2i_X509/ */
  3943. len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
  3944. /*
  3945. * These checks are verifying we got back the same values as when we
  3946. * sized the buffer. it is pretty weak since they should always be the
  3947. * same. But it gives us something to test.
  3948. */
  3949. if((len1 != len2) || !temp || ((temp - buff1) != len1))
  3950. break; /* failed */
  3951. /* End Gyrations */
  3952. /* The one good exit point */
  3953. result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
  3954. } while(0);
  3955. if(buff1)
  3956. curlx_free(buff1);
  3957. return result;
  3958. }
  3959. #if !(defined(LIBRESSL_VERSION_NUMBER) && \
  3960. LIBRESSL_VERSION_NUMBER < 0x3060000fL) && \
  3961. !defined(HAVE_BORINGSSL_LIKE) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  3962. static void infof_certstack(struct Curl_easy *data, const SSL *ssl)
  3963. {
  3964. STACK_OF(X509) *certstack;
  3965. long verify_result;
  3966. int num_cert_levels;
  3967. int cert_level;
  3968. if(!Curl_trc_is_verbose(data))
  3969. return;
  3970. verify_result = SSL_get_verify_result(ssl);
  3971. if(verify_result != X509_V_OK)
  3972. certstack = SSL_get_peer_cert_chain(ssl);
  3973. else
  3974. certstack = SSL_get0_verified_chain(ssl);
  3975. if(!certstack)
  3976. return;
  3977. num_cert_levels = sk_X509_num(certstack);
  3978. for(cert_level = 0; cert_level < num_cert_levels; cert_level++) {
  3979. char cert_algorithm[80] = "";
  3980. char group_name_final[80] = "";
  3981. const X509_ALGOR *palg_cert = NULL;
  3982. const ASN1_OBJECT *paobj_cert = NULL;
  3983. X509 *current_cert;
  3984. EVP_PKEY *current_pkey;
  3985. int key_bits;
  3986. int key_sec_bits;
  3987. int get_group_name;
  3988. const char *type_name;
  3989. current_cert = sk_X509_value(certstack, cert_level);
  3990. if(!current_cert)
  3991. continue;
  3992. current_pkey = X509_get0_pubkey(current_cert);
  3993. if(!current_pkey)
  3994. continue;
  3995. X509_get0_signature(NULL, &palg_cert, current_cert);
  3996. X509_ALGOR_get0(&paobj_cert, NULL, NULL, palg_cert);
  3997. OBJ_obj2txt(cert_algorithm, sizeof(cert_algorithm), paobj_cert, 0);
  3998. key_bits = EVP_PKEY_bits(current_pkey);
  3999. #ifndef HAVE_OPENSSL3
  4000. #define EVP_PKEY_get_security_bits EVP_PKEY_security_bits
  4001. #endif
  4002. key_sec_bits = EVP_PKEY_get_security_bits(current_pkey);
  4003. #ifdef HAVE_OPENSSL3
  4004. {
  4005. char group_name[80] = "";
  4006. get_group_name = EVP_PKEY_get_group_name(current_pkey, group_name,
  4007. sizeof(group_name), NULL);
  4008. curl_msnprintf(group_name_final, sizeof(group_name_final), "/%s",
  4009. group_name);
  4010. }
  4011. type_name = EVP_PKEY_get0_type_name(current_pkey);
  4012. #else
  4013. get_group_name = 0;
  4014. type_name = NULL;
  4015. #endif
  4016. infof(data, " Certificate level %d: "
  4017. "Public key type %s%s (%d/%d Bits/secBits), signed using %s",
  4018. cert_level, type_name ? type_name : "?",
  4019. get_group_name == 0 ? "" : group_name_final,
  4020. key_bits, key_sec_bits, cert_algorithm);
  4021. }
  4022. }
  4023. #else
  4024. #define infof_certstack(data, ssl)
  4025. #endif
  4026. static CURLcode ossl_check_issuer(struct Curl_cfilter *cf,
  4027. struct Curl_easy *data,
  4028. X509 *server_cert)
  4029. {
  4030. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  4031. X509 *issuer = NULL;
  4032. BIO *fp = NULL;
  4033. char err_buf[256] = "";
  4034. bool verify_enabled = (conn_config->verifypeer || conn_config->verifyhost);
  4035. CURLcode result = CURLE_OK;
  4036. /* e.g. match issuer name with provided issuer certificate */
  4037. if(conn_config->issuercert_blob) {
  4038. fp = BIO_new_mem_buf(conn_config->issuercert_blob->data,
  4039. (int)conn_config->issuercert_blob->len);
  4040. if(!fp) {
  4041. failf(data, "BIO_new_mem_buf NULL, " OSSL_PACKAGE " error %s",
  4042. ossl_strerror(ERR_get_error(), err_buf, sizeof(err_buf)));
  4043. result = CURLE_OUT_OF_MEMORY;
  4044. goto out;
  4045. }
  4046. }
  4047. else if(conn_config->issuercert) {
  4048. fp = BIO_new(BIO_s_file());
  4049. if(!fp) {
  4050. failf(data, "BIO_new return NULL, " OSSL_PACKAGE " error %s",
  4051. ossl_strerror(ERR_get_error(), err_buf, sizeof(err_buf)));
  4052. result = CURLE_OUT_OF_MEMORY;
  4053. goto out;
  4054. }
  4055. if(BIO_read_filename(fp, conn_config->issuercert) <= 0) {
  4056. if(verify_enabled)
  4057. failf(data, "SSL: Unable to open issuer cert (%s)",
  4058. conn_config->issuercert);
  4059. result = CURLE_SSL_ISSUER_ERROR;
  4060. goto out;
  4061. }
  4062. }
  4063. if(fp) {
  4064. issuer = PEM_read_bio_X509(fp, NULL, ZERO_NULL, NULL);
  4065. if(!issuer) {
  4066. if(verify_enabled)
  4067. failf(data, "SSL: Unable to read issuer cert (%s)",
  4068. conn_config->issuercert);
  4069. result = CURLE_SSL_ISSUER_ERROR;
  4070. goto out;
  4071. }
  4072. if(X509_check_issued(issuer, server_cert) != X509_V_OK) {
  4073. if(verify_enabled)
  4074. failf(data, "SSL: Certificate issuer check failed (%s)",
  4075. conn_config->issuercert);
  4076. result = CURLE_SSL_ISSUER_ERROR;
  4077. goto out;
  4078. }
  4079. infof(data, " SSL certificate issuer check ok (%s)",
  4080. conn_config->issuercert);
  4081. }
  4082. out:
  4083. if(fp)
  4084. BIO_free(fp);
  4085. if(issuer)
  4086. X509_free(issuer);
  4087. return result;
  4088. }
  4089. static CURLcode ossl_check_pinned_key(struct Curl_cfilter *cf,
  4090. struct Curl_easy *data,
  4091. X509 *server_cert)
  4092. {
  4093. const char *ptr;
  4094. CURLcode result = CURLE_OK;
  4095. (void)cf;
  4096. #ifndef CURL_DISABLE_PROXY
  4097. ptr = Curl_ssl_cf_is_proxy(cf) ?
  4098. data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
  4099. data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  4100. #else
  4101. ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  4102. #endif
  4103. if(ptr) {
  4104. result = ossl_pkp_pin_peer_pubkey(data, server_cert, ptr);
  4105. if(result)
  4106. failf(data, "SSL: public key does not match pinned public key");
  4107. }
  4108. return result;
  4109. }
  4110. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  4111. #define MAX_CERT_NAME_LENGTH 2048
  4112. static CURLcode ossl_infof_cert(struct Curl_cfilter *cf,
  4113. struct Curl_easy *data,
  4114. X509 *server_cert)
  4115. {
  4116. BIO *mem = NULL;
  4117. struct dynbuf dname;
  4118. char err_buf[256] = "";
  4119. char *buf;
  4120. long len;
  4121. CURLcode result = CURLE_OK;
  4122. if(!Curl_trc_is_verbose(data))
  4123. return CURLE_OK;
  4124. curlx_dyn_init(&dname, MAX_CERT_NAME_LENGTH);
  4125. mem = BIO_new(BIO_s_mem());
  4126. if(!mem) {
  4127. failf(data, "BIO_new return NULL, " OSSL_PACKAGE " error %s",
  4128. ossl_strerror(ERR_get_error(), err_buf, sizeof(err_buf)));
  4129. result = CURLE_OUT_OF_MEMORY;
  4130. goto out;
  4131. }
  4132. infof(data, "%s certificate:", Curl_ssl_cf_is_proxy(cf) ?
  4133. "Proxy" : "Server");
  4134. result = x509_name_oneline(X509_get_subject_name(server_cert), &dname);
  4135. infof(data, " subject: %s", result ? "[NONE]" : curlx_dyn_ptr(&dname));
  4136. ASN1_TIME_print(mem, X509_get0_notBefore(server_cert));
  4137. len = BIO_get_mem_data(mem, (char **)&buf);
  4138. infof(data, " start date: %.*s", (int)len, buf);
  4139. (void)BIO_reset(mem);
  4140. ASN1_TIME_print(mem, X509_get0_notAfter(server_cert));
  4141. len = BIO_get_mem_data(mem, (char **)&buf);
  4142. infof(data, " expire date: %.*s", (int)len, buf);
  4143. (void)BIO_reset(mem);
  4144. result = x509_name_oneline(X509_get_issuer_name(server_cert), &dname);
  4145. if(result) /* should be only fatal stuff like OOM */
  4146. goto out;
  4147. infof(data, " issuer: %s", curlx_dyn_ptr(&dname));
  4148. out:
  4149. BIO_free(mem);
  4150. curlx_dyn_free(&dname);
  4151. return result;
  4152. }
  4153. #endif /* !CURL_DISABLE_VERBOSE_STRINGS */
  4154. #ifdef USE_APPLE_SECTRUST
  4155. struct ossl_certs_ctx {
  4156. STACK_OF(X509) *sk;
  4157. size_t num_certs;
  4158. };
  4159. static CURLcode ossl_chain_get_der(struct Curl_cfilter *cf,
  4160. struct Curl_easy *data,
  4161. void *user_data,
  4162. size_t i,
  4163. unsigned char **pder,
  4164. size_t *pder_len)
  4165. {
  4166. struct ossl_certs_ctx *chain = user_data;
  4167. X509 *cert;
  4168. int der_len;
  4169. (void)cf;
  4170. (void)data;
  4171. *pder_len = 0;
  4172. *pder = NULL;
  4173. if(i >= chain->num_certs)
  4174. return CURLE_TOO_LARGE;
  4175. cert = sk_X509_value(chain->sk, (int)i);
  4176. if(!cert)
  4177. return CURLE_FAILED_INIT;
  4178. der_len = i2d_X509(cert, pder);
  4179. if(der_len < 0)
  4180. return CURLE_FAILED_INIT;
  4181. *pder_len = (size_t)der_len;
  4182. return CURLE_OK;
  4183. }
  4184. static CURLcode ossl_apple_verify(struct Curl_cfilter *cf,
  4185. struct Curl_easy *data,
  4186. struct ossl_ctx *octx,
  4187. struct ssl_peer *peer,
  4188. bool *pverified)
  4189. {
  4190. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  4191. struct ossl_certs_ctx chain;
  4192. CURLcode result;
  4193. memset(&chain, 0, sizeof(chain));
  4194. chain.sk = SSL_get_peer_cert_chain(octx->ssl);
  4195. chain.num_certs = chain.sk ? sk_X509_num(chain.sk) : 0;
  4196. if(!chain.num_certs &&
  4197. (conn_config->verifypeer || conn_config->verifyhost)) {
  4198. failf(data, "SSL: could not get peer certificate");
  4199. result = CURLE_PEER_FAILED_VERIFICATION;
  4200. }
  4201. else {
  4202. #ifdef HAVE_BORINGSSL_LIKE
  4203. const uint8_t *ocsp_data = NULL;
  4204. #else
  4205. unsigned char *ocsp_data = NULL;
  4206. #endif
  4207. long ocsp_len = 0;
  4208. if(conn_config->verifystatus && !octx->reused_session)
  4209. ocsp_len = (long)SSL_get_tlsext_status_ocsp_resp(octx->ssl, &ocsp_data);
  4210. /* SSL_get_tlsext_status_ocsp_resp() returns the length of the OCSP
  4211. response data or -1 if there is no OCSP response data. */
  4212. if(ocsp_len < 0)
  4213. ocsp_len = 0; /* no data available */
  4214. result = Curl_vtls_apple_verify(cf, data, peer, chain.num_certs,
  4215. ossl_chain_get_der, &chain,
  4216. ocsp_data, ocsp_len);
  4217. }
  4218. *pverified = !result;
  4219. return result;
  4220. }
  4221. #endif /* USE_APPLE_SECTRUST */
  4222. CURLcode Curl_ossl_check_peer_cert(struct Curl_cfilter *cf,
  4223. struct Curl_easy *data,
  4224. struct ossl_ctx *octx,
  4225. struct ssl_peer *peer)
  4226. {
  4227. struct connectdata *conn = cf->conn;
  4228. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  4229. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  4230. CURLcode result = CURLE_OK;
  4231. long ossl_verify;
  4232. X509 *server_cert;
  4233. bool verified = FALSE;
  4234. #if !defined(OPENSSL_NO_OCSP) && defined(USE_APPLE_SECTRUST)
  4235. bool sectrust_verified = FALSE;
  4236. #endif
  4237. if(data->set.ssl.certinfo && !octx->reused_session) {
  4238. /* asked to gather certificate info. Reused sessions do not have cert
  4239. chains */
  4240. result = ossl_certchain(data, octx->ssl);
  4241. if(result)
  4242. return result;
  4243. }
  4244. server_cert = SSL_get1_peer_certificate(octx->ssl);
  4245. if(!server_cert) {
  4246. /* no verification at all, this maybe acceptable */
  4247. if(!(conn_config->verifypeer || conn_config->verifyhost))
  4248. goto out;
  4249. failf(data, "SSL: could not get peer certificate");
  4250. result = CURLE_PEER_FAILED_VERIFICATION;
  4251. goto out;
  4252. }
  4253. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  4254. result = ossl_infof_cert(cf, data, server_cert);
  4255. if(result)
  4256. goto out;
  4257. infof_certstack(data, octx->ssl);
  4258. #endif
  4259. if(conn_config->verifyhost) {
  4260. result = ossl_verifyhost(data, conn, peer, server_cert);
  4261. if(result)
  4262. goto out;
  4263. }
  4264. /* `verifyhost` is either OK or not requested from here on */
  4265. ossl_verify = SSL_get_verify_result(octx->ssl);
  4266. ssl_config->certverifyresult = ossl_verify;
  4267. verified = (ossl_verify == X509_V_OK);
  4268. if(verified)
  4269. infof(data, "SSL certificate verified via OpenSSL.");
  4270. #ifdef USE_APPLE_SECTRUST
  4271. if(!verified && conn_config->verifypeer && ssl_config->native_ca_store) {
  4272. /* we verify using Apple SecTrust *unless* OpenSSL already verified.
  4273. * This may happen if the application intercepted the OpenSSL callback
  4274. * and installed its own. */
  4275. result = ossl_apple_verify(cf, data, octx, peer, &verified);
  4276. if(result && (result != CURLE_PEER_FAILED_VERIFICATION))
  4277. goto out; /* unexpected error */
  4278. if(verified) {
  4279. infof(data, "SSL certificate verified via Apple SecTrust.");
  4280. ssl_config->certverifyresult = X509_V_OK;
  4281. #ifndef OPENSSL_NO_OCSP
  4282. sectrust_verified = TRUE;
  4283. #endif
  4284. }
  4285. }
  4286. #endif
  4287. if(!verified) {
  4288. /* no trust established, report the OpenSSL status */
  4289. if(conn_config->verifypeer) {
  4290. failf(data, "SSL certificate OpenSSL verify result: %s (%ld)",
  4291. X509_verify_cert_error_string(ossl_verify), ossl_verify);
  4292. result = CURLE_PEER_FAILED_VERIFICATION;
  4293. goto out;
  4294. }
  4295. infof(data, " SSL certificate verification failed, continuing anyway!");
  4296. }
  4297. #ifndef OPENSSL_NO_OCSP
  4298. if(conn_config->verifystatus &&
  4299. #ifdef USE_APPLE_SECTRUST
  4300. !sectrust_verified && /* already verified via apple sectrust, cannot
  4301. * verifystate via OpenSSL in that case as it
  4302. * does not have the trust anchors */
  4303. #endif
  4304. !octx->reused_session) {
  4305. /* do not do this after Session ID reuse */
  4306. result = verifystatus(cf, data, octx);
  4307. if(result)
  4308. goto out;
  4309. }
  4310. #endif
  4311. result = ossl_check_issuer(cf, data, server_cert);
  4312. if(result)
  4313. goto out;
  4314. result = ossl_check_pinned_key(cf, data, server_cert);
  4315. out:
  4316. X509_free(server_cert);
  4317. return result;
  4318. }
  4319. static CURLcode ossl_connect_step3(struct Curl_cfilter *cf,
  4320. struct Curl_easy *data)
  4321. {
  4322. CURLcode result = CURLE_OK;
  4323. struct ssl_connect_data *connssl = cf->ctx;
  4324. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4325. DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
  4326. /*
  4327. * We check certificates to authenticate the server; otherwise we risk
  4328. * man-in-the-middle attack; NEVERTHELESS, if we are told explicitly not to
  4329. * verify the peer, ignore faults and failures from the server cert
  4330. * operations.
  4331. */
  4332. result = Curl_ossl_check_peer_cert(cf, data, octx, &connssl->peer);
  4333. if(result)
  4334. /* on error, remove sessions we might have in the pool */
  4335. Curl_ssl_scache_remove_all(cf, data, connssl->peer.scache_key);
  4336. return result;
  4337. }
  4338. #ifdef HAVE_OPENSSL_EARLYDATA
  4339. static CURLcode ossl_send_earlydata(struct Curl_cfilter *cf,
  4340. struct Curl_easy *data)
  4341. {
  4342. struct ssl_connect_data *connssl = cf->ctx;
  4343. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4344. CURLcode result = CURLE_OK;
  4345. const unsigned char *buf;
  4346. size_t blen, nwritten;
  4347. int rc;
  4348. DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sending);
  4349. octx->io_result = CURLE_OK;
  4350. while(Curl_bufq_peek(&connssl->earlydata, &buf, &blen)) {
  4351. nwritten = 0;
  4352. rc = SSL_write_early_data(octx->ssl, buf, blen, &nwritten);
  4353. CURL_TRC_CF(data, cf, "SSL_write_early_data(len=%zu) -> %d, %zu",
  4354. blen, rc, nwritten);
  4355. if(rc <= 0) {
  4356. long sslerror;
  4357. char error_buffer[256];
  4358. int err = SSL_get_error(octx->ssl, rc);
  4359. switch(err) {
  4360. case SSL_ERROR_WANT_READ:
  4361. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  4362. result = CURLE_AGAIN;
  4363. goto out;
  4364. case SSL_ERROR_WANT_WRITE:
  4365. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  4366. result = CURLE_AGAIN;
  4367. goto out;
  4368. case SSL_ERROR_SYSCALL: {
  4369. int sockerr = SOCKERRNO;
  4370. if(octx->io_result == CURLE_AGAIN) {
  4371. result = CURLE_AGAIN;
  4372. goto out;
  4373. }
  4374. sslerror = ERR_get_error();
  4375. if(sslerror)
  4376. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
  4377. else if(sockerr)
  4378. curlx_strerror(sockerr, error_buffer, sizeof(error_buffer));
  4379. else
  4380. curl_msnprintf(error_buffer, sizeof(error_buffer), "%s",
  4381. SSL_ERROR_to_str(err));
  4382. failf(data, OSSL_PACKAGE " SSL_write:early_data: %s, errno %d",
  4383. error_buffer, sockerr);
  4384. result = CURLE_SEND_ERROR;
  4385. goto out;
  4386. }
  4387. case SSL_ERROR_SSL: {
  4388. /* A failure in the SSL library occurred, usually a protocol error.
  4389. The OpenSSL error queue contains more information on the error. */
  4390. sslerror = ERR_get_error();
  4391. failf(data, "SSL_write_early_data() error: %s",
  4392. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
  4393. result = CURLE_SEND_ERROR;
  4394. goto out;
  4395. }
  4396. default:
  4397. /* a true error */
  4398. failf(data, OSSL_PACKAGE " SSL_write_early_data: %s, errno %d",
  4399. SSL_ERROR_to_str(err), SOCKERRNO);
  4400. result = CURLE_SEND_ERROR;
  4401. goto out;
  4402. }
  4403. }
  4404. Curl_bufq_skip(&connssl->earlydata, nwritten);
  4405. }
  4406. /* sent everything there was */
  4407. infof(data, "SSL sending %zu bytes of early data", connssl->earlydata_skip);
  4408. out:
  4409. return result;
  4410. }
  4411. #endif /* HAVE_OPENSSL_EARLYDATA */
  4412. static CURLcode ossl_connect(struct Curl_cfilter *cf,
  4413. struct Curl_easy *data,
  4414. bool *done)
  4415. {
  4416. CURLcode result = CURLE_OK;
  4417. struct ssl_connect_data *connssl = cf->ctx;
  4418. /* check if the connection has already been established */
  4419. if(ssl_connection_complete == connssl->state) {
  4420. *done = TRUE;
  4421. return CURLE_OK;
  4422. }
  4423. *done = FALSE;
  4424. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  4425. if(ssl_connect_1 == connssl->connecting_state) {
  4426. CURL_TRC_CF(data, cf, "ossl_connect, step1");
  4427. result = ossl_connect_step1(cf, data);
  4428. if(result)
  4429. goto out;
  4430. }
  4431. if(ssl_connect_2 == connssl->connecting_state) {
  4432. CURL_TRC_CF(data, cf, "ossl_connect, step2");
  4433. #ifdef HAVE_OPENSSL_EARLYDATA
  4434. if(connssl->earlydata_state == ssl_earlydata_await) {
  4435. goto out;
  4436. }
  4437. else if(connssl->earlydata_state == ssl_earlydata_sending) {
  4438. result = ossl_send_earlydata(cf, data);
  4439. if(result)
  4440. goto out;
  4441. connssl->earlydata_state = ssl_earlydata_sent;
  4442. }
  4443. #endif
  4444. DEBUGASSERT((connssl->earlydata_state == ssl_earlydata_none) ||
  4445. (connssl->earlydata_state == ssl_earlydata_sent));
  4446. result = ossl_connect_step2(cf, data);
  4447. if(result)
  4448. goto out;
  4449. }
  4450. if(ssl_connect_3 == connssl->connecting_state) {
  4451. CURL_TRC_CF(data, cf, "ossl_connect, step3");
  4452. result = ossl_connect_step3(cf, data);
  4453. if(result)
  4454. goto out;
  4455. connssl->connecting_state = ssl_connect_done;
  4456. #ifdef HAVE_OPENSSL_EARLYDATA
  4457. if(connssl->earlydata_state > ssl_earlydata_none) {
  4458. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4459. /* We should be in this state by now */
  4460. DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sent);
  4461. connssl->earlydata_state =
  4462. (SSL_get_early_data_status(octx->ssl) == SSL_EARLY_DATA_ACCEPTED) ?
  4463. ssl_earlydata_accepted : ssl_earlydata_rejected;
  4464. }
  4465. #endif
  4466. }
  4467. if(ssl_connect_done == connssl->connecting_state) {
  4468. CURL_TRC_CF(data, cf, "ossl_connect, done");
  4469. connssl->state = ssl_connection_complete;
  4470. }
  4471. out:
  4472. if(result == CURLE_AGAIN) {
  4473. *done = FALSE;
  4474. return CURLE_OK;
  4475. }
  4476. *done = ((connssl->state == ssl_connection_complete) ||
  4477. (connssl->state == ssl_connection_deferred));
  4478. return result;
  4479. }
  4480. static bool ossl_data_pending(struct Curl_cfilter *cf,
  4481. const struct Curl_easy *data)
  4482. {
  4483. struct ssl_connect_data *connssl = cf->ctx;
  4484. (void)data;
  4485. return connssl->input_pending;
  4486. }
  4487. static CURLcode ossl_send(struct Curl_cfilter *cf,
  4488. struct Curl_easy *data,
  4489. const void *mem,
  4490. size_t len,
  4491. size_t *pnwritten)
  4492. {
  4493. /* SSL_write() is said to return 'int' while write() and send() returns
  4494. 'size_t' */
  4495. int err;
  4496. char error_buffer[256];
  4497. sslerr_t sslerror;
  4498. int memlen;
  4499. struct ssl_connect_data *connssl = cf->ctx;
  4500. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4501. CURLcode result = CURLE_OK;
  4502. int nwritten;
  4503. (void)data;
  4504. DEBUGASSERT(octx);
  4505. *pnwritten = 0;
  4506. ERR_clear_error();
  4507. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  4508. memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
  4509. if(octx->blocked_ssl_write_len && (octx->blocked_ssl_write_len != memlen)) {
  4510. /* The previous SSL_write() call was blocked, using that length.
  4511. * We need to use that again or OpenSSL will freak out. A shorter
  4512. * length should not happen and is a bug in libcurl. */
  4513. if(octx->blocked_ssl_write_len > memlen) {
  4514. DEBUGASSERT(0);
  4515. return CURLE_BAD_FUNCTION_ARGUMENT;
  4516. }
  4517. memlen = octx->blocked_ssl_write_len;
  4518. }
  4519. octx->blocked_ssl_write_len = 0;
  4520. nwritten = SSL_write(octx->ssl, mem, memlen);
  4521. if(nwritten > 0)
  4522. *pnwritten = (size_t)nwritten;
  4523. else {
  4524. err = SSL_get_error(octx->ssl, nwritten);
  4525. switch(err) {
  4526. case SSL_ERROR_WANT_READ:
  4527. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  4528. octx->blocked_ssl_write_len = memlen;
  4529. result = CURLE_AGAIN;
  4530. goto out;
  4531. case SSL_ERROR_WANT_WRITE:
  4532. result = CURLE_AGAIN;
  4533. octx->blocked_ssl_write_len = memlen;
  4534. goto out;
  4535. case SSL_ERROR_SYSCALL: {
  4536. int sockerr = SOCKERRNO;
  4537. if(octx->io_result == CURLE_AGAIN) {
  4538. octx->blocked_ssl_write_len = memlen;
  4539. result = CURLE_AGAIN;
  4540. goto out;
  4541. }
  4542. sslerror = ERR_get_error();
  4543. if(sslerror)
  4544. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
  4545. else if(sockerr)
  4546. curlx_strerror(sockerr, error_buffer, sizeof(error_buffer));
  4547. else
  4548. curl_msnprintf(error_buffer, sizeof(error_buffer), "%s",
  4549. SSL_ERROR_to_str(err));
  4550. failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d",
  4551. error_buffer, sockerr);
  4552. result = CURLE_SEND_ERROR;
  4553. goto out;
  4554. }
  4555. case SSL_ERROR_SSL: {
  4556. /* A failure in the SSL library occurred, usually a protocol error.
  4557. The OpenSSL error queue contains more information on the error. */
  4558. sslerror = ERR_get_error();
  4559. failf(data, "SSL_write() error: %s",
  4560. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
  4561. result = CURLE_SEND_ERROR;
  4562. goto out;
  4563. }
  4564. default:
  4565. /* a true error */
  4566. failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d",
  4567. SSL_ERROR_to_str(err), SOCKERRNO);
  4568. result = CURLE_SEND_ERROR;
  4569. goto out;
  4570. }
  4571. }
  4572. out:
  4573. return result;
  4574. }
  4575. static CURLcode ossl_recv(struct Curl_cfilter *cf,
  4576. struct Curl_easy *data, /* transfer */
  4577. char *buf, /* store read data here */
  4578. size_t buffersize, /* max amount to read */
  4579. size_t *pnread)
  4580. {
  4581. char error_buffer[256];
  4582. unsigned long sslerror;
  4583. int buffsize;
  4584. struct ssl_connect_data *connssl = cf->ctx;
  4585. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4586. CURLcode result = CURLE_OK;
  4587. int nread;
  4588. (void)data;
  4589. DEBUGASSERT(octx);
  4590. *pnread = 0;
  4591. ERR_clear_error();
  4592. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  4593. buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
  4594. nread = SSL_read(octx->ssl, buf, buffsize);
  4595. if(nread > 0)
  4596. *pnread = (size_t)nread;
  4597. else {
  4598. /* failed SSL_read */
  4599. int err = SSL_get_error(octx->ssl, (int)nread);
  4600. switch(err) {
  4601. case SSL_ERROR_NONE: /* this is not an error */
  4602. break;
  4603. case SSL_ERROR_ZERO_RETURN: /* no more data */
  4604. /* close_notify alert */
  4605. if(cf->sockindex == FIRSTSOCKET)
  4606. /* mark the connection for close if it is indeed the control
  4607. connection */
  4608. CURL_TRC_CF(data, cf, "TLS close_notify");
  4609. break;
  4610. case SSL_ERROR_WANT_READ:
  4611. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  4612. result = CURLE_AGAIN;
  4613. goto out;
  4614. case SSL_ERROR_WANT_WRITE:
  4615. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  4616. result = CURLE_AGAIN;
  4617. goto out;
  4618. default:
  4619. /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
  4620. value/errno" */
  4621. /* https://docs.openssl.org/master/man3/ERR_get_error/ */
  4622. if(octx->io_result == CURLE_AGAIN) {
  4623. result = CURLE_AGAIN;
  4624. goto out;
  4625. }
  4626. sslerror = ERR_get_error();
  4627. if((nread < 0) || sslerror) {
  4628. /* If the return code was negative or there actually is an error in the
  4629. queue */
  4630. int sockerr = SOCKERRNO;
  4631. if(sslerror)
  4632. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
  4633. else if(sockerr && err == SSL_ERROR_SYSCALL)
  4634. curlx_strerror(sockerr, error_buffer, sizeof(error_buffer));
  4635. else
  4636. curl_msnprintf(error_buffer, sizeof(error_buffer), "%s",
  4637. SSL_ERROR_to_str(err));
  4638. failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d",
  4639. error_buffer, sockerr);
  4640. result = CURLE_RECV_ERROR;
  4641. goto out;
  4642. }
  4643. else if(err == SSL_ERROR_SYSCALL) {
  4644. if(octx->io_result) {
  4645. /* logging handling in underlying filter already */
  4646. result = octx->io_result;
  4647. }
  4648. else if(connssl->peer_closed) {
  4649. failf(data, "Connection closed abruptly");
  4650. result = CURLE_RECV_ERROR;
  4651. }
  4652. else {
  4653. /* We should no longer get here nowadays. But handle
  4654. * the error in case of some weirdness in the OSSL stack */
  4655. int sockerr = SOCKERRNO;
  4656. if(sockerr)
  4657. curlx_strerror(sockerr, error_buffer, sizeof(error_buffer));
  4658. else {
  4659. curl_msnprintf(error_buffer, sizeof(error_buffer),
  4660. "Connection closed abruptly");
  4661. }
  4662. failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d",
  4663. error_buffer, sockerr);
  4664. result = CURLE_RECV_ERROR;
  4665. }
  4666. goto out;
  4667. }
  4668. }
  4669. }
  4670. out:
  4671. if((!result && !*pnread) || (result == CURLE_AGAIN)) {
  4672. /* This happens when:
  4673. * - we read an EOF
  4674. * - OpenSSLs buffers are empty, there is no more data
  4675. * - OpenSSL read is blocked on writing something first
  4676. * - an incomplete TLS packet is buffered that cannot be read
  4677. * until more data arrives */
  4678. connssl->input_pending = FALSE;
  4679. }
  4680. CURL_TRC_CF(data, cf, "ossl_recv(len=%zu) -> %d, %zu (in_pending=%d)",
  4681. buffersize, result, *pnread, connssl->input_pending);
  4682. return result;
  4683. }
  4684. static CURLcode ossl_get_channel_binding(struct Curl_easy *data, int sockindex,
  4685. struct dynbuf *binding)
  4686. {
  4687. X509 *cert;
  4688. int algo_nid;
  4689. const EVP_MD *algo_type;
  4690. const char *algo_name;
  4691. unsigned int length;
  4692. unsigned char buf[EVP_MAX_MD_SIZE];
  4693. const char prefix[] = "tls-server-end-point:";
  4694. struct connectdata *conn = data->conn;
  4695. struct Curl_cfilter *cf = conn->cfilter[sockindex];
  4696. struct ossl_ctx *octx = NULL;
  4697. CURLcode result = CURLE_OK;
  4698. do {
  4699. const struct Curl_cftype *cft = cf->cft;
  4700. struct ssl_connect_data *connssl = cf->ctx;
  4701. if(cft->name && !strcmp(cft->name, "SSL")) {
  4702. octx = (struct ossl_ctx *)connssl->backend;
  4703. break;
  4704. }
  4705. cf = cf->next;
  4706. } while(cf);
  4707. if(!octx) {
  4708. failf(data, "Failed to find the SSL filter");
  4709. return CURLE_BAD_FUNCTION_ARGUMENT;
  4710. }
  4711. cert = SSL_get1_peer_certificate(octx->ssl);
  4712. if(!cert)
  4713. /* No server certificate, do not do channel binding */
  4714. return CURLE_OK;
  4715. if(!OBJ_find_sigid_algs(X509_get_signature_nid(cert), &algo_nid, NULL)) {
  4716. failf(data,
  4717. "Unable to find digest NID for certificate signature algorithm");
  4718. result = CURLE_SSL_INVALIDCERTSTATUS;
  4719. goto error;
  4720. }
  4721. /* https://datatracker.ietf.org/doc/html/rfc5929#section-4.1 */
  4722. if(algo_nid == NID_md5 || algo_nid == NID_sha1) {
  4723. algo_type = EVP_sha256();
  4724. }
  4725. else {
  4726. algo_type = EVP_get_digestbynid(algo_nid);
  4727. if(!algo_type) {
  4728. algo_name = OBJ_nid2sn(algo_nid);
  4729. failf(data, "Could not find digest algorithm %s (NID %d)",
  4730. algo_name ? algo_name : "(null)", algo_nid);
  4731. result = CURLE_SSL_INVALIDCERTSTATUS;
  4732. goto error;
  4733. }
  4734. }
  4735. if(!X509_digest(cert, algo_type, buf, &length)) {
  4736. failf(data, "X509_digest() failed");
  4737. result = CURLE_SSL_INVALIDCERTSTATUS;
  4738. goto error;
  4739. }
  4740. /* Append "tls-server-end-point:" */
  4741. result = curlx_dyn_addn(binding, prefix, sizeof(prefix) - 1);
  4742. if(result)
  4743. goto error;
  4744. /* Append digest */
  4745. result = curlx_dyn_addn(binding, buf, length);
  4746. error:
  4747. X509_free(cert);
  4748. return result;
  4749. }
  4750. size_t Curl_ossl_version(char *buffer, size_t size)
  4751. {
  4752. #ifdef LIBRESSL_VERSION_NUMBER
  4753. char *p;
  4754. size_t count;
  4755. const char *ver = OpenSSL_version(OPENSSL_VERSION);
  4756. const char expected[] = OSSL_PACKAGE " "; /* ie "LibreSSL " */
  4757. if(curl_strnequal(ver, expected, sizeof(expected) - 1)) {
  4758. ver += sizeof(expected) - 1;
  4759. }
  4760. count = curl_msnprintf(buffer, size, "%s/%s", OSSL_PACKAGE, ver);
  4761. for(p = buffer; *p; ++p) {
  4762. if(ISBLANK(*p))
  4763. *p = '_';
  4764. }
  4765. return count;
  4766. #elif defined(OPENSSL_IS_BORINGSSL)
  4767. #ifdef CURL_BORINGSSL_VERSION
  4768. return curl_msnprintf(buffer, size, "%s/%s",
  4769. OSSL_PACKAGE, CURL_BORINGSSL_VERSION);
  4770. #else
  4771. return curl_msnprintf(buffer, size, OSSL_PACKAGE);
  4772. #endif
  4773. #elif defined(OPENSSL_IS_AWSLC)
  4774. return curl_msnprintf(buffer, size, "%s/%s",
  4775. OSSL_PACKAGE, AWSLC_VERSION_NUMBER_STRING);
  4776. #else /* OpenSSL 3+ */
  4777. return curl_msnprintf(buffer, size, "%s/%s",
  4778. OSSL_PACKAGE, OpenSSL_version(OPENSSL_VERSION_STRING));
  4779. #endif
  4780. }
  4781. /* can be called with data == NULL */
  4782. static CURLcode ossl_random(struct Curl_easy *data,
  4783. unsigned char *entropy, size_t length)
  4784. {
  4785. int rc;
  4786. if(data) {
  4787. if(ossl_seed(data)) /* Initiate the seed if not already done */
  4788. return CURLE_FAILED_INIT; /* could not seed for some reason */
  4789. }
  4790. else {
  4791. if(!rand_enough())
  4792. return CURLE_FAILED_INIT;
  4793. }
  4794. /* RAND_bytes() returns 1 on success, 0 otherwise. */
  4795. rc = RAND_bytes(entropy, (ossl_valsize_t)curlx_uztosi(length));
  4796. return rc == 1 ? CURLE_OK : CURLE_FAILED_INIT;
  4797. }
  4798. static CURLcode ossl_sha256sum(const unsigned char *tmp, /* input */
  4799. size_t tmplen,
  4800. unsigned char *sha256sum /* output */,
  4801. size_t unused)
  4802. {
  4803. EVP_MD_CTX *mdctx;
  4804. unsigned int len = 0;
  4805. (void)unused;
  4806. mdctx = EVP_MD_CTX_create();
  4807. if(!mdctx)
  4808. return CURLE_OUT_OF_MEMORY;
  4809. if(!EVP_DigestInit(mdctx, EVP_sha256())) {
  4810. EVP_MD_CTX_destroy(mdctx);
  4811. return CURLE_FAILED_INIT;
  4812. }
  4813. EVP_DigestUpdate(mdctx, tmp, tmplen);
  4814. EVP_DigestFinal_ex(mdctx, sha256sum, &len);
  4815. EVP_MD_CTX_destroy(mdctx);
  4816. return CURLE_OK;
  4817. }
  4818. static bool ossl_cert_status_request(void)
  4819. {
  4820. #ifndef OPENSSL_NO_OCSP
  4821. return TRUE;
  4822. #else
  4823. return FALSE;
  4824. #endif
  4825. }
  4826. static void *ossl_get_internals(struct ssl_connect_data *connssl,
  4827. CURLINFO info)
  4828. {
  4829. /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */
  4830. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4831. DEBUGASSERT(octx);
  4832. return info == CURLINFO_TLS_SESSION ?
  4833. (void *)octx->ssl_ctx : (void *)octx->ssl;
  4834. }
  4835. const struct Curl_ssl Curl_ssl_openssl = {
  4836. { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */
  4837. SSLSUPP_CA_PATH |
  4838. SSLSUPP_CAINFO_BLOB |
  4839. SSLSUPP_CERTINFO |
  4840. SSLSUPP_PINNEDPUBKEY |
  4841. SSLSUPP_SSL_CTX |
  4842. #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
  4843. SSLSUPP_TLS13_CIPHERSUITES |
  4844. #endif
  4845. #ifdef HAVE_SSL_CTX_SET1_SIGALGS
  4846. SSLSUPP_SIGNATURE_ALGORITHMS |
  4847. #endif
  4848. #ifdef HAVE_SSL_SET1_ECH_CONFIG_LIST
  4849. SSLSUPP_ECH |
  4850. #endif
  4851. SSLSUPP_CA_CACHE |
  4852. SSLSUPP_HTTPS_PROXY |
  4853. SSLSUPP_CIPHER_LIST,
  4854. sizeof(struct ossl_ctx),
  4855. ossl_init, /* init */
  4856. ossl_cleanup, /* cleanup */
  4857. Curl_ossl_version, /* version */
  4858. ossl_shutdown, /* shutdown */
  4859. ossl_data_pending, /* data_pending */
  4860. ossl_random, /* random */
  4861. ossl_cert_status_request, /* cert_status_request */
  4862. ossl_connect, /* connect */
  4863. Curl_ssl_adjust_pollset, /* adjust_pollset */
  4864. ossl_get_internals, /* get_internals */
  4865. ossl_close, /* close_one */
  4866. ossl_close_all, /* close_all */
  4867. ossl_set_engine, /* set_engine or provider */
  4868. ossl_set_engine_default, /* set_engine_default */
  4869. ossl_engines_list, /* engines_list */
  4870. ossl_sha256sum, /* sha256sum */
  4871. ossl_recv, /* recv decrypted data */
  4872. ossl_send, /* send data to encrypt */
  4873. ossl_get_channel_binding /* get_channel_binding */
  4874. };
  4875. #endif /* USE_OPENSSL */