forked from n8fr8/UnveillanceViewer
/
index.py
511 lines (408 loc) · 12.9 KB
/
index.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
import requests, signal, sys, re, os, hashlib, base64, json, copy
import tornado.ioloop
import tornado.web
import tornado.httpserver
from mako.template import Template
from conf import server_port, use_ssl, cert_file, key_file, auth_root, user_root, uurl, assets_path, cookie_tag, admin_cookie_tag, cookie_secret, no_access_cookie
from funcs import createNewUser, getPrivateIV, getFileSalt, getPasswordSalt, encrypt, pad, unpad, decrypt
import urlparse, urllib
class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
status = getStatus(self)
if status == 2 or status == 3:
cookie = self.get_secure_cookie(cookie_tag)
return json.loads(base64.b64decode(cookie))['username']
if status == 0:
return '$PUBLIC_USER' # TODO
return None
def terminationHandler(signal, frame):
sys.exit(0)
def getStatus(req):
# if you have a NO_ACCESS cookie, well, that's too bad
try:
for cookie in req.request.cookies:
if cookie == no_access_cookie:
return 0
except KeyError as e:
pass
access = req.get_secure_cookie(cookie_tag)
if access is not None:
admin = req.get_secure_cookie(admin_cookie_tag)
if admin is not None:
return 3
return 2
return 1
def getDefaultHome(req):
user = req.get_secure_cookie(cookie_tag)
if user is not None:
user = json.loads(base64.b64decode(user))
try:
return user['default_home']
except KeyError as e:
print e
pass
try:
from conf import default_home
return default_home
except ImportError as e:
print e
pass
return "submissions"
def checkForAdminParty():
for root_, dir_, files in os.walk(user_root):
for f in files:
return False
return True
class PingHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
try:
r = requests.get(uurl)
self.write(r.text)
except requests.exceptions.ConnectionError as e:
print e
self.write({'result':404})
self.finish()
class RouteHandler(BaseHandler):
@tornado.web.asynchronous
def validateUnprivilegedQuery(self, q_list):
if not q_list:
return True
allowed_queries = ["public_hash", "get_all", "capturedOn", "mime_type","hashes"]
'''
for kvp in q_string[1:].split("&"):
key_val = kvp.split("=")
if key_val[0] not in allowed_queries:
return False
'''
for k, _ in q_list:
if k not in allowed_queries:
return False
return True
def getExtraScriptsByStatus(self, status, route):
exts = []
if status == 2 or status == 3:
if route is not None:
if route[0] == "submission":
exts.append(Template(filename="%s/layout/opts/media_browser.html" % static_path).render())
return exts
def getExtraTemplatesByStatus(self, status, route, as_search_result=False):
extra_tmpls = []
if status == 0:
if route == "submission":
extra_tmpls.append(Template(
filename="%s/layout/opts/download_options.html" % static_path
).render())
extra_tmpls.append(Template(
filename="%s/layout/opts/j3mviewer_public.html" % static_path
).render())
if status == 2 or status == 3:
if route == "submission":
extra_tmpls.append(Template(
filename="%s/layout/opts/download_options.html" % static_path
).render())
extra_tmpls.append(Template(
filename="%s/layout/opts/j3mviewer_user.html" % static_path
).render())
# no annotations for now please
# extra_tmpls.append(Template(
# filename="%s/layout/opts/annotate_submission.html" % static_path
# ).render())
if as_search_result:
extra_tmpls.append(Template(
filename="%s/layout/opts/save_search.html" % static_path
).render())
return extra_tmpls
@tornado.web.authenticated
def get(self, route):
# sets xsrf cookie
self.xsrf_token
auth_layout = None
# format query string
q_list = urlparse.parse_qsl(self.request.query, keep_blank_values=True)
q_string = urllib.urlencode(q_list)
extra_scripts = []
status = getStatus(self)
if route is not None:
url = "%s%s" % (uurl, route)
else:
url = "%s%s/" % (uurl, getDefaultHome(self))
print url
format = self.get_query_argument("format", default=None)
as_search_result = False
if format is not None:
q_list = filter(lambda kvp: kvp[0] != "format", q_list)
q_string = urllib.urlencode(q_list)
if q_string:
as_search_result = True
if status == 0 and not self.validateUnprivilegedQuery(q_list):
print self.validateUnprivilegedQuery(q_list)
self.redirect('/')
return
print "%s?%s" % (url, q_string)
try:
r = requests.get("%s?%s" % (url, q_string))
except requests.exceptions.ConnectionError as e:
error_tmpl = Template(filename="%s/layout/errors/error_no_api.html" % static_path)
self.finish(main_layout.render(
template_content=error_tmpl.render(),
data={},
authentication_holder='',
search_ctrl='',
extra_scripts='',
authentication_ctrl=''
))
return
tmpl_extras = []
if format:
self.write(r.text.replace(assets_path, ""))
else:
if route is not None:
route = route.split("/")
route[:] = [word for word in route if word != '']
if len(route) >= 3 and route[0] == "submission" and route[2] in media_routes:
if route[2] == media_routes[0]:
self.finish(r.text.replace(assets_path, ""))
elif route[2] == media_routes[1]:
self.set_header("Content-Type", r.headers['content-type'])
self.finish(r.content)
return
layout = route[0]
tmpl_extras.extend(self.getExtraTemplatesByStatus(status, route[0], as_search_result))
else:
if status == 0:
layout = "main_public"
else:
layout = "main"
layout = "%s_%s" % (getDefaultHome(self), layout)
if status == 2 or status == 3:
auth_layout = "logout_ctrl"
extra_scripts.append(Template(
filename="%s/layout/authentication/enable_user.html" % static_path
).render())
else:
extra_scripts.append(Template(
filename="%s/layout/authentication/disable_user.html" % static_path
).render())
tmpl = Template(filename="%s/layout/%s.html" % (static_path, layout))
authentication_holder = ''
if status != 0:
auth_tmpl = Template(filename="%s/layout/authentication/%s.html" % (static_path, auth_layout))
authentication_holder = auth_tmpl.render()
authentication_ctrl = ''
if status == 3:
authentication_ctrl = Template(
filename="%s/layout/authentication/admin_ctrl.html" % static_path
).render()
search_ctrl = Template(
filename="%s/layout/searches/search_ctrl.html" % static_path
).render()
extra_scripts.extend(self.getExtraScriptsByStatus(status, route))
data = json.loads(r.text.replace(assets_path, ""))
#print data
self.finish(main_layout.render(
template_content=tmpl.render(extras="".join(tmpl_extras)),
authentication_holder=authentication_holder,
search_ctrl=search_ctrl,
extra_scripts="".join(extra_scripts),
authentication_ctrl=authentication_ctrl,
data=json.dumps(data)
))
class LeafletHandler(tornado.web.RequestHandler):
def get(self, route):
r = requests.get("http://cdn.leafletjs.com/leaflet-0.6.4/%s" % route)
self.finish(r.content)
class EaselHandler(tornado.web.RequestHandler):
def get(self, route):
r = requests.get("http://code.createjs.com/%s" % route)
self.finish(r.content)
class LoginHandler(BaseHandler):
@tornado.web.asynchronous
def get(self):
# sets xsrf cookie
self.xsrf_token
auth_layout = Template(filename="%s/layout/authentication/login_ctrl.html" % static_path).render()
# first, let's see if you have any user files
if checkForAdminParty():
auth_stopgap = Template(
filename="%s/layout/authentication/admin_party.html" % static_path
).render()
else:
auth_stopgap = Template(
filename="%s/layout/errors/error_not_logged_in.html" % static_path
).render()
extra_scripts = Template(
filename="%s/layout/authentication/disable_user.html" % static_path
).render()
self.finish(main_layout.render(
template_content=auth_stopgap,
authentication_holder='',
search_ctrl='',
extra_scripts=extra_scripts,
authentication_ctrl=auth_layout,
data=''
))
@tornado.web.asynchronous
def post(self):
if getStatus(self) == 0:
self.finish({'ok':False})
return
username = ''
password = ''
credentials = self.request.body
for kvp in credentials.split("&"):
kv = kvp.split("=")
if kv[0] == "username":
username = kv[1]
elif kv[0] == "password":
password = kv[1]
if not username or not password:
self.finish({'ok':False})
return
#createNewUser(username, password)
auth = "%s.txt" % hashlib.sha1(username + getFileSalt()).hexdigest()
# if this file exists,
try:
f = open(os.path.join(user_root, auth), 'rb')
ciphertext = f.read()
f.close()
# decrypt it using supplied password.
plaintext = decrypt(ciphertext, password, p_salt=getPasswordSalt())
# if that works, send back plaintext
if plaintext is not None:
try:
if plaintext['admin']:
del plaintext['admin']
self.set_secure_cookie(admin_cookie_tag, "true", path="/", expires_days=1)
except KeyError as e:
pass
new_cookie = base64.b64encode(json.dumps(plaintext))
if new_cookie is not None:
self.set_secure_cookie(cookie_tag, new_cookie, path="/", expires_days=1)
self.finish({'ok':True, 'user' : plaintext})
return
except IOError as e:
print e
pass
self.finish({'ok':False})
class LogoutHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def post(self):
if getStatus(self) == 0:
self.finish({'ok':False})
return
self.clear_cookie(cookie_tag)
self.clear_cookie(admin_cookie_tag)
if self.request.body != "":
try:
credentials = json.loads(self.request.body)
auth = "%s.txt" % hashlib.sha1(credentials['user']['username'] + getFileSalt()).hexdigest()
f = open(os.path.join(user_root, auth), 'rb')
ciphertext = f.read()
f.close()
# decrypt it using supplied password.
plaintext = decrypt(ciphertext, credentials['password'], p_salt=getPasswordSalt())
# if that works, encrypt new data
if plaintext is not None:
new_data = copy.deepcopy(plaintext)
new_data['saved_searches'] = credentials['user']['saved_searches']
# also, new_data might have ['default_home']
f = open(os.path.join(user_root, auth), 'wb+')
f.write(encrypt(
new_data,
credentials['password'],
iv=getPrivateIV(),
p_salt=getPasswordSalt()
))
f.close()
else:
self.finish({'ok':False})
return
except ValueError as e:
print e
self.finish({'ok':False})
return
except TypeError as e:
print e
self.finish({'ok':False})
return
self.finish({'ok':True})
class ImportHandler(tornado.web.RequestHandler):
def post(self):
status = getStatus(self)
if status != 3:
self.finish({'ok':False})
return
try:
file = {
'file' : (
self.request.files['file'][0]['filename'],
self.request.files['file'][0]['body']
)
}
r = requests.post("%simport/" % uurl, files=file)
self.finish(json.loads(r.content))
return
except requests.exceptions.ConnectionError as e:
print e
pass
self.finish({'ok':False})
class UserHandler(tornado.web.RequestHandler):
def post(self):
status = getStatus(self)
if status != 3:
if not checkForAdminParty() and status == 1:
self.finish({'ok':False})
return
username = ''
password = ''
credentials = self.request.body
for kvp in credentials.split("&"):
kv = kvp.split("=")
if kv[0] == "username":
username = kv[1]
elif kv[0] == "password":
password = kv[1]
if len(username) < 4 or len(password) < 6:
self.finish({'ok':False})
return
if not re.match(r'[a-zA-Z0-9_\-]+$', username):
print "THIS DOES NOT MATCH THE SPEC!"
self.finish({'ok':False})
return
if createNewUser(username, password, as_admin=checkForAdminParty()):
self.finish({'ok' : True})
return
self.finish({'ok':False})
static_path = os.path.join(os.path.dirname(__file__), "web")
main_layout = Template(filename="%s/index.html" % static_path)
media_routes = ["j3m", "media"]
routes = [
(r"/web/([a-zA-Z0-9\-/\._]+)", tornado.web.StaticFileHandler, {"path" : static_path }),
(r"/leaflet/(.*)", LeafletHandler),
(r"/easel/(.*)", EaselHandler),
(r"/login/", LoginHandler),
(r"/logout/", LogoutHandler),
(r"/upanel/", UserHandler),
(r"/import/", ImportHandler),
(r"/ping/", PingHandler),
(r"/([a-zA-Z0-9/]*/$)?", RouteHandler),
]
settings = {
'cookie_secret': cookie_secret,
'login_url': '/login/',
'xsrf_cookies': True
}
app = tornado.web.Application(routes, **settings)
signal.signal(signal.SIGINT, terminationHandler)
if __name__ == "__main__":
if (use_ssl == False):
app.listen(server_port)
else:
server = tornado.httpserver.HTTPServer(app, ssl_options={
'certfile' : os.path.join(auth_root, cert_file),
'keyfile': os.path.join(auth_root, key_file)
})
server.bind(server_port)
server.start(50)
tornado.ioloop.IOLoop.instance().start()