the code behind the vulnerability - owasp foundation€¦ · xss in asp.net core with raw html...

Post on 06-Jun-2020

41 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

TheCodeBehindTheVulnerability(v3)BarryDorrans.NETSecurityCzarhttps://idunno.org

WhoamI.NETSecurity“Czar”WhichmeansIannoyeveryoneaboutcodingsecurelyAndIgettodealwithitwhenImissthingsIalsorambleandswearontwitterinanon-workapprovedmanner@blowdart

Whatyoucanexpect7MSRCbulletinsandwhatlaybehindthem

Andafewthingswecaughtbeforetheycausedabulletin.

UnicodeandhowtoabuseitMisusingencryptionZipfilesandrunawayprocessesNaïvecertcomparisonsXSSviaURLvalidation

7TalesofMSRCCases

TheMicrosoftBulletinProcess.§Vulnerabilityreported§MSRCopencase§ProductGroupSecurityemailed

§Reproductionattempted§ReproductiontestedagainstallsupportedOS/softwareconfigurations

§Fixdeveloped§Fixtested§Bulletinwritten§Fixdeployedinternally§Bulletinandfixreleased

SecurityBulletinsHashDoS (MS11-100/CVE-2011-3141)PaddingOracle(MS10-070/CVE-2010-3332)SharePointViewState RCE(MS13-067/CVE-2013-1330)InfiniteRegexDoS (MS15-101/CVE-2015-2526)XSSinASP.NETCorewithRawHTML(CVE-2018-0784)Griefing viaCSRF(CVE-2018-0785)MalwareviaWSDL(CVE-2017-8759)

HashDoS (CVE-2011-3141)ADenialofServicecausedbyparsingFORMinputs.CausedbyHashTable andDictionaryusingapredictablehashalgorithmforstringkeys.Fixedbyswitchinghashfunctionstoonethatisunpredictableorlimitingdictionarysize.

HashDoS explainedAllformfieldsbeginningwithAwouldgointoslotA.

Togetavaluebackyougototheslotandlookthrougheverything.ThemoreAfieldstherearethelongerittakes.

IfyoucanforceeverythingintoasingleslotthenlookupswilltakemoreandmoreCPUwhichleadstoDoS.Originallypresentedat28c8(28thChaosCommunicationCongress)2011.Alexander“alech”KlinkandJulian“zeri”Wälde exploitedPHP,Java,Python,JavaScript.

DIYHashDoSDictionary<TKey>fixonlyappliestostringkeys.Ifyouallowuserinputintoahashbasedcollectionwhichhasakeywhichisn’tstringandyourGetHashCode()algorithmforthekeyclassispredictablethenyouarevulnerable…

HashDOSDemo

HowcanIfixthis?Don’tuseuserinputaskeysindictionariesunlessTheuserinputisastringORTheHashCode fortheinputisstrongandyouimplementasessionkey;eg.SHA1HMACwitharandomkeysetatruntime.

PaddingOracle(CVE-2010-3332)Informationdisclosureviacryptographicattack.Anendpointwasexposedwhichvalidatedifastringwasencryptedcorrectly.Theattackercouldusetheyesornoresulttobuildproperlyencryptedstringswithoutknowingthekey.Thisthenallowedforgedrequeststoscriptresource.axd andserveupanyfileinthewebapplication,likeweb.config,whichcontainsmachinekeys,whichyoucanforgeauth ticketswith.Fixedbyhavingscriptresource.axd validatesignaturesandserveJSonly.

PaddingOracleExplainedEncrypteddataisoftenpaddedtomeetalgorithmrequirements.Sidechannelattackcanbeusedtodiscoverthepaddingiscorrect.Thiscanthenleadtofastdecryption– youtweakasinglebyteandask“Isthispaddingcorrect?”.Fromthereyoucancalculatetheoriginalcharacter.OriginallypresentedatEUROCRYPT2002,SergeVaudenay againstCBCmodeinSSL,IPSEC

ExpandedtoASP.NETbyThaiDuong,JulianoRizzoatIEEESymposiumonSecurityandPrivacy2011.

HowcanIfixthis?Don’texposepaddingoracles.Addaauthenticatedsignaturetotheencrypteddata,andvalidateit.

SharePointViewState RCE(CVE-2013-1330)RemotecodeexecutionviaSerialization.MadepossiblebySharePointdisablingViewState MAC.FixedbyturningViewState MACon.DiscoveredbyAlexandreHerzog,presentedatArea41in2013.ExpandedbyAlexandretodemonstrateRCEifmachinekeyisknown.Expandsonaremoting exploitdiscoveredbyJamesForshawandpresentedatBlackHat2012.

RCEviaViewStateViewState is,bydefault,signed.Ifitisnotsigned,orthesigningkeyisknownyoucanforgeViewState tocontainarbitraryobjects.ViewState isimplicitlytrustedandobjectsembeddedinitgetcreatedwhenit’sparsed.

