- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatch.py
More file actions
Latest commit
208 lines (196 loc) · 9.57 KB
/
Copy pathpatch.py
File metadata and controls
208 lines (196 loc) · 9.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
frompwnimport*
fromcapstoneimport*
fromcapstone.x86importX86_INS_PUSH
importlief
importstruct
importos
importargparse
fromshellcodeimportmyShellCraft
classELFPatchUtils():
def__init__(self, binary):
self.e=lief.parse(binary)
self.name=binary
self.elf=ELF(binary, checksec=False)
self.originEntryPoint=self.e.entrypoint
self.modifiedPtr=0
defaddDataSegment(self, size):
segment_add=lief.ELF.Segment()
segment_add.type=lief.ELF.SEGMENT_TYPES.LOAD
segment_add.alignment=8
segment_add.add(lief.ELF.SEGMENT_FLAGS.W)
segment_add.add(lief.ELF.SEGMENT_FLAGS.R)
segment_add.content= [0for_inrange(size)]
segment=self.e.add(segment_add, base=0x20000)
log.success("add data segment succeed!")
returnsegment
defaddHookSegment(self):
segment_add=lief.ELF.Segment()
segment_add.type=lief.ELF.SEGMENT_TYPES.LOAD
segment_add.alignment=8
segment_add.add(lief.ELF.SEGMENT_FLAGS.X)
segment_add.add(lief.ELF.SEGMENT_FLAGS.R)
segment_add.content= [0for_inrange(0x1000)]
segment=self.e.add(segment_add, base=0x10000)
log.success("add hook segment succeed!")
returnsegment
defgetLOADSegment(self):
forsegmentinself.e.segments:
ifsegment.type==lief.ELF.SEGMENT_TYPES.LOADandsegment.flags&lief.ELF.SEGMENT_FLAGS.X!=0:
returnsegment
defgetSectionByName(self, name):
forsectioninself.e.sections:
ifsection.name==name:
returnsection
defgetPltAddress(self, name, static=False, pltAddress=None):
ifname=='nop':
return0
ifnotstatic:
try:
returnself.elf.plt[name]
except:
log.warn("No %s function"%(name))
return0
else:
returnpltAddress[name]
defgenShellcode(self, shellcodeName, args=None):
ifself.e.header.identity_class==lief.ELF.ELF_CLASS.CLASS64:
context.arch='amd64'
init_asm=''
ifshellcodeName=='initLog':
init_asm=asm(myShellCraft.init_shellcode64[shellcodeName].format(hex(args[0]), hex(args[1])))
shellcode=init_asm
elifshellcodeName=='readLog':
shellcode=asm(myShellCraft.shellcode64[shellcodeName].format(hex(args[0]), hex(args[1]+0x8)))
elifshellcodeName=='__isoc99_scanfLog':
shellcode=asm(myShellCraft.shellcode64[shellcodeName].format(hex(args[0]), hex(args[1]+8)))
elifself.e.header.identity_class==lief.ELF.ELF_CLASS.CLASS32:
context.arch='i386'
init_asm=''
ifshellcodeName=='initLog':
init_asm=asm(myShellCraft.init_shellcode32[shellcodeName].format(hex(args[0]), hex(args[1])))
shellcode=init_asm
elifshellcodeName=='readLog':
shellcode=asm(myShellCraft.shellcode32[shellcodeName].format(hex(args[0]), hex(args[1]+0x8)))
elifshellcodeName=='__isoc99_scanfLog':
shellcode=asm(myShellCraft.shellcode32[shellcodeName].format(hex(args[0]), hex(args[1]+8)))
code= []
try:
foriinshellcode:
code.append(ord(i))
except:
raiseException("No such shellcode")
returncode, len(init_asm)
defgetFunctionAddress(self, func_name, static):
ifstaticisFalseorfunc_name=='nop':
ifnotself.e.is_pieorfunc_name=='nop':
func_plt_address=self.getPltAddress(func_name)
else:
func_plt_address=self.getPltAddress(func_name) -self.originEntryPoint+self.e.entrypoint
returnfunc_plt_address
else:
try:
returnfunc_name
except:
raiseException("With --static please enter address@shellcode")
defhookCallPlt(self, funcShellcodeName, isStatic, args=None):
data_segment_added=self.addDataSegment(0x100)
oldEntrypoint=self.e.entrypoint
segment_add=self.addHookSegment()
init_length=0
forfuncShellcodeinfuncShellcodeName:
func_name, shellcodeName=funcShellcode.split('@')
ifisStaticandfunc_name!='nop':
func_name=eval(func_name)
ifshellcodeNamein ['initLog', 'readLog', '__isoc99_scanfLog']:
shellcode, init_length=self.genShellcode(shellcodeName, [segment_add.virtual_address, data_segment_added.virtual_address])
else:
shellcode=args[func_name]
prevShellcode=segment_add.content[:self.modifiedPtr]
prevShellcode+=shellcode
shellcodeLength=len(shellcode)
segment_add.content=prevShellcode
ifinit_length!=0:
patch_address=segment_add.virtual_address+init_length-5
init_offset=self.e.entrypoint-patch_address-5
patched_code= [ord(i) foriin (myShellCraft.opcode['jmp_offset']+struct.pack('i', init_offset))]
self.e.patch_address(patch_address, patched_code)
elifshellcodeNamein ['__isoc99_scanfLog']:
patch_address=segment_add.virtual_address+self.modifiedPtr+shellcodeLength-5
ifisStatic:
#patch_offset = self.getPltAddress('__isoc99_scanfPlt', isStatic, args) - patch_address - 5
patch_offset=self.getPltAddress(shellcodeName, isStatic, args) -patch_address-5
else:
#patch_offset = self.getFunctionAddress('__isoc99_scanf', isStatic) - patch_address - 5
patch_offset=self.getFunctionAddress(func_name, isStatic) -patch_address-5
patched_code= [ord(i) foriin (myShellCraft.opcode['jmp_offset']+struct.pack('i', patch_offset))]
self.e.patch_address(patch_address, patched_code)
LOADSegment=self.getLOADSegment()
textSection=self.getSectionByName('.text')
code_offset=textSection.file_offset
func_plt_address=self.getFunctionAddress(func_name, isStatic)
iffunc_plt_address==0:
self.modifiedPtr+=shellcodeLength
continue
ifself.e.header.identity_class==lief.ELF.ELF_CLASS.CLASS64:
md=Cs(CS_ARCH_X86, CS_MODE_64)
elifself.e.header.identity_class==lief.ELF.ELF_CLASS.CLASS32:
md=Cs(CS_ARCH_X86, CS_MODE_32)
code=bytearray(textSection.content)
offset_need_to_modified= []
findFunctionFlag=0
ifnotisStatic:
foriinmd.disasm(code, LOADSegment.virtual_address+code_offset):
ifi.mnemonic=='call':
ifi.op_str.startswith('0x'):
call_address=int(i.op_str, 16)
ifcall_address==func_plt_addressorcall_address==func_plt_address+4:
findFunctionFlag=1
offset_need_to_modified.append(i.address)
else:
offset_need_to_modified= [iforiinfunc_name]
findFunctionFlag=1
iffindFunctionFlag==0:
raiseException("can not find target function!")
foraddressinoffset_need_to_modified:
ifnotself.e.is_pie:
modified_offset=address- (self.e.entrypoint&~0xfffff) -code_offset
else:
modified_offset=address
offset=segment_add.virtual_address+init_length+self.modifiedPtr-address-5
patched_code= [ord(i) foriin (myShellCraft.opcode['call_offset'] +struct.pack('i', offset))]
self.e.patch_address(address, patched_code)
log.success("patched 0x%x"%(address))
self.modifiedPtr+=shellcodeLength
ifisStatic:
LOADSegment.physical_size=self.e.header.program_header_offset+self.e.header.numberof_segments*self.e.header.program_header_size
LOADSegment.virtual_size=LOADSegment.physical_size
self.e.header.entrypoint=segment_add.virtual_address
log.success("new entrypoint: 0x%x"%(self.e.entrypoint))
outfile=self.name+'_patch'
self.e.write(outfile)
st=os.stat(outfile)
os.chmod(outfile, st.st_mode|0111)
log.success("patch succeed!")
if__name__=='__main__':
parser=argparse.ArgumentParser(description="AWD patch tool")
parser.add_argument("bin", help="/path/to/your/input binary")
parser.add_argument("-s", "--shellcode", action='append', default=[], help="choose shellcode", required=True)
parser.add_argument("--static", action='store_true', help="static mode")
parser.add_argument("-p", "--plt", help="plt address; Need with --static")
args=parser.parse_args()
elf=ELFPatchUtils(args.bin)
#elf.hookPlt(args.functions, args.shellcode)
ifnotargs.static:
shellcode= ['nop@initLog']
forsinargs.shellcode:
shellcode.append(s)
elf.hookCallPlt(shellcode, False)
elifargs.static:
shellcode= ['nop@initLog']
forsinargs.shellcode:
shellcode.append(s)
try:
plt=eval(args.plt)
except:
raiseException("args Error")
elf.hookCallPlt(shellcode, True, plt)