/
flowcollection.py
193 lines (165 loc) · 7.22 KB
/
flowcollection.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
from libmproxy import encoding
from libhproxy.honey import HoneyProxy
import re, socket, cgi, StringIO
import hashlib #@UnusedImport
"""
flatten a given fieldStorage and return a dict with the following structure:
{"filenameA":"filecontentA",...}
This dict will be processed for creating hash checksums
"""
def getParts(fieldStorage,parts=None):
if parts == None:
parts = {}
if type(fieldStorage.value) != type([]):
name = ""
# empty strings -> None; else: strip()
fieldStorage.name = fieldStorage.name.strip() if (fieldStorage.name != None and fieldStorage.name.strip() != "") else None
fieldStorage.filename = fieldStorage.filename.strip() if (fieldStorage.filename != None and fieldStorage.filename.strip() != "") else None
if fieldStorage.name == None and fieldStorage.filename == None:
if "Checksum" in parts:
return parts
name = "Checksum"
else:
if fieldStorage.name != None:
name = str(fieldStorage.name)
if fieldStorage.filename != None:
name += ": " + str(fieldStorage.filename)
else:
if len(fieldStorage.value) < 1025:
return parts #don't calculate md5s for really small chunks
elif fieldStorage.filename != None:
name = str(fieldStorage.filename)
#find next avail. name
i=2
if name in parts:
name += " (2)"
while name in parts:
i += 1
name = name[:-(2+len(str(i)))] + ("(%d)" % i)
parts[name] = str(fieldStorage.value)
else:
for i in fieldStorage.value:
getParts(i,parts)
return parts
class FlowCollection:
"""
Collects all flows, gives them an id, decodes content.
"""
regex_charset = re.compile("charset=\s*([\S]+|['\"][^'\"]+['\"])")
regex_isip = re.compile("^([0-9]{1,3}\.){3}[0-9]{1,3}$")
def __init__(self):
self._flows_serialized = []
self._flows = []
self._decoded_contents = []
def getFlow(self,flowId):
return self._flows[flowId]
def getDecodedContents(self):
return self._decoded_contents
def getFlowsSerialized(self):
return self._flows_serialized
def addFlow(self, flow):
"""
Adds a flow to all lists in the corresponding format
"""
flowRepr = flow._get_state()
flowRepr["id"] = len(self._flows_serialized)
#In transparent mode, we are unsure about the actual host, but we want to show it in the GUI.
#Firstly, we get the Host from the request headers.
#As this might be faked, we go on and check whether the request IP matches one of the DNS entries belonging to the headerHost
if(FlowCollection.regex_isip.match(flowRepr["request"]["host"])):
try:
headerHost = flow.request.headers["Host"]
if(headerHost):
headerHost = headerHost[0]
info = socket.getaddrinfo(flowRepr["request"]["host"], flowRepr["request"]["port"],0,0,socket.SOL_TCP)
for i in info:
if i[4][0] == flowRepr["request"]["host"]:
flowRepr["request"]["host_guess"] = headerHost
break
except socket.gaierror:
pass
except:
import traceback
print traceback.format_exc()
#Save decoded content
decoded_content = {}
algorithms = ["md5","sha1","sha256"]
for i in ["request","response"]:
#strip content out of the flowRepr
flowRepr[i]["contentLength"] = len(flowRepr[i]["content"])
del flowRepr[i]["content"]
r = getattr(flow,i)
decoded = r.content
#decode with http content-encoding
try:
ce = r.headers["content-encoding"]
if ce and ce[0] in encoding.ENCODINGS:
decoded_ = encoding.decode(ce[0],decoded)
if decoded_ != None: #If the decoding fails, encoding.decode returns None.
decoded = decoded_
except:
print "Warning: Data cannot be decoded with given Content Encoding."
#calculate hashsums
flowRepr[i]["contentChecksums"] = {}
parts = {"Checksum":decoded}
#Handle multipart checksums
if i == "request":
try:
headers = dict(map(str.lower, map(str,a)) for a in flow.request.headers) # odict -> (lowered) dict
fs = cgi.FieldStorage(StringIO.StringIO(decoded),headers,environ={ 'REQUEST_METHOD':'POST' })
parts = getParts(fs)
except Exception as e:
import traceback
traceback.print_exc()
print "Warning: Cannot decode multipart"
for item, data in parts.viewitems():
checksums = {}
for a in algorithms:
checksums[a] = getattr(hashlib,a)(data).hexdigest()
flowRepr[i]["contentChecksums"][item] = checksums
#decode with http content-type encoding
ct = r.headers["content-type"]
default_charset = "latin-1" #HTTP 1.1 says that the default charset is ISO-8859-1
#RFC2616 3.7.1
charset = default_charset
if ct:
m = FlowCollection.regex_charset.search(ct[0])
if m:
charset = m.group(1).strip('"').strip('"\'')
#TODO: guess from html metadata
try:
decoded = decoded.decode(charset)
except:
try:
decoded = decoded.decode(default_charset)
except:
print "Warning: Could not decode request."
import traceback
print traceback.format_exc()
try:
decoded = decoded.encode('utf-8')
except:
print "Warning: Cannot encode request to utf8"
decoded_content[i] = decoded
self._flows.append(flow)
self._flows_serialized.append(flowRepr)
self._decoded_contents.append(decoded_content)
return len(self._flows_serialized)-1
class includeDecodedContent(object):
"""
A context manager that adds the decoded request and response content to a serialized list of flows
and removes it after execution of the block
Example:
with includeDecodedContent(flows):
search(flows)
"""
def __init__(self, flows):
self.flows = flows
def __enter__(self):
for flow in self.flows:
for i in ["request","response"]:
flow[i]["content"] = HoneyProxy.getProxyMaster().getFlowCollection().getDecodedContents()[flow.get("id")][i]
def __exit__(self, exc_type, value, tb):
for flow in self.flows:
for i in ["request","response"]:
del flow[i]["content"]