DeletingfileswithViewState.NETcontainsaTempFileCollection classwhichisserializable.SerializableclassescanbestoredinViewStateTheclasscleansupfileswhentheclassisGCed.Youcouldsetthefilenamesinthecollectionfromaserializedrepresentation…

Viewstate /SerializationDemo

HowcanIfixthis?Whenyouroundtripstatetoausercontrolledspacesignthedata.Don’tpublishyoursigningkey.

InfiniteRegex(CVE-2015-2526)DoS againstvalidatorswithcraftedinput.MadepossibleduetoabacktrackingRegexand.NETnotputtingatimeoutonregularexpressionsbydefault.Fixedbyaddingtimeouts.DiscoveredbyRobertoSuggi,reportedinApril2015.

InfiniteRegexDemo

HowcanIfixthis?Findabetterwaytovalidatethanregularexpressions.Settimeoutsonallregularexpressions.Setaglobalregextimeout.AppDomain.CurrentDomain.SetData(

"REGEX_DEFAULT_MATCH_TIMEOUT",

TimeSpan.FromSeconds(1));

XSSinASP.NETCore(CVE-2018-0784)MVCencodeseverypieceofoutputbydefault.Exceptwhenyoutellitnotto.Andwetolditnotto.Whichwouldhavebeenok…but…DiscoveredbyKévinChalet,reportedin2017.

XSSviaOverbindingDemo

HowcanIfixthis?Don’tuseHtml.Raw.Searchyourcodeforit.Forthingsshouldnevercomefromuserinputapply[BindNever].Ifsomethingisgeneratedserverside,alwaysgenerateserverside,stopputtingitinahiddenfieldtotransportitbetweenrequests.

CSRFinASP.NETCore(CVE-2018-0785)CSRFallowsanothersitetoactonbehalfofaloggedinuser.ASP.NETCoreMVCautomaticallyaddstokenstoallHTMLformstopreventthis.Whichdoesn’thelpwhenit’snotaform.DiscoveredbyKévinChalet,reportedin2017.

HowcanIfixthis?GETshouldbeidempotent.(ResubmittingaGETshouldn’tchangetheresults)WhenyouchangestateuseaPOST.

WSDLabuse(CVE-2017-8759)Nationstateattack.WSDLismetadataforSOAPendpoints.Usedtogenerateproxyobjects.Didyouknow.NETFrameworkhasaWSDLparserwhichgeneratescode?DiscoveredbyFireEye,reportedin2017.

WSDLabuse(CVE-2017-8759)IsValidUrl()insidetheparserhadabug.ThisenabledanationstatetargetingRussianspeakersinanotherEasternEuropecountrytocompilecodeontheirmachine.ItwasactivatedviaWord’sSOAPmonikerfunctionalitythatstartsoff.NETwithnouserinteraction,parsesWSDLandthencanconnecttoaSOAPendpoint.

HowcanIfixthis?Don’tbeacountryRussiawantstoinvade(orhaspartiallyinvaded).Don’teverwritecodethatgeneratescodefromuserinput,thencompilesandrunsit.

Mistakeswe’veseen

