-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcuckoo_parse_https.py
236 lines (228 loc) · 11.9 KB
/
cuckoo_parse_https.py
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import argparse
import json
import re
import dateutil.parser
from datetime import datetime
import pytz
from StringIO import StringIO
option_flags = {'0x0000001f':'INTERNET_OPTION_SECURITY_FLAGS',
'0x00000002':'INTERNET_OPTION_CONNECT_TIMEOUT',
'0x00000006':'INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT',
'0x0000003a':'INTERNET_OPTION_REQUEST_PRIORITY',
'0x0000003e':'INTERNET_OPTION_ERROR_MASK',
'0x00000041':'INTERNET_OPTION_HTTP_DECODING',
'0x00000064':'INTERNET_OPTION_CODEPAGE_PATH',
'0x00000066':'INTERNET_OPTION_IDN',
'0x00000044':'INTERNET_OPTION_CODEPAGE',
'0x00000065':'INTERNET_OPTION_CODEPAGE_EXTRA'
}
http_option_flags= {128: 'INTERNET_FLAG_CACHE_ASYNC', 67108864: 'INTERNET_FLAG_NO_CACHE_WRITE', 2147483648: 'INTERNET_FLAG_RELOAD', 4: 'WININET_API_FLAG_SYNC', 134217728: 'INTERNET_FLAG_PASSIVE', 1: 'WININET_API_FLAG_ASYNC', 8: 'WININET_API_FLAG_USE_CONTEXT', 268435456: 'INTERNET_FLAG_ASYNC', 256: 'INTERNET_FLAG_PRAGMA_NOCACHE', 16: 'INTERNET_FLAG_NEED_FILE', 8388608: 'INTERNET_FLAG_SECURE', 512: 'INTERNET_FLAG_NO_UI', 4194304: 'INTERNET_FLAG_KEEP_CONNECTION', 16777216: 'INTERNET_FLAG_OFFLINE', 536870912: 'INTERNET_FLAG_EXISTING_CONNECT', 32: 'INTERNET_FLAG_FWD_BACK', 131072: 'INTERNET_FLAG_RESTRICTED_ZONE', 4096: 'INTERNET_FLAG_IGNORE_CERT_CN_INVALID', 262144: 'INTERNET_FLAG_NO_AUTH', 1024: 'INTERNET_FLAG_HYPERLINK', 8192: 'INTERNET_FLAG_IGNORE_CERT_DATE_INVALID', 524288: 'INTERNET_FLAG_NO_COOKIES', 33554432: 'INTERNET_FLAG_MAKE_PERSISTENT', 16384: 'INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS', 1048576: 'INTERNET_FLAG_READ_PREFETCH', 32768: 'INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP', 64: 'INTERNET_FLAG_FORMS_SUBMIT', 2: 'INTERNET_FLAG_TRANSFER_BINARY', 2048: 'INTERNET_FLAG_RESYNCHRONIZE', 2097152: 'INTERNET_FLAG_NO_AUTO_REDIRECT', 65536: 'INTERNET_FLAG_CACHE_IF_NET_FAIL', 1073741824: 'INTERNET_FLAG_RAW_DATA'}
security_flags = {'0x00000100':'SECURITY_FLAG_IGNORE_CERT_CN_INVALID'}
def _parse_https(proc):
handle_maps = {}
handle_data = {}
handle_maps['0x00000001'] = []
crypts = {}
lastcrypt = {}
lastnet = {}
for call in proc['calls']:
#if call['api'].startswith('WinHttp'):
# print call
if call['category'] == 'crypto':
args = dict([(x['name'],x['value']) for x in call['arguments']])
call.pop('arguments')
call['arguments'] = args
if lastnet.get('api','').lower() in ['wsarecv','recv'] and call['api'] == 'CryptDecrypt' and lastnet['arguments']['socket'] in crypts:
crypts[lastnet['arguments']['socket']].append(call)
lastnet = {}
lastcrypt = call
if call['category'] == 'network':
args = dict([(x['name'],x['value']) for x in call['arguments']])
call.pop('arguments')
call['arguments'] = args
if call['api'].lower() in ['wsasend','send']:
#print call,lastcrypt
if lastcrypt.get('api','') == 'CryptEncrypt' and call['api'] == 'WSASend':
crypts[call['arguments']['Socket']] = [lastcrypt]
elif lastcrypt.get('api','') == 'CryptEncrypt' and call['api'] == 'send':
crypts[call['arguments']['socket']] = [lastcrypt]
lastcrypt = {}
if args.get('InternetHandle',None) in ['0x00000000','0x00000001']: continue
if 'InternetRead' in call['api'] or 'InternetSetOption' in call['api'] or 'Send' in call['api']:
if 'InternetHandle' in args:
handle = handle_data.get(args['InternetHandle'],None)
if not handle: continue
val = handle_maps.get(handle,[])
val = [] if val is None else val
handle_maps[handle] += [call]
elif 'RequestHandle' in args:
handle = handle_data.get(args['RequestHandle'],None)
if not handle:
#print call
continue
else:
val = handle_maps.get(handle,[])
val = [] if val is None else val
handle_maps[handle] += [call]
elif 'Open' in call['api'] or 'Connect' in call['api']:
if args.get('InternetHandle',None):
handle = handle_data.get(args['InternetHandle'],None)
if not handle:
handle_data[args['InternetHandle']] = args['InternetHandle']
handle_maps[args['InternetHandle']] = [call]
else:
val = handle_maps.get(args['InternetHandle'],[])
val = [] if val is None else val
handle_data[call['return']] = handle_data[args['InternetHandle']]
handle_maps[handle] += [call]
elif args.get('RequestHandle',None):
handle = handle_data[args['RequestHandle']]
val = handle_maps.get(handle,[])
val = [] if val is None else val
handle_data[call['return']] = handle_data[args['RequestHandle']]
handle_maps[handle] += [call]
else:
handle_data[call['return']] = call['return']
handle_maps[call['return']] = [call]
elif call['api'].startswith("InternetClose"):
handle = handle_data.get(args['InternetHandle'],None)
if not handle: continue
handle_maps[handle].append(call)
lastnet = call
#print crypts
return handle_maps,crypts
def _find_https_requests(proc):
parsed,crypts = _parse_https(proc)
for handle, calls in parsed.items():
if handle == '0x00000001': continue
response = ""
options = {}
server = ""
uri = ""
headers = ""
postdata = ""
response = ""
user_agent = ""
options = {}
for call in calls:
if call['api'].startswith('Crypt'): print call
elif call['api'].startswith('InternetOpen'):
user_agent = call['arguments'].get('Agent','DEFAULT')
#print user_agent
elif call['api'].startswith('InternetConnect'):
if server and 'INTERNET_FLAG_SECURE' in arr_flags:
url = "https://{}{}".format(server,uri)
timestamp = pytz.timezone('America/Detroit').localize(dateutil.parser.parse(timestamp.split(',')[0]))
#timestamp = common.now()
#print self._network_api.add_https_request(task,timestamp,uri,url,user_agent,postdata,referer,headers,flags,response)
print_request(server,uri,user_agent,headers,postdata,response,options,arr_flags,timestamp)
user_agent = ""
server = "{}:{}".format(call['arguments']['ServerName'],call['arguments']['ServerPort']) if call['arguments']['ServerName'] else ""
uri = ""
headers = ""
referer = ""
postdata = ""
response = ""
options = {}
arr_flags = []
elif call['api'].startswith('HttpOpen'):
print call
referer = call['arguments'].get("Referer","")
timestamp = call['timestamp']
flags=int(call['arguments']['Flags'],16)
if 'UserAgent' in call['arguments']:
user_agent = call['arguments']['UserAgent']
arr_flags = []
for k,v in http_option_flags.items():
if k & flags: arr_flags.append(v)
uri = call['arguments'].get('Path','/')
elif call['api'].startswith('HttpSend'):
headers = call['arguments']['Headers']
postdata = call['arguments']['PostData']
elif call['api'].startswith('InternetRead'):
response += call['arguments']['Buffer']
elif call['api'].startswith('InternetSet'):
optval = option_flags.get(call['arguments']['Option'],call['arguments']['Option'])
if 'SECURITY' in optval:
buff = security_flags.get(call['arguments']['Buffer'],call['arguments']['Buffer'])
elif 'Buffer' in call['arguments']: buff = call['arguments']['Buffer']
else: buff = ""
options[optval] = buff
elif call['api'].startswith('InternetClose'):
if server and 'INTERNET_FLAG_SECURE' in arr_flags:
url = "https://{}{}".format(server,uri)
timestamp = pytz.timezone('America/Detroit').localize(dateutil.parser.parse(timestamp.split(',')[0]))
#timestamp = common.now()
print_request(server,uri,user_agent,headers,postdata,response,options,arr_flags,timestamp)
#print self._network_api.add_https_request(task,timestamp,uri,url,user_agent,postdata,referer,headers,flags,response)
server = ""
referer = ""
uri = ""
headers = ""
postdata = ""
user_agent = ""
response = ""
options = {}
arr_flags = []
if server and 'INTERNET_FLAG_SECURE' in arr_flags:
url = "https://{}{}".format(server,uri)
timestamp = pytz.timezone('America/Detroit').localize(dateutil.parser.parse(timestamp.split(',')[0]))
#timestamp = common.now()
#print self._network_api.add_https_request(task,timestamp,uri,url,user_agent,postdata,referer,headers,flags,response)
print_request(server,uri,user_agent,headers,postdata,response,options,arr_flags,timestamp)
for ch,calls in crypts.items():
req = calls[0]
res = calls[1]['arguments']['Buffer']
if '\r\n\r\n' in req['arguments']['Buffer']:
req_header,postdata = req['arguments']['Buffer'].split('\r\n\r\n')
else:
postdata = ''
req_header = req['arguments']['Buffer'].strip()
req_lines = req_header.split('\r\n')
method,uri,ver = re.split('\s+',req_lines[0])
headers = req_lines[1:]
timestamp = datetime.now()
user_agent = ""
ua_header = None
host_header = None
for header in headers:
#print header
if header.lower().startswith('user-agent'):
user_agent = header[header.find(':')+1:].strip()
ua_header = header
elif header.lower().startswith('host:'):
server = header[header.find(':')+1:].strip()
host_header = header
if ua_header: headers.remove(ua_header)
if host_header: headers.remove(host_header)
if '' in headers:headers.remove('')
headers = '\r\n'.join(headers)
print_request(server,uri,user_agent,headers,postdata,res,{},['INTERNET_FLAG_SECURE'],timestamp)
def print_request(server,uri,user_agent,headers,postdata,response,options,arr_flags,timestamp):
if 'INTERNET_FLAG_SECURE' in arr_flags:
url = "https://{}{}".format(server,uri)
else:
url = "http://{}{}".format(server,uri)
print "Timestamp: {}".format(timestamp)
print "URL: {}".format(url)
print "User-Agent: {}".format(user_agent)
print "Headers: {}".format(headers)
print "PostData: {}".format(postdata.encode('unicode_escape'))
print "Response: {}".format(response.encode('unicode_escape'))
for k,v in options.items():
print "Option {}: {}".format(k,v)
for f in arr_flags:
print "HTTP Option: {}".format(f)
print "\n"
def main():
parser = argparse.ArgumentParser("Create IDApython annotation scripts for cuckoo task(s)")
parser.add_argument("JSON_FILE",help="Cuckoo JSON Report File to parse")
args = parser.parse_args()
with open(args.JSON_FILE) as f:
data = f.read()
j = json.loads(data)
for proc in j['behavior']['processes']:
print "[+] Processing PID-{}".format(proc['process_id'])
_find_https_requests(proc)
if __name__ == "__main__":
main()