Upload
thanh-huong
View
221
Download
0
Embed Size (px)
Citation preview
7/29/2019 02 Ctrl Hijacking
1/58
ControlHijackin
BasicControHijackingA5
7/29/2019 02 Ctrl Hijacking
2/58
Controlhijackinga5acks A5ackersgoal:
Takeovertargetmachine(e.g.webserve Executearbitrarycodeontargetby
hijackingapplicaFoncontrolflow
Examples. Bufferoverflowa5acks Integeroverflowa5acks ormatstringvulnerabiliFes
7/29/2019 02 Ctrl Hijacking
3/58
Example1:bufferoverflows
ExtremelycommonbuginC/C++programs. irstmajorexploit:1988InternetWorm.fingerd.
0
100
200
300
400
500
600
1995 1997 1999 2001 2003 2005
Source:
20%ofa200-200
7/29/2019 02 Ctrl Hijacking
4/58
Whatisneeded UnderstandingCfuncFons,thestack,andtheheap. Knowhowsystemcallsaremade Theexec()systemcall A5ackerneedstoknowwhichCPUandOSusedonthetar
Ourexamplesareforx86runningLinuxorW DetailsvaryslightlybetweenCPUsandOSs:
Li5leendianvs.bigendian(x86 vs. Motorola) Stackramestructure(Unixvs.Windows)
7/29/2019 02 Ctrl Hijacking
5/58
Linuxprocessmemorylayo
unused 0x08048000
runFmeheap
sharedlibraries
userstack
0x40000000
0xC0000000
%esp
brk
Loaded
fromexec
0
7/29/2019 02 Ctrl Hijacking
6/58
excepFonhandlers
Stackrame
arguments
returnaddress
stackframepointer
localvariables
SP
SGr
high
low
calleesavedregisters
7/29/2019 02 Ctrl Hijacking
7/58
Whatarebufferoverflows
void func(chchar buf[
strcpy(bu
do-someth
}
SupposeawebservercontainsafuncFon:
Whenfunc()iscalledstacklookslike:
argument:str
returnaddressstackframepointer
charbuf[128]
SP
7/29/2019 02 Ctrl Hijacking
8/58
Whatarebufferoverflows
void func(ch
char buf[
strcpy(bu
do-someth
}
Whatif*stris136byteslong?
Aerstrcpy:
argument:str
returnaddressstackframepointer
charbuf[128]
SP
*str Problem:
nolengthchec
7/29/2019 02 Ctrl Hijacking
9/58
charbuf
returna
Basicstackexploit
Suppose*strissuchthat
aerstrcpystacklookslike:
ProgramP:exec(/bin/sh)
Whenfunc()exits,theusergetsshell!
Note:a5ackcodePrunsinstack.
(exact shell code by Aleph One)
Progra
7/29/2019 02 Ctrl Hijacking
10/58
TheNOPslide
Problem:howdoesa5ackerdetermineret-address?
SoluFon:NOPslide
Guessapproximatestackstatewhenfunc()iscalled
InsertmanyNOPsbeforeprogramP:nop,xoreax,eax,incax
charbuf
returna
NOPS
Progra
7/29/2019 02 Ctrl Hijacking
11/58
Detailsandexamples SomecomplicaFons:
ProgramPshouldnotcontainthe\0charact Overflowshouldnotcrashprogrambeforefunc
Sampleremotestacksmashingoverflows: (2007)OverflowinWindowsanimatedcursors(ANI). (200)OverflowinSymantecVirusDetecFon
test.GetPrivateProfileString "file", [long string]
7/29/2019 02 Ctrl Hijacking
12/58
ManyunsafelibcfuncFon
strcpy(char*dest,constchar*src)
strcat(char*dest,constchar*src)
gets(char*s)
scanf(constchar*format,)andmanymore.
Safelibcversionsstrncpy(),strncat()aremisleadin e.g.strncpy()mayleavestringunterminated.
WindowsCrunFme(CRT): strcpy_s(*dest,DestSize,*src):ensurespropert
7/29/2019 02 Ctrl Hijacking
13/58
BufferoverflowopportuniFe
ExcepFonhandlers:(WindowsSEHa5acks) OverwritetheaddressofanexcepFonhandlerin
uncFonpointers:(e.g.PHP4.0.2,MSMediaPlayerBitmaps)
OverflowingbufwilloverridefuncFonpointer. Longjmpbuffers:longjmp(pos)(e.g.Perl.003)
Overflowingbufnexttoposoverridesvalueofpo
He
ostbuf[128] uncPtr
7/29/2019 02 Ctrl Hijacking
14/58
CorrupFngmethodpointe
CompilergeneratedfuncFonpointers(e.g.C++code)
Aeroverflowofbuf:
ptr
data
ObjectT
P1P2P3
vtable
method#1
method#2
method#3
ptr
buf[26]
obj
vtable
NOP
slide
7/29/2019 02 Ctrl Hijacking
15/58
indingbufferoverflows
Tofindoverflow:RunwebserveronlocalmachineIssuemalformedrequests(endingwith$$$$$)
Manyautomatedtoolsexist(calledfuzzersne
Ifwebservercrashes,searchcoredumpfor$$$$$tofindoverflowl
Constructexploit(noteasygivenlatestdefenses)
7/29/2019 02 Ctrl Hijacking
16/58
ControlHijackin
MoreControHijackingA5
7/29/2019 02 Ctrl Hijacking
17/58
MoreHijackingOpportuniF
Integeroverflows:(e.g. MS DirectX MIDI Lib) Doublefree:doublefreespaceonheap.
Cancausememorymgrtowritedatatospecificl Examples:CVSserver
Format string vulnerabilities
7/29/2019 02 Ctrl Hijacking
18/58
IntegerOverflows(seePhrack
Problem:whathappenswhenintexceedsmaxvalue?
intm;(32bits)shorts;(16bits)char
c=0x80+0x80=128+128 c=0
s=0xff80+0x80 s=0
m=0xffffff80+0x80 m=0
Canthisbeexploited?
A l
7/29/2019 02 Ctrl Hijacking
19/58
Anexamplevoidfunc(char*buf1,*buf2,unsignedintlen1,len2){
char temp[256];
if (len1 + len2 > 256) {return -1} // length c
memcpy(temp, buf1, len1); // cat buff
memcpy(temp+len1, buf2, len2);
do-something(temp); // do stuff
}
Whatiflen1=0x80,len2=0xffffff80
len1+len2=0
Secondmemcpy()willoverflowheap!!
7/29/2019 02 Ctrl Hijacking
20/58
0
20
40
60
80
100
120
140
1996 1998 2000 2002 2004 2006
Sou
Integeroverflowexploitsta
7/29/2019 02 Ctrl Hijacking
21/58
ormatstringbugs
bl
7/29/2019 02 Ctrl Hijacking
22/58
ormatstringproblem int func(char *user) {
fprintf( stderr, user);
}
Problem:whatif*user = %s%s%s%s%s%s%
Mostlikelyprogramwillcrash:DoS. Ifnot,programwillprintmemorycontents. ullexploitusinguser=%n
Correct form: fprintf( stdout, %s, user
i
7/29/2019 02 Ctrl Hijacking
23/58
History
irstexploitdiscoveredinJune2000. Examples:
wu-pd2.*: remoterootLinuxrpc.statd: remoterootIRIXtelnetd: remoterootBSDchpass: localroot
7/29/2019 02 Ctrl Hijacking
24/58
VulnerablefuncFonsAnyfuncFonusingaformatstring.
PrinFng:
prin},fprin},sprin},
vprin},vfprin},vsprin},
Logging:
syslog,err,warn
7/29/2019 02 Ctrl Hijacking
25/58
Exploit Dumpingarbitrarymemory:
WalkupstackunFldesiredpointerisfound. prin}(%08x.%08x.%08x.%08x|%s|)
WriFngtoarbitrarymemory: prin}(hello%n,&temp)--writes6intotem prin}(%08x.%08x.%08x.%08x.%n)
7/29/2019 02 Ctrl Hijacking
26/58
ControlHijackin
Pla}ormDefe
7/29/2019 02 Ctrl Hijacking
27/58
PrevenFnghijackinga5ack
1. ixbugs:Auditsoware Automatedtools:Coverity,Prefast/Prefix.Rewritesowareinatypesafelanguange(Java,M
DifficultforexisFng(legacy)code2. Concedeoverflow,butpreventcodeexecuFon3. AddrunFmecodetodetectoverflowsexploits
Haltprocesswhenoverflowexploitdetected StackGuard, LibSafe,
Marking memory as non execute
7/29/2019 02 Ctrl Hijacking
28/58
Markingmemoryasnon-execute
Preventa5ackcodeexecuFonbymarkingstackandheapasno
NX-bit on AMD Athlon 64, XD-bit on Intel P4 Prescot NXbitineveryPageTableEntry(PTE) Deployment:
Linux(viaPaXproject);OpenBSD Windows:sinceXPSP2(DEP)
VisualStudio:/NXCompat[:NO] LimitaFons:
Someappsneedexecutableheap(e.g.JITs). Doesnotdefendagainst`ReturnOrientedProgramming
7/29/2019 02 Ctrl Hijacking
29/58
Examples:DEPcontrolsinWindo
DEPterminaFnga
A5 k R t O i t d P i
7/29/2019 02 Ctrl Hijacking
30/58
A5ack:ReturnOrientedProgramming
ControlhijackingwithoutexecuFngcodeargs
ret-addrsfp
local buf
stackexec()printf()
/bin/sh
libc.so
Response: randomizaFon
7/29/2019 02 Ctrl Hijacking
31/58
Response:randomizaFon ASLR:(AddressSpaceLayoutRandomizaFon)
MapsharedlibrariestorandlocaFoninprocessA5ackercannotjumpdirectlytoexecfuncFo
Deployment:(/DynamicBase) WindowsVista: 8bitsofrandomnessforDLLs
alignedto64Kpageina16MBregion26ch Windows8: 24bitsofrandomnesson64-bi
OtherrandomizaFonmethods: Sys-callrandomizaFon:randomizesys-callids InstrucFon Set RandomizaFon (ISR)
ASLR Example
7/29/2019 02 Ctrl Hijacking
32/58
ASLRExampleBooting twice loads libraries into different locatio
Note:everythinginprocessmemorymustberandomiz
stack,heap,sharedlibs,image
Win 8 Force ASLR: ensures all loaded modules us
More a5acks : JiT sprayin
7/29/2019 02 Ctrl Hijacking
33/58
Morea5acks:JiTsprayinIdea: 1.orceJavascriptJiTtofillheapwith
executableshellcode
2.thenpointSPanywhereinsprayarea
vtable
NOPslide shellco
executeenabledexecuteenabled
executeenabled executeenabled
7/29/2019 02 Ctrl Hijacking
34/58
ControlHijackin
Run-FmeDef
R F h ki St kG
7/29/2019 02 Ctrl Hijacking
35/58
RunFmechecking:StackGu Manyrun-Fmecheckingtechniques
weonlydiscussmethodsrelevanttooverflowprot
SoluFon1:StackGuard RunFmetestsforstackintegrity. Embedcanariesinstackframesandverifytheiri
priortofuncFonreturn.
sretsfplocal canarystrretlocal canary
rame1rame2
sfp
Canary Types
7/29/2019 02 Ctrl Hijacking
36/58
CanaryTypes
Randomcanary: Randomstringchosenatprogramstartup. Insertcanarystringintoeverystackframe. VerifycanarybeforereturningfromfuncFon.
Exitprogramifcanarychanged.TurnspotenFalexplo Tocorrupt,a5ackermustlearncurrentrandomst
Terminatorcanary:Canary={0,newline,linefeed,EO StringfuncFonswillnotcopybeyondterminator. A5ackercannotusestringfuncFonstocorruptsta
7/29/2019 02 Ctrl Hijacking
37/58
StackGuard(Cont.) StackGuardimplementedasaGCCpatch.
Programmustberecompiled.
Minimalperformanceeffects:8%forApache. Note:CanariesdontprovidefullproofprotecFon.
Somestacksmashinga5acksleavecanariesunchanged HeapprotecFon:PointGuard.
ProtectsfuncFonpointersandsetjmpbuffersbyencrype.g.XORwithrandomcookie
LesseffecFve,morenoFceableperformanceeffects
StackGuard enhancements: Pr
7/29/2019 02 Ctrl Hijacking
38/58
StackGuardenhancements:Pr
ProPolice(IBM) - gcc 3.4.1. (-fstack-protector) Rearrangestacklayouttopreventptroverflow.
args
retaddr
SP
CANARY
localstringbuffers
localnon-buffervariables
Stack
Growth pointers,b
String
Growth
copy of pointer args
Protectspointe
pointersfrom
MS Visual Studio /GS [ i
7/29/2019 02 Ctrl Hijacking
39/58
MSVisualStudio/GS[sinceCompiler/GSopFon:
CombinaFonofProPoliceandRandomcanary. Ifcookiemismatch,defaultbehavioristocall_e
uncFonprolog:subesp,8//allocate8bytesforcookie
moveax,DWORDPTR___security_cookie
xoreax,esp//xorcookiewithcurrentespmovDWORDPTR[esp+8],eax//saveinstack
uncFonepilog:
movecx,DWORD
xorecx,esp
call@__security_addesp,8
Enhanced/GSinVisualStudio2010:
/GSprotecFonaddedtoallfuncFons,unlesscanbeprovenu
/GS stack frame
7/29/2019 02 Ctrl Hijacking
40/58
/GSstackframe
args
retaddr
SP
CANARYlocalstringbuffers
localnon-buffervariables
Stack
Growth pointers,but
String
Growth
copyofpointerargs
exceponhandlers
Canaryprotects
excepFonhand
Evading /GS with excepFon han
7/29/2019 02 Ctrl Hijacking
41/58
Evading/GSwithexcepFonhan
WhenexcepFonisthrown,dispatcherwalksupexceunFlhandlerisfound(elseusedefaulthandler)
next hanext handlernext handler
0xffffffff
buf
SEHfraSEHframe
Aeroverflow:handlerpointstoa5ackerscode
excepFontriggeredcontrolhijack
ptrto
a5ackcode
Mainpoint:excepFonistriggeredbeforecanary
next
Defenses: SAESEH and SEH
7/29/2019 02 Ctrl Hijacking
42/58
Defenses:SAESEHandSEH
/SAESEH:linkerflag LinkerproducesabinarywithatableofsafeexcepFon SystemwillnotjumptoexcepFonhandlernotonlist
/SEHOP:pla}ormdefense(sincewinvistaSP1) ObservaFon:SEHa5ackstypicallycorruptthenextentr SEHOP:addadummyrecordattopofSEHlist WhenexcepFonoccurs,dispatcherwalksuplistandverifie
recordisthere.Ifnot,terminatesprocess.
Summary: Canaries are not full p
7/29/2019 02 Ctrl Hijacking
43/58
Summary:Canariesarenotfullp
Canariesareanimportantdefensetool,butdonotprcontrolhijackinga5acks:
Heap-baseda5ackssFllpossible Integeroverflowa5ackssFllpossible /GSbyitselfdoesnotpreventExcepFonHandlinga (alsoneedSAESEHandSEHOP)
What if cant recompile: Lib
7/29/2019 02 Ctrl Hijacking
44/58
Whatifcan trecompile:Lib
SoluFon2:Libsafe(AvayaLabs)
Dynamicallyloadedlibrary(noneedtorecompileapp.)
Interceptscallstostrcpy(dest,src) Validatessufficientspaceincurrentstackframe:
|frame-pointerdest|>strlen(src)
Ifso,doesstrcpy.Otherwise,terminatesapplicaFondestret-addrsfp src buf ret-addrsfp
Libsafe strcpy main
How robust is Libsafe?
7/29/2019 02 Ctrl Hijacking
45/58
HowrobustisLibsafe?
strcpy()canoverwriteapointerbetweenbufan
destret-addrsfp src buf ret-addrsfp
Libsafestrcpy main
lowmemory
More methods
7/29/2019 02 Ctrl Hijacking
46/58
Moremethods StackShield
AtfuncFonprologue,copyreturnaddressRETansafelocaFon(beginningofdatasegment)
Uponreturn,checkthatRETandSFPisequalto Implementedasassemblerfileprocessor(GCC)
ControlFlowIntegrity(CI) AcombinaFonofstaFcanddynamicchecking
StaFcallydetermineprogramcontrolflow Dynamicallyenforcecontrolflowintegrity
7/29/2019 02 Ctrl Hijacking
47/58
ControlHijackin
Advanced
HijackingA5a
7/29/2019 02 Ctrl Hijacking
48/58
HeapSprayA5acks
AreliablemethodforexploiFngheapov
Heap based control hijacki
7/29/2019 02 Ctrl Hijacking
49/58
Heap-basedcontrolhijacki CompilergeneratedfuncFonpointers(e.g.C++code)
Supposevtableisontheheapnexttoastringobject:
ptr
data
ObjectT
P1P2P3
vtable
method#1method#2
method#3
ptr
buf[26]
obj
vtable
Heap based control hijacki
7/29/2019 02 Ctrl Hijacking
50/58
Heap-basedcontrolhijacki CompilergeneratedfuncFonpointers(e.g.C++code)
Aeroverflowofbufwehave:
ptr
data
ObjectT
P1P2P3
vtable
method#1method#2
method#3
ptr
buf[26]
obj
vtable
s
c
Areliableexploit?
7/29/2019 02 Ctrl Hijacking
51/58
p shellcode=unescape("%u4343%u4343%...");
overflow-string=unescape(%u2332%u4276%...);
cause-overflow(overflow-string);//overflowbuf[]
Problem: a5ackerdoesnotknowwherebrowserplacesshellcodeontheheap
t
buf[26] d t
shellvtable
???
HeapSpraying[SkyLined2004
7/29/2019 02 Ctrl Hijacking
52/58
p p y gIdea: 1.useJavascripttosprayheap
withshellcode(andNOPslides
2.thenpointvtableptranywhereinspray
vtable
NOPslide shellco
heapsprayarea
Javascript heap spraying
7/29/2019 02 Ctrl Hijacking
53/58
Javascriptheapspraying
var nop = unescape(%u9090%u9090)
while (nop.length < 0x100000) nop += nop
var shellcode = unescape("%u4343%u4343%...");
var x = new Array ()
for (i=0; i
7/29/2019 02 Ctrl Hijacking
54/58
p Placingvulnerablebuf[256]nexttoobjectO:
BysequenceofJavascriptallocaFonsandfreesmakeheaplookasfollows:
Allocatevuln.bufferinJavascriptandcauseoverflow SuccessfullyusedagainstaSafariPCREoverflow[DHM08]
objectO
freeblocks
heap
Many heap spray exploit
7/29/2019 02 Ctrl Hijacking
55/58
Manyheapsprayexploit
Improvements:HeapengShui[S07] ReliableheapexploitsonIEwithoutspraying
Gives a5acker full control of IE heap from Javascr
[RLZ
(parFal)Defenses
7/29/2019 02 Ctrl Hijacking
56/58
ProtectheapfuncFonpointers(e.g.PointGuard) Be5erbrowserarchitecture: StoreJavaScriptstringsinaseparateheapfrombrowserheap OpenBSDheapoverflowprotecFon:
Nozzle[RLZ08]:detectspraysbyprevalenceofcodeonheapnon-writablepages
Referencesonheapsprayi
7/29/2019 02 Ctrl Hijacking
57/58
p p y[1] HeapFengShuiinJavascript,
byA.SoFrov,BlackhatEurope2007
[2] EngineeringHeapOverflowExploitswithJavaScript
M.Daniel,J.Honoroff,andC.Miller,WooT2008
[3] Nozzle:ADefenseAgainstHeap-sprayingCodeInjeco
byP.Ratanaworabhan,B.Livshits,andB.Zorn
[4] InterpreterExploitaon:PointerinferenceandJiTspra byDionBlazakis
7/29/2019 02 Ctrl Hijacking
58/58
EndofSegment