Program hijacking - Rutgers CS
文章推薦指數: 80 %
The best-known set of attacks are based on buffer overflow. ... The function then adjusts the stack pointer to make room for hold local ... ProgramHijacking Programhijackingreferstotechniquesthatcanbeusedtotakecontrol ofaprogramandhaveitdosomethingotherthanwhatitwasintendedto do.Oneclassoftechniquesusescodeinjection,inwhichan adversarymanagestoaddcodetotheprogramandchangethe program’sexecutionflowtorunthatcode. Thebest-knownsetofattacksarebasedonbufferoverflow. Bufferoverflowistheconditionwhereaprogrammerallocatesa chunkofmemory(forexample,anarrayofcharacters)butneglects tocheckthesizeofthatbufferwhenmovingdataintoit. Datawillspilloverintoadjacentmemoryandoverwritewhatever isinthatmemory. LanguagessuchasC,C++,andassembleraresusceptibleto bufferoverflowssincethelanguagedoesnothaveameansof testingarraybounds.Hence,thecompilercannotgeneratecode tovalidatethatdataisonlygoingintotheallocatedbuffer.Forexample, whenyoucopyastringusingstrcpy(char*dest,char*src),you passthefunctiononlysourceanddestinationpointers.The strcpyfunctionhasnoideahowbigeitherofthebuffersare. Stack-basedoverflows Whenaprocessruns,theoperatingsystem’sprogramloader allocatesaregionfortheexecutablecodeandstaticdata(called thetextanddatasegments),aregionforthestack, andaregionfortheheap(usedfordynamicmemory allocation,suchasbymalloc). Justbeforeaprogramcallsafunction,itpushes thefunction’sparametersonto thestack.Whenthecallis made,thereturnaddressgetspushedonthestack. Onentrytothefunctionthatwascalled, thefunctionpushesthecurrentframepointer (aregisterintheCPU) onthestack,which formsalinkedlisttothepreviousframepointerandprovides aneasywaytorevertthestacktowhereitwasbeforemakingthe functioncall.Theframepointerregisteristhenset tothecurrenttopofthestack. Thefunctionthenadjuststhestackpointertomakeroom forholdlocalvariables,whichliveonthestack. Thisregionforthefunction’slocaldataiscalledthestackframe. Ensuringthatthestackpointerisalwayspointing tothetopofthestackenablesthefunctiontogetinterrupts orcallotherfunctionswithoutoverwriting anythingusefulonthestack. Thecompilergeneratescodeto referenceparametersandlocal variablesasoffsetsfromthecurrentframepointerregister. Beforeafunctionreturns,thecompilergeneratescodeto: Adjustthestackbacktopointtowhereitwasbeforethestackexpandedtomakeroomforlocalvariables.Thisisdonebycopyingtheframepointertothestackpointer. Restorethepreviousframepointerbypoppingitoffthestack(sothatlocalvariablesforthepreviousfunctioncouldbereferencedproperly). Returnfromthefunction.Oncethepreviousframepointerhasbeenpoppedoffthestack,the stackpointerpointstoalocationonthestackthatholdsthereturnaddress. Simplestackoverflows Localvariablesareallocatedonthestackandthestackgrowsdownwardinmemory.Hence,thetopofthestackisinlowermemorythanthestart,orbottom, ofthestack.Ifabuffer(e.g.,charbuf[128])isdefinedasalocalvariable, itwillresideonthestack.Asthebuffergetsfilledup,itscontents willbewrittentohigherandhighermemoryaddresses.Ifthebuffer overflows,datawillbewrittenfurtherdownthestack(inhighermemory), overwritingthe contentsofanyothervariablesthatwereallocatedforthatfunction andeventuallyoverwritingthesavedframepointerandthesaved returnaddress. Whenthishappensandthefunctiontriestoreturn,thereturnaddress thatisreadfromthestackwillcontaingarbagedata,usuallya memoryaddressthatisnotmappedintotheprogram’smemory. Assuch,theprogramwillcrashwhenthefunctionreturnsandtriesto executecodeatthatinvalidaddress.Thisisanavailabilityattack. Ifwecanexploitthefactthataprogramdoesnotcheckthebounds ofabufferandoverflowsthebuffer,wecancauseaprogramtocrash. Subvertingcontrolflowthroughastackoverflow Bufferoverflowcanbeusedinamoremaliciousmanner. Thebufferitselfcanbefilledwithbytesofvalidmachinecode. Iftheattackerknowstheexactsizeofthebuffer,shecanwrite justtherightnumberofbytestowriteanewreturnaddressinto theverysameregionofmemoryonthestackthatheldthereturnaddress totheparentfunction.Thisnewreturnaddresspointstothe startofthebufferthatcontainstheinjectedcode.When thefunctionreturns,itwill“return”tothenewcodeinthebuffer andexecutethecodeatthatlocation. Off-by-onestackoverflows Aswesaw,bufferoverflowoccursbecauseofprogrammingbugs:the programmerneglectedtomakesurethatthedatawrittento abufferdoesnotoverflow.Thisoftenoccursbecausethe programmerusedold,unsafefunctionsthatdonot allowtheprogrammertospecifylimits.Commonfunctions include: -strcpy(char*dest,char*src) -strcat(char*dest,char*src) -sprintf(char*format,...) Eachofthesefunctionshasasafecounterpartthataccepts acountparametersothatthefunctionwillnevercopymorethan countnumberofbytes: -strcpy(char*dest,char*src,intcount) -strcat(char*dest,char*src,intcount) -sprintf(char*format,intcount,...) You’dthinkthiswouldputanendtobufferoverflowproblems. However,programmersmaymiscountortheymaychoose towritetheirownfunctionsthatdonotcheckarrayboundscorrectly. Acommonerrorisanoff-by-oneerror.Forexample,aprogrammer maydeclareabufferas: charbuf[128]; andthencopyintoitwith: for(i=0;i<=128;i++) buf[i]=stuff[i]; Theprogrammerinadvertentlyuseda<=comparisoninsteadof<. withoff-by-oneboundschecking maliciousinputcanoverwritethereturnaddressonthe stack:thecopyoperationwouldstopbeforethattime. however allocatedonthestack onebyteofthesavedframepointer. thepotentialfordamagedependsverymuchonwhatthe valueofthatsavedframepointerwasandhowthe compilergeneratescodeformanagingthestack.intheworstcase itcouldbesetuptoavaluethatis255byteslowerinmemory. iftheframepointerismodified returnnormally.however popstheframepointerfromthestacktorestorethe savedvalueofthecallingfunction wascorruptedbythebufferoverflow. nowtheprogramhasamodifiedframepointer. recallthatreferencestoafunction expressedasoffsetsfromthecurrentframepointer. anyreferences tolocalvariablesmaynowbereferencestodatainthe buffer.moreover willupdateitsstackpointertothisbufferareaand returntoanaddressthattheattackerdefined. heapoverflows notalldataisallocatedonthestack:onlylocalvariables. globalandstaticvariablesareplacedinaregionofmemory rightabovetheexecutableprogram.dynamicallyallocated memory ofmemorycalledtheheap.ineithercase isnotthestack thereisnoabilityforabufferoverflowattacktooverwrite returnaddresses. wearen causedatatospilloverintohighermemoryaddressesabove thebufferthatmaycontainothervariables.iftheattacker knowstheorderinwhichvariablesareallocated whiletheseoverwriteswillnotchangeareturnaddress theycanchangethingssuchasfilenames orlinkedlists.someprogramsmakeextensiveuseoffunction pointers suchaslinkedlistsonaheap.ifabuffer overflowcanoverwriteafunctionpointerthenitcanchange theexecutionoftheprogram:whenthatfunctioniscalled controlwillbetransferredtoalocationoftheattacker choosing. ifwearen start instructionspriortotheinjectedcode.iftheprocessorjumps anywhereinthatregionofmemory nopinstructionsuntiliteventuallyreachestheinjectedcode. thisiscalleda nopslide formatstringattackswithprintf thefamilyofprintffunctionsarecommonlyusedincandc tocreateformattedoutput.theyacceptaformatstringthat defineswhatwillbeprinted directivesforparameters.forexample printf willprintastringsuchas value="01234" ifthevalueofvis1234. readingarbitrarymemory occasionally forinstance toastring.thislocalvariablemaybeoverwrittenbyabufferoverflow attacktopointtoadifferentstring. itisalsocommon ifsisastringthatisgeneratedbytheattacker containunexpectedformattingdirectives. notethatprintftakes avariablenumberofargumentsandmatcheseach enoughparameterspassedtoprintf itassumestheyareonthestackandwillhappilyreadwhatevervalue isonthestackwhereitthinkstheparametershouldbe. thisgivesanattackertheabilitytoreadarbitrarilydeepintothe stack.forexample printfwillexpectfourparameters readthenextfourvaluesthatareonthetopofthestackandprinteachofthose integersasan8-character-longhexadecimalvalueprefixedwithleading zeros writingarbitrarymemory theprintffunctionalsocontainsasomewhatobscureformattingdirective: unlikeother itwritesthenumberofcharactersthatithasoutputthusfar.forexample willstorethenumber4 anattackerwhocanchangetheformatspecifiermaybeabletowriteto arbitrarymemory.each tolookforthenextvariableinthenextslotinthestack.hence formatdirectivessuchas lengthofanint thefollowinglocationonthestack.thus canskipthroughanynumberofbytesonthestackuntilwegettotheaddress wherewewanttomodifyavalue.atthatpoint formatstring ofbytesthatwereoutput. wecanpreciselycontrolthevaluethatwillbewritten byspecifyinghowmanybytesareoutputaspartoftheformatstring. forexample takeup55 wecanchangethecountthatwillbewrittenwith whatprintfactuallyprints avaluewecareabout defenseagainsthijackingattacks betterprogramming hijackingattacksaretheresultofsloppyprogramming:alackofbounds checkingthatresultsinoverflows.theycanbeeliminatediftheprogrammer neverusesunsafefunctions iscarefulaboutoff-by-oneerrors. aprogramercanuseatechniquecalledfuzzingtolocatebufferoverflow problems.wheneverastringcanbeprovidedbytheuser extremelylongstringswithwell-definedpatterns crashesbecauseabufferoverflowdestroyedareturnaddressonthestack theprogrammercanthenloadthecoredumpintoadebugger theprogramcrashedandsearch forasubstringoftheenteredpattern affected. bufferoverflowscanbeavoidedbyusinglanguageswithstrongertype checkingandarrayboundschecking.languagessuchasjava checkarraybounds.candc toavoidusingcorc tightspecificationofrequirements constructingtestsbasedonthoserequirementshelpsavoidbufferoverflow bugs.ifinputlengthsarespecified andchecked.documentationshouldbeexplicit programmersoftenmakeimplicitassumptionsthattheynevercheckforbecauseitseemsinconceivablethatauserwoul deverdosomething.forinstance evendatathatmaynotbeenteredbyausermightcauseproblems. in2022 dataexecutionprevention bufferoverflowsaffectdataareas:eitherthestack thereisusuallynoreasonthatthoseregionsofcodeshouldcontainexecutablecode. hence memorymanagementunit permissionformemorypagesinthoseregions. thiswasnotpossiblewithearlyinteloramdprocessors:theirmmudidnot supportenablingordisablingexecutepermissions.allmemorycould containexecutablecode.thatchangedin2004 addedannx architectures operatingsystemsupportfollowed. windows depcannotalwaysbeused.someenvironments interpretersactuallydoneedexecutionenabledintheirstackand someenvironmentsneedexecutablecodeintheirheapsection loading attacks depattacks attackerscameupwithsomecleversolutionstodefeatdep. thefirstoftheseiscalledreturn-to-libc bufferoverflowsstillallowustocorruptthestack.wejust cannotexecutecodeonthestack.however alotofcodesittingintheprogramandthelibrariesituses. insteadofaddingcodeintothebuffer overflowsabuffertocreateanewreturnaddressand parameterlistonthestack.whenthefunctionreturns itswitchescontroltothenewreturnaddress.this returnaddresswillbeanaddressinthestandardclibrary whichcontainsfunctionssuchasprintf frontendstosystemcalls.allthatanattackeroftenneedsto doistopushparametersthatpointtoastringinthebuffer thatcontainsacommandtoexecuteandthen libcsystemfunction asashellcommand. amoresophisticatedvariantofreturn-to-libcis returnorientedprogramming returnorientedprogrammingissimilartoreturn-to-libc butrealizesthatexecutioncanbranchtoanyarbitrarypoint inanyfunctioninanyloadedlibrary.thefunctionwill executeaseriesofinstructionsandeventuallyreturn. theattackerwilloverflowthestackwith datathatnowtellsthisfunctionwhereto itsreturncanjumptoyetanotherarbitrarypointinanother library.whenthatreturns directedtoanaddresschosenbytheintruderthat hasbeenplacedfurtherdownthestack localvariables therearelotsandlotsofreturninstructionsamong allthelibrariesnormallyusedbyprograms. eachofthesetailendsofafunctioniscalledagadget. ithasbeen demonstratedthatusingcarefullychosengadgets allowsanattackertopushastringofreturnaddressesthat willenabletheexecutionofarbitraryalgorithms. tomakelifeeasierfortheattacker createdthatsearchthroughlibrariesandidentify usefulgadgets.aropcompilerthenallowstheattackerto programoperationsusingthesegadgets. addressspacelayoutrandomization stackoverflowattacksrequireknowingandinjectingan addressthatwillbeusedas atargetwhenafunctionreturns.ropalsorequires knowingaddressesofalltheentrypointsofgadgets. isatechniquethatwasdevelopedtohavetheoperatingsystem loaderpickrandomstartingpointsfortheexecutable program sincecodeanddataresidesindifferentlocationseach timetheprogramruns bufferoverflowswithusefulknownaddresses. foraslrtowork compiledtousepositionindependentcode whichusesrelativeoffsetsinsteadofabsolutememory addresses. stackcanaries astackcanaryisacompilertechniquetoensurethat afunctionwillnotbeallowedtoreturnifabufferoverflow tookplacethatmayhaveclobberedthereturnaddress. atthestartofafunction thecompileraddscodetogeneratearandominteger andpushitontothestackbeforeallocatingspacefor thefunction thecanarysitsbetweenthereturnaddressandthesevariables.if thereisabufferoverflowinalocalvariablethattriestochange thereturnaddress ofthecanary. thecompilergeneratescodetohavethefunction checkthatthecanaryhasavalidvaluebeforereturning.ifthe valueofthecanaryisnottheoriginalvaluethenabufferoverflow occurredandit thevalueofthecanaryorthereturnaddress.considerafunction thathastwolocalarrays stackwithinthesamestackframe.ifarrayaisinlowermemory thanarraybthenanoverflowinacanaffectthecontentsofb. dependingonthecode thesamethingcanhappenwithscalarvariables instance followedbyanarray.anoverflowinthearraycanchangethevalue oftheintegerthat this.eveniftheoverflowhappenedtoclobberthereturnvalueas well meanwhile tochangealsoalteredthebehaviorofthefunction. stackcanariescannotfixthisproblemingeneral.however compiler cantakestepstoensurethatabufferoverflowcannotoverwrite non-arrayvariables arraysfirst compilercanmakesurethatabufferoverflowinanarraywillnot changethevalueofscalarvariables.onearrayoverflowingto anotherisstillarisk variablesthatcontainvaluesthatdefinethecontrolflowofa function. intelcontrol-flowenforcementtechnology in2020 thisaddstwonewprotectionmechanismstotheprocessor. overflowingthebufferofalocalvariablecanmodifythereturnaddressofafunction.thisisbecauselocalvariables sharethesamestackasreturnaddresses. withcet itisprotectedfromtamperingbyanextraprotectionattributeintheprocessor bufferoverflowsonthemainstackcannottouchtheshadowstackandthuscannotchangethecontrolflow. whentheprocessorexecutesareturninstruction thesecondfeatureintelintroducediscalledindirectbranchtracking. thiswasdesignedtorestrictaprogram ajumptableisatableofmemorylocationstowhichaprogrambranch.itiscommonlyusedforoperationssuchasimplemen tingswitchstatementsandlookuptables.jumptablesarelistsofindirectbranches.whenimplementedinc anattackrelatedtoreturnorientedprogrammingisjumporientedprogramming indirectbranchtrackingaddsanewendbranchinstructiontoallowaprogrammertospecifyvalidtargetsforindirect jumpsorcallsinaprogram.anindirectbranchmustjumptoanendbranchinstruction.ifahijackedprogramforcesabra nchtosomeotherlocation homepage maincoursepage syllabus announcements homework documents gradinginfo canvas courseinfo aboutthecourse prerequisistes thingsyouneed classrules forquestionsorcommentsaboutthissite gro.kp>
延伸文章資訊
- 1Function pointer - Wikipedia
- 2Function Pointers in C and C++ - Cprogramming.com
- 3Program hijacking - Rutgers CS
The best-known set of attacks are based on buffer overflow. ... The function then adjusts the sta...
- 4Jump Tables via Function Pointer Arrays in C/C++
Here's a look at the use of arrays of function pointers in C/C++ as jump ... the function that us...
- 5Am not able to call C++ function pointers from inline assembly
Stack Overflow for Teams – Start collaborating and sharing organizational knowledge. Create a fre...