forked from thinkst/canarytokens
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpd_site.py
555 lines (457 loc) · 22.3 KB
/
httpd_site.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
import base64
import simplejson
import cgi
from twisted.web import server, resource
from twisted.application import internet
from twisted.web.server import Site, GzipEncoderFactory
import twisted.web.resource
from twisted.web.resource import Resource, EncodingResourceWrapper, \
ForbiddenResource, NoResource
from twisted.web.static import File, DirectoryLister, Data
from twisted.web.util import Redirect
from twisted.python import log
from jinja2 import Environment, FileSystemLoader
import pyqrcode
from tokens import Canarytoken
from canarydrop import Canarydrop
from queries import save_canarydrop, save_imgur_token, get_canarydrop,\
create_linkedin_account, create_bitcoin_account,\
get_linkedin_account, get_bitcoin_account, \
save_clonedsite_token, get_all_canary_sites, get_canary_google_api_key,\
is_webhook_valid
from exception import NoCanarytokenPresent
from ziplib import make_canary_zip
from msword import make_canary_msword
from pdfgen import make_canary_pdf
from authenticode import make_canary_authenticode_binary
import settings
import datetime
import tempfile
import hashlib
import os
env = Environment(loader=FileSystemLoader('templates'),
extensions=['jinja2.ext.loopcontrols'])
with open('/srv/templates/error_http.html', 'r') as f:
twisted.web.resource.ErrorPage.template = f.read()
class GeneratorPage(resource.Resource):
isLeaf = True
def getChild(self, name, request):
if name == '':
return self
return Resource.getChild(self, name, request)
def render_GET(self, request):
template = env.get_template('generate_new.html')
sites_len = len(get_all_canary_sites())
return template.render(settings=settings, sites_len=sites_len).encode('utf8')
def render_POST(self, request):
request.responseHeaders.addRawHeader(b"content-type", b"application/json")
response = { 'Error': None,
'Url': "",
'Url_components': None,
'Token': "",
'Email': "",
'Hostname': "",
'Auth': ''}
try:
try:
token_type = request.args.get('type', None)[0]
if token_type not in ['web',
'dns',
'web_image',
'ms_word',
'adobe_pdf',
'windows_dir',
'clonedsite',
'qr_code',
'svn',
'smtp',
'sql_server',
'signed_exe']:
raise Exception()
except:
raise Exception('Unknown type')
try:
email = request.args.get('email', None)[0]
webhook = request.args.get('webhook', None)[0]
if not email and not webhook:
response['Error'] = 1
raise Exception('No email/webhook supplied')
except IndexError:
response['Error'] = 1
raise Exception('No email supplied')
try:
memo = ''.join(request.args.get('memo', None))
if not memo:
response['Error'] = 2
raise Exception('No memo supplied')
except TypeError:
response['Error'] = 2
raise Exception('No memo supplied')
if webhook and not is_webhook_valid(webhook):
response['Error'] = 3
raise Exception('Invalid webhook supplied')
alert_email_enabled = False if not email else True
alert_webhook_enabled = False if not webhook else True
canarytoken = Canarytoken()
if token_type == "web":
#always enable the browser scanner by default
browser_scanner = True
else:
browser_scanner = False
canarydrop = Canarydrop(type=token_type,generate=True,
alert_email_enabled=alert_email_enabled,
alert_email_recipient=email,
alert_webhook_enabled=alert_webhook_enabled,
alert_webhook_url=webhook,
canarytoken=canarytoken.value(),
memo=memo,
browser_scanner_enabled=browser_scanner)
if settings.TWILIO_ENABLED:
try:
if not request.args['mobile'][0]:
raise KeyError
canarydrop['alert_sms_recipient'] = request.args['mobile'][0]
canarydrop['alert_sms_enabled'] = True
except KeyError:
canarydrop['alert_sms_recipient'] = ''
canarydrop['alert_sms_enabled'] = False
save_canarydrop(canarydrop)
response['Token'] = canarytoken.value()
response['Url'] = canarydrop.get_url()
response['Hostname'] = canarydrop.get_hostname()
response['Auth'] = canarydrop['auth']
response['Email'] = email
response['Url_components'] = list(canarydrop.get_url_components())
save_canarydrop(canarydrop)
try:
clonedsite = request.args['clonedsite'][0]
if not clonedsite:
raise KeyError
cloned_token = {'clonedsite': clonedsite,
'canarytoken': canarytoken.value()}
canarydrop.clonedsite_token = save_clonedsite_token(cloned_token)
canarydrop['clonedsite'] = clonedsite
save_canarydrop(canarydrop)
response['clonedsite_js'] = canarydrop.get_cloned_site_javascript()
response['clonedsite'] = clonedsite
except (IndexError, KeyError):
pass
try:
if not request.args.get('type', None)[0] == 'qr_code':
raise Exception()
response['qrcode_png'] = canarydrop.get_qrcode_data_uri_png()
except:
pass
try:
if not request.args.get('type', None)[0] == 'web_image':
raise Exception()
if not settings.WEB_IMAGE_UPLOAD_PATH:
raise Exception("Image upload not supported, set CANARY_WEB_IMAGE_UPLOAD_PATH in frontend.env.")
fields = cgi.FieldStorage(
fp = request.content,
headers = request.getAllHeaders(),
environ = {'REQUEST_METHOD':'POST',
'CONTENT_TYPE': request.getAllHeaders()['content-type'],
}
)
filename = fields['web_image'].filename
filebody = fields['web_image'].value
if len(filebody) > settings.MAX_UPLOAD_SIZE:
raise Exception('File too large')
if not filename.lower().endswith(('.png','.gif','.jpg')):
raise Exception('Uploaded image must be a PNG, GIF or JPG')
ext = filename.lower()[-4:]
#create a random local filename
r = hashlib.md5(os.urandom(32)).hexdigest()
filepath = os.path.join(settings.WEB_IMAGE_UPLOAD_PATH,
r[:2],
r[2:])+ext
if not os.path.exists(os.path.dirname(filepath)):
try:
os.makedirs(os.path.dirname(filepath))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filepath, "w") as f:
f.write(filebody)
canarydrop['web_image_enabled'] = True
canarydrop['web_image_path'] = filepath
save_canarydrop(canarydrop)
except:
pass
try:
if request.args.get('type', None)[0] != 'signed_exe':
raise Exception()
fields = cgi.FieldStorage(
fp = request.content,
headers = request.getAllHeaders(),
environ = {'REQUEST_METHOD':'POST',
'CONTENT_TYPE': request.getAllHeaders()['content-type'],
}
)#hacky way to parse out file contents and filenames
filename = fields['signed_exe'].filename
filebody = fields['signed_exe'].value
if len(filebody) > settings.MAX_UPLOAD_SIZE:
raise Exception('File too large')
if not filename.lower().endswith(('exe','dll')):
raise Exception('Uploaded authenticode file must be an exe or dll')
signed_contents = make_canary_authenticode_binary(hostname=
canarydrop.get_hostname(with_random=False, as_url=True),
filebody=filebody)
response['file_name'] = filename
response['file_contents'] = "data:octet/stream;base64,"+base64.b64encode(signed_contents)
except:
pass
except Exception as e:
if response['Error'] is None:
response['Error'] = 255
log.err('Unexpected error: {err}'.format(err=e))
return simplejson.dumps(response)
class DownloadPage(resource.Resource):
isLeaf = True
def getChild(self, name, request):
if name == '':
return self
return Resource.getChild(self, name, request)
def render_GET(self, request):
try:
token = request.args.get('token', None)[0]
fmt = request.args.get('fmt', None)[0]
auth = request.args.get('auth', None)[0]
canarydrop = Canarydrop(**get_canarydrop(canarytoken=token))
if not canarydrop:
raise NoCanarytokenPresent()
if not canarydrop['auth'] or canarydrop['auth'] != auth:
raise NoCanarytokenPresent()
if fmt == 'zip':
request.setHeader("Content-Type", "application/zip")
request.setHeader("Content-Disposition",
'attachment; filename={token}.zip'\
.format(token=token))
return make_canary_zip(hostname=
canarydrop.get_hostname(with_random=False))
elif fmt == 'msword':
request.setHeader("Content-Type",
"application/vnd.openxmlformats-officedocument"+\
".wordprocessingml.document")
request.setHeader("Content-Disposition",
'attachment; filename={token}.docx'\
.format(token=token))
return make_canary_msword(url=canarydrop.get_url())
elif fmt == 'pdf':
request.setHeader("Content-Type", "application/pdf")
request.setHeader("Content-Disposition",
'attachment; filename={token}.pdf'\
.format(token=token))
return make_canary_pdf(hostname=canarydrop.get_hostname(nxdomain=True, with_random=False))
except Exception as e:
log.err('Unexpected error in download: {err}'.format(err=e))
return NoResource().render(request)
def render_POST(self, request):
try:
fields = cgi.FieldStorage(
fp = request.content,
headers = request.getAllHeaders(),
environ = {'REQUEST_METHOD':'POST',
'CONTENT_TYPE': request.getAllHeaders()['content-type'],
}
)#hacky way to parse out file contents and filenames
token = request.args.get('token', None)[0]
fmt = request.args.get('fmt', None)[0]
if fmt not in ['authenticode']:
raise Exception('Unsupported token type for POST.')
canarydrop = Canarydrop(**get_canarydrop(canarytoken=token))
if not canarydrop:
raise NoCanarytokenPresent()
if fmt == 'authenticode':
filename = fields['file_for_signing'].filename
filebody = fields['file_for_signing'].value
if len(filebody) > settings.MAX_UPLOAD_SIZE:
raise Exception('File too large')
if not filename.lower().endswith(('exe','dll')):
raise Exception('Uploaded authenticode file must be an exe or dll')
signed_contents = make_canary_authenticode_binary(hostname=
canarydrop.get_hostname(with_random=False, as_url=True),
filebody=filebody)
request.setHeader("Content-Type", "octet/stream")
request.setHeader("Content-Disposition",
'attachment; filename={filename}.signed'\
.format(filename=filename))
return signed_contents
except Exception as e:
log.err('Unexpected error in POST download: {err}'.format(err=e))
template = env.get_template('error.html')
return template.render(error=e.message).encode('utf8')
return NoResource().render(request)
class ManagePage(resource.Resource):
isLeaf = True
def getChild(self, name, request):
if name == '':
return self
return Resource.getChild(self, name, request)
def render_GET(self, request):
try:
token = request.args.get('token', None)[0]
auth = request.args.get('auth', None)[0]
canarydrop = Canarydrop(**get_canarydrop(canarytoken=token))
if not canarydrop['auth'] or canarydrop['auth'] != auth:
raise NoCanarytokenPresent()
if canarydrop.get('triggered_list', None):
for timestamp in canarydrop['triggered_list'].keys():
formatted_timestamp = datetime.datetime.fromtimestamp(
float(timestamp)).strftime('%Y %b %d %H:%M:%S')
canarydrop['triggered_list'][formatted_timestamp] = canarydrop['triggered_list'].pop(timestamp)
except (TypeError, NoCanarytokenPresent):
return NoResource().render(request)
g_api_key = get_canary_google_api_key()
try:
canarydrop['type']
template = env.get_template('manage_new.html')
except KeyError:
template = env.get_template('manage.html')
return template.render(canarydrop=canarydrop, API_KEY=g_api_key).encode('utf8')
def render_POST(self, request):
try:
try:
token = request.args.get('token', None)[0]
auth = request.args.get('auth', None)[0]
canarydrop = Canarydrop(**get_canarydrop(canarytoken=token))
if not canarydrop['auth'] or canarydrop['auth'] != auth:
raise NoCanarytokenPresent()
except (IndexError, TypeError, NoCanarytokenPresent):
return NoResource().render(request)
try:
email_enable_status = request.args.get('email_enable', None)[0] == "on"
except (TypeError, IndexError):
email_enable_status = False
try:
webhook_enable_status = request.args.get('webhook_enable', None)[0] == "on"
except (TypeError, IndexError):
webhook_enable_status = False
try:
sms_enable_status = request.args.get('sms_enable', None)[0] == "on"
except (TypeError, IndexError):
sms_enable_status = False
try:
web_image_status = request.args.get('web_image_enable', None)[0] == "on"
except (TypeError, IndexError):
web_image_status = False
try:
token_fmt = request.args.get('fmt', None)[0]
except (TypeError, IndexError):
token_fmt = ''
canarydrop['alert_email_enabled'] = email_enable_status
canarydrop['alert_webhook_enabled'] = webhook_enable_status
canarydrop['alert_sms_enabled'] = sms_enable_status
canarydrop['web_image_enabled'] = web_image_status
save_canarydrop(canarydrop=canarydrop)
g_api_key = get_canary_google_api_key()
template = env.get_template('manage.html')
return template.render(canarydrop=canarydrop, saved=True,
settings=settings, API_KEY=g_api_key).encode('utf8')
except Exception as e:
import traceback
log.err('Exception in manage.html: {e}, {stack}'.format(e=e, stack=traceback.format_exc()))
template = env.get_template('manage.html')
return template.render(canarydrop=canarydrop, error=e,
settings=settings).encode('utf8')
class HistoryPage(resource.Resource):
isLeaf = True
def getChild(self, name, request):
if name == '':
return self
return Resource.getChild(self, name, request)
def render_GET(self, request):
try:
token = request.args.get('token', None)[0]
auth = request.args.get('auth', None)[0]
canarydrop = Canarydrop(**get_canarydrop(canarytoken=token))
if not canarydrop['auth'] or canarydrop['auth'] != auth:
raise NoCanarytokenPresent()
if canarydrop.get('triggered_list', None):
for timestamp in canarydrop['triggered_list'].keys():
formatted_timestamp = datetime.datetime.fromtimestamp(
float(timestamp)).strftime('%Y %b %d %H:%M:%S')
canarydrop['triggered_list'][formatted_timestamp] = canarydrop['triggered_list'].pop(timestamp)
except (TypeError, NoCanarytokenPresent):
return NoResource().render(request)
g_api_key = get_canary_google_api_key()
template = env.get_template('history.html')
return template.render(canarydrop=canarydrop, API_KEY=g_api_key).encode('utf8')
class LimitedFile(File):
def directoryListing(self):
dl = DirectoryLister(self.path,
[],
self.contentTypes,
self.contentEncodings,
self.defaultType)
dl.template = ""
return dl
class SettingsPage(resource.Resource):
isLeaf = True
def getChild(self, name, request):
if name == '':
return self
return Resource.getChild(self, name, request)
def render_POST(self, request):
request.responseHeaders.addRawHeader(b"content-type", b"application/json")
response = { }
try:
token = request.args.get('token', None)[0]
auth = request.args.get('auth', None)[0]
setting = request.args.get('setting', None)[0]
canarydrop = Canarydrop(**get_canarydrop(canarytoken=token))
if not canarydrop['auth'] or canarydrop['auth'] != auth:
raise NoCanarytokenPresent()
if setting not in ['clonedsite', 'email_enable', 'webhook_enable',
'sms_enable', 'browser_scanner_enable', 'web_image_enable']:
raise NoCanarytokenPresent()
except (IndexError, TypeError, NoCanarytokenPresent):
return NoResource().render(request)
if setting == 'clonedsite':
try:
clonedsite = request.args['clonedsite'][0]
if not clonedsite:
raise KeyError
cloned_token = {'clonedsite': clonedsite,
'canarytoken': token}
canarydrop.clonedsite_token = save_clonedsite_token(cloned_token)
save_canarydrop(canarydrop)
response['clonedsite_js'] = canarydrop.get_cloned_site_javascript()
response['clonedsite'] = clonedsite
except (IndexError, KeyError):
return NoResource().render(request)
elif setting == "email_enable":
canarydrop['alert_email_enabled'] = request.args['value'][0] == "on"
elif setting == "webhook_enable":
canarydrop['alert_webhook_enabled'] = request.args['value'][0] == "on"
elif setting == "sms_enable":
canarydrop['alert_sms_enabled'] = request.args['value'][0] == "on"
elif setting == "browser_scanner_enable":
canarydrop['browser_scanner_enabled'] = request.args['value'][0] == "on"
elif setting == "web_image_enable":
canarydrop['web_image_enabled'] = request.args['value'][0] == "on"
save_canarydrop(canarydrop=canarydrop)
response['result'] = 'success'
return simplejson.dumps(response)
class CanarytokensHttpd():
def __init__(self, port=80):
self.port = port
root = Resource()
root.putChild("", Redirect("generate"))
root.putChild("generate", GeneratorPage())
root.putChild("manage", ManagePage())
root.putChild("download", DownloadPage())
root.putChild("settings", SettingsPage())
root.putChild("history", HistoryPage())
root.putChild("resources", LimitedFile("/srv/templates/static"))
with open('/srv/templates/robots.txt', 'r') as f:
root.putChild("robots.txt", Data(f.read(), "text/plain"))
wrapped = EncodingResourceWrapper(root, [GzipEncoderFactory()])
site = server.Site(wrapped)
if settings.DEBUG:
site.displayTracebacks = settings.DEBUG
else:
site.displayTracebacks = False
self.service = internet.TCPServer(self.port, site)
return None