BadencodingWhat’swrongwith?string.Format(

"onmouseover=\"DisplayTooltip('Issue: {0}');\"" +"onmouseout=\"DisplayTooltip('');\"",HttpUtility.HtmlEncode(d["Title"]);

EncodingiscontextspecificandhardtogetrightonceJavaScriptisinvolved.BettertosetthevalueinaDIVHTMLEncodedthenpulloutcontents.<div data-stuff="{@Title}" />

IİCaptainWhatwillthefollowingprint?const string input = "interesting";bool comparison = input.ToUpper() == "INTERESTING";Console.WriteLine("These things are equal: " + comparison);

Peoplemakesecuritydecisionsbasedonstringcomparisons.Usestring.Compare(a, b, StringComparison.OrdinalIgnoreCase)There’sacodeanalysisruleforthis– CA1309

TurkishIDemo

It’snotjustTurkeyIfyouhaveaCultureInfo ofth_TH.UTF8StartsWith(".") crashesaprocessonMac&LinuxbecauseThaihasnopunctuationmarks.ISO/IEC14651:http://unicode.org/L2/L2006/06105-02n3847-14651-2001-fdam3.pdf (AnnexC2.1)

“Nosyllablestructureorwordboundaryanalysisisrequired,asThailexiconsareorderedalphabetically,notphonetically.NotethatThainormallydoesnotuseanywordseparator,except,andexceptionally,zerowidthspace.“

Wide<Unicodehas“fullwidth”characters<becomes<< is&#xfeff;&#xff1c;Browsersignorethis,so<script> isn’tXSSHoweverifput< intoaSQLvarchar fielditgetsconvertedto<AndnowyouhavepersistedXSSSodon’tuseanonUnicodecolumntostoreUnicodecharacters.(Anddon’ttrustdatacomingfromSQL– HtmlEncode it!)

Commoncryptographymistakes“Thisisbase64encrypted.”“Ihavethisgreatnewalgorithm.”Key/IVreuse– whenadocument/resourcechanges,changeKey/IV.Keyshavepurposes.Don’treusekeysacrosspurposes.Encrypteddatamusthavemessageauthentication.Hashedcombinedstringerrorsbuiltin+securely == built+insecurelyPreferhash(len(a) + hash(a) + len(b) + hash (b))Certificateverificationbyhostnamealone.

PathTransversalFileupload– RFC1867The original local file name may be supplied as well, either as a 'filename' parameter either of the 'content-disposition: form-data' header or in the case of multiple files in a 'content-disposition:file' header of the subpart.

Ofcourseifyouedittherequestbeforeitleavesthebrowser…Useauniquename.Generateityourself.Ifyouhavetokeepitusesomethinglikestring filename =

System.IO.Path.GetFileName(userProvidedFileName);string fullPath = Server.MapPath(

System.IO.Path.Combine(@"d:\inetpub\inbound\",filename));

ZipbombsWhenacceptinguserfilesforparsingit’seasytoevil.Zipbombs– tinyfilewhichrecursivelyuncompresses.e.g.42.zip- zipfileconsistingof42kilobytesofcompresseddata,containingfivelayersofnestedzipfilesinsetsof16,eachbottomlayerarchivecontaininga4.3gigabytefileforatotalof4.5petabyteswhenuncompressed.

BillionlaughsXMLhasthesameproblem.BillionLaughsdefines10entities,eachofwhichisdefinedasconsistingof10ofthepreviousentitiesetc.thedocumentbeingasingleinstanceofthelargestentity,whichcontainsonebillioncopesofthefirstentity.<?xml version="1.0"?><!DOCTYPE lolz [<!ENTITY lol "lol"><!ELEMENT lolz (#PCDATA)><!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"><!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;"><!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;"><!ENTITY lol4 "&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;"><!ENTITY lol5 "&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;"><!ENTITY lol6 "&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;"><!ENTITY lol7 "&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;"><!ENTITY lol8 "&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;"><!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;">

]><lolz>&lol9;</lolz>

PreventablebyturningoffDTDParsing

Thingswedoforyouandacoupleofthingswedon’t.

Opt-intoprotectionsBackcompat meansyouneedtoopt-intocertainbreakingchanges.TooptintoASP.NET4.5behaviors,setthefollowinginweb.config<machineKey compatibilityMode="Framework45" />

Or(whichiswhattheASP.NET4.5projecttemplatesdo)<httpRuntime targetFramework="4.5" />

Stringhashcode randomisationTohelpagainstHashDOS wecanrandomizehashcodes.Wedon’tdothisbydefaultinthe.NETFrameworkbecausepeoplesavehashcodes eventhoughweneverpromisedthey’dbeconstant.

<configuration><runtime><UseRandomizedStringHashAlgorithm enabled=1 />...

</runtime></configuration>

DataProtectorASP.NET4.5introducesMachineKey.Protect andUnprotectThisreplacesEncodeandDecodewhichallowedadevelopertochoosebetweenSign,EncryptorBoth.It’snowalwaysboth.Aimedatephemeraldata.ASP.NETCorereplacesitwithDataProtector

StopusingthisPartialTrust-https://support.microsoft.com/kb/2698981RequestValidationMachineKey.Encode &MachineKey.Decodehttp://www.asp.net/aspnet/overview/web-development-best-practices/what-not-to-do-in-aspnet,-and-what-to-do-instead#security

Breakingpartialtrustdemo

Thescarydemo

InsummarySignyourdata,evenwhenit’sencryptedDon’tuseregularexpressionsDon’tuseBinaryFormatterDon’toverbindUsetherightverbOpt-intonewprotections

©2015MicrosoftCorporation.Allrightsreserved.Microsoft,Windows,andotherproductnamesareormayberegisteredtrademarksand/ortrademarksintheU.S.and/orothercountries.TheinformationhereinisforinformationalpurposesonlyandrepresentsthecurrentviewofMicrosoftCorporationasofthedateofthispresentation.BecauseMicrosoftmustrespondtochangingmarketconditions,itshouldnotbeinterpretedtobeacommitmentonthepartofMicrosoft,andMicrosoftcannotguaranteetheaccuracyofanyinformationprovidedafterthedateofthispresentation.MICROSOFTMAKES NO WARRANTIES,EXPRESS,IMPLIEDORSTATUTORY,ASTOTHEINFORMATIONINTHISPRESENTATION.

top related