openssl.c 158 KB

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