-
Notifications
You must be signed in to change notification settings - Fork 1
/
__init__.py
284 lines (231 loc) · 10.5 KB
/
__init__.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# camelCase naming conventions to match java wappalyzer style
import json
import os
import re
import requests
from bs4 import BeautifulSoup
class Props(object):
def __init__(self, *args, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
def __getattr__(self, item):
if item not in self.__dict__:
return None
return self.__dict__[item]
class Application(object):
def __init__(self, name, props, detected=False):
self.confidence = {}
self.confidenceTotal = 0
self.detected = bool(detected)
self.excludes = []
self.name = name
self.props = Props(**props)
self.version = ''
def __str__(self):
return self.name
def getConfidence(self):
total = 0
for id in self.confidence:
total += int(self.confidence[id])
self.confidenceTotal = min(total, 100)
return self.confidenceTotal
class Wappalyzer(requests.Session):
def __init__(self, url, filename='apps.json'):
super().__init__()
self.verify = False
file = os.path.join(os.getcwd(), os.path.dirname(__file__), filename)
if not os.path.exists(file):
self.log('Downloading latest wappalyzer database file', 'init', 'error')
self.downloadWappalyzerDB(file)
self.headers['User-Agent'] = 'Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181'
self.db = json.load(open(file, encoding='utf-8'))
self.apps = self.db['apps']
self.jsPatterns = self.parseJsPatterns()
self.url = url
self.data = self.get(url)
js = {}
for i in self.jsPatterns:
for j in self.jsPatterns[i]:
js.update({i: {j: {}}})
self.data.js = js
self.data.scripts = [script['src'] for script in
BeautifulSoup(self.data.text, 'html.parser').find_all('script', {'src': True})]
self.data.headers = {i.lower(): j for i, j in self.data.headers.items()}
def downloadWappalyzerDB(self, file):
db_url = 'https://raw.githubusercontent.com/AliasIO/Wappalyzer/master/src/apps.json'
resp = self.get(db_url, stream=True)
with open(file, 'wb') as f:
for chunk in resp.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
def asArray(self, value):
return value if isinstance(value, list) else [value]
def analyze(self):
apps = {}
matches = re.search('<html[^>]*[: ]lang="([a-z]{2}((-|_)[A-Z]{2})?)"', self.data.text, re.IGNORECASE)
language = None
if matches:
language = matches.groups()[0]
matches = matches.group()
for appName in self.apps:
apps[appName] = Application(appName, self.apps[appName])
app = apps[appName]
if self.data.text:
self.analyzeHtml(app, self.data.text)
self.analyzeMeta(app, self.data.text)
if self.data.scripts:
self.analyzeScripts(app, self.data.scripts)
if self.data.headers:
self.analyzeHeaders(app, self.data.headers)
if hasattr(self.data, 'env'):
self.analyzeEnv(app, self.data.env)
if self.data.js:
for appName in self.data.js:
self.analyzeJs(apps[appName], self.data.js[appName])
for appName, app in apps.copy().items():
if not app.detected or not app.getConfidence():
apps.pop(appName)
self.resolveExcludes(apps)
self.resolveImplies(apps)
return apps
def parseJsPatterns(self):
patterns = {}
for appName in self.apps:
if 'js' in self.apps[appName]:
patterns.update({appName: self.parsePatterns(self.apps[appName]['js'])})
return patterns
def resolveExcludes(self, apps):
excludes = []
for appName, app in apps.items():
if app.props.excludes:
for excluded in self.asArray(app.props.excludes):
excludes.append(excluded)
for appName in apps.copy():
if appName in excludes:
apps.pop(appName)
def parsePatterns(self, patterns):
if not patterns:
return []
parsed = {}
if isinstance(patterns, str) or isinstance(patterns, list):
patterns = {
'main': self.asArray(patterns)
}
for key in patterns:
parsed[key] = []
for pattern in self.asArray(patterns[key]):
attrs = {}
pattern_version = pattern.split('\\;')
for i in range(len(pattern_version)):
attr = pattern_version[i]
if i:
attr = attr.split(':')
if len(attr) > 1:
attrs[attr[0]] = attr[1]
else:
attrs['string'] = attr
attrs['regex'] = attr.replace('/', '\/')
parsed[key].append(attrs)
if 'main' in parsed:
parsed = parsed['main']
return parsed
def resolveImplies(self, apps):
checkImplies = True
while checkImplies:
checkImplies = False
for appName in apps.copy():
app = apps[appName]
if app and app.props.implies:
for implied in self.asArray(app.props.implies):
implied = self.parsePatterns(implied)[0]
if not self.apps[implied['string']]:
self.log('Implied application ' + implied.string + ' does not exist', 'core', 'warn')
return
if not implied['string'] in apps:
apps[implied['string']] = Application(implied['string'], self.apps[implied['string']], True)
checkImplies = True
for id in app.confidence:
apps[implied['string']].confidence[id + ' implied by ' + appName] = app.confidence[
id] * int(
int(implied['confidence']) / 100 if 'confidence' in implied else 1)
def analyzeUrl(self, app: Application, url):
patterns = self.parsePatterns(app.props['url'])
if patterns:
for pattern in patterns:
if re.search(pattern['regex'], url):
self.addDetected(app, pattern, 'url', url)
def analyzeHtml(self, app, html):
patterns = self.parsePatterns(app.props.html)
if patterns:
for pattern in patterns:
if 'regex' in pattern and re.search(pattern['regex'], html):
self.addDetected(app, pattern, 'html', html)
def analyzeScripts(self, app: Application, scripts):
patterns = self.parsePatterns(app.props.script)
for pattern in patterns:
for uri in scripts:
if re.search(pattern['regex'], uri):
self.addDetected(app, pattern, 'script', uri)
def analyzeMeta(self, app, html):
regex = re.compile('<meta[^>]+>', re.IGNORECASE)
patterns = self.parsePatterns(app.props.meta)
matches = re.findall(regex, html)
for match in matches:
for meta in patterns:
r = re.search('(?:name|property)=["\']' + meta + '["\']', match, re.IGNORECASE)
if r:
content = re.findall('content=["|\']([^"\']+)["|\']', match, re.IGNORECASE)
for pattern in patterns[meta]:
if content and re.search(pattern['regex'], content[0], re.IGNORECASE):
self.addDetected(app, pattern, 'meta', content[0], meta)
def analyzeHeaders(self, app: Application, headers: dict):
patterns = self.parsePatterns(app.props.headers)
if headers:
for headerName in patterns:
for pattern in patterns[headerName]:
headerName = headerName.lower()
if headerName in headers:
headerValue = headers[headerName]
if re.search(pattern['regex'], headerValue):
self.addDetected(app, pattern, 'headers', headerValue, headerName)
def analyzeJs(self, app: Application, results):
for string in results:
for index in results[string]:
pattern = self.jsPatterns[app.name][string][index]
value = results[string][index]
if pattern and re.search(pattern['regex'], value):
self.addDetected(app, pattern, 'js', value)
def addDetected(self, app: Application, pattern, type, value, key=''):
app.detected = True
app.confidence[type + ' ' + (key + ' ' if key else '') + pattern['regex']] = pattern[
'confidence'] if 'confidence' in pattern else 100
if 'version' in pattern:
versions = []
version = pattern['version']
matches = re.findall(pattern['regex'], value, re.IGNORECASE)
if matches:
for i in range(len(matches)):
match = matches[i]
ternary = re.findall('\\\\' + str(i) + '\\?([^:]+):(.*)$', version)
if isinstance(match, tuple): # findall returns tuple groups sometimes if groups used in regex
match = match[1]
if ternary and len(ternary) >= 3:
version = version.replace(ternary[0], ternary[1] if match else ternary[2])
version = version.replace(version, match or '')
if version and version not in versions:
versions.append(version.strip())
if len(versions):
app.version = max(versions)
def analyzeEnv(self, app, envs):
patterns = self.parsePatterns(app.props.env)
for pattern in patterns:
for env in envs:
if re.search(pattern['regex'], env):
self.addDetected(app, pattern, 'env', env)
def log(self, message, source, _type):
print('[wappalyzer {}] [{}] {}'.format(_type, source, message))
def __del__(self):
del self.db
del self.apps
del self.jsPatterns
del self.data