forked from harlo/UnveillanceInterface
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
368 lines (282 loc) · 10.1 KB
/
api.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
import os, requests, json, re, copy, urllib
from subprocess import Popen, PIPE
from time import sleep
from itertools import chain
from io import BytesIO
from Models.uv_annex_client import UnveillanceAnnexClient
from lib.Core.vars import Result
from lib.Core.Utils.funcs import parseRequestEntity, generateMD5Hash
from conf import PERMISSIONS, BASE_DIR, buildServerURL, DEBUG, SERVER_HOST, CONF_ROOT, getConfig, getSecrets, USER_ROOT
from vars import FILE_NON_OVERWRITES, USER_CREDENTIAL_PACK, UnveillanceCookie, MIME_TYPE_TASK_REQUIREMENTS
class UnveillanceAPI():
def __init__(self):
print "Stock Unveillance Frontend API started..."
self.UNVEILLANCE_LM_VARS = {}
def do_documents(self, handler): return self.passToAnnex(handler)
def do_list(self, handler): return self.passToAnnex(handler)
def do_cluster(self, handler): return self.passToAnnex(handler)
def do_reindex(self, handler):
req = parseRequestEntity(handler.request.body)
if req is None:
return None
if '_id' not in req.keys():
return None
'''
we might have to replace parts of the request with
secret values.
'''
if 'task_path' in req.keys():
req_keys = list(chain.from_iterable(
[k.keys() for k in MIME_TYPE_TASK_REQUIREMENTS]))
if req['task_path'] in req_keys:
try:
req_field = [k for k in MIME_TYPE_TASK_REQUIREMENTS if k.keys()[0] == req['task_path']][0][req['task_path']]
print req_field
except Exception as e:
if DEBUG: print "Could not resolve required task info. %s" % e
for repl in req_field.iteritems():
if repl[0] in req.keys():
handler.request.body = handler.request.body.replace(
repl[1], getSecrets(repl[1]))
return self.passToAnnex(handler)
def do_import(self, handler):
status = self.do_get_status(handler)
if status not in PERMISSIONS['upload_local']:
return
for s_a in handler.request.files.keys():
if s_a != "uv_import":
save_as = handler.request.files[s_a][0]
break
try:
entry = BytesIO()
entry.write(save_as['body'])
except Exception as e:
if DEBUG:
print "COULD NOT CREATE FILE FROM BLOB %s" % e
return None
netcat_stub = {
'save_as' : save_as['filename'],
'file' : entry,
'importer_source' : "web_frontend_status_%d" % status
}
if status not in PERMISSIONS['upload_global']:
# add this filename to the restricted list in handler
if DEBUG:
print "SINCE STATUS == %d, this file will be restricted locally" % status
#netcat_stub['for_local_use_only'] = True
res = self.checkForDuplicate(self.get_new_hash(netcat_stub['file']))
if res is None:
res = {
'file_name' : save_as['filename'],
'result' : 403,
'duplicate_attempt' : False
}
else:
res.update({
'result' : 200, # or??
'duplicate_attempt' : True
})
return res
else:
try:
res = self.addToNetcatQueue(netcat_stub)
if 'duplicate_attempt' not in res.keys():
res.update({
'file_name' : save_as['filename'],
'result' : 200 if res['uploaded'] else 403
})
return res
except Exception as e:
if DEBUG:
print "ERROR IN NETCAT: %s" % e
return None
def do_open_drive_file(self, handler):
if DEBUG: print "opening this drive file in unveillance annex"
status = self.do_get_status(handler)
if status not in [2,3]:
if DEBUG: print "NO-ACCESS TO THIS METHOD (\"do_open_drive_file\")"
return None
files = None
self.initDriveClient(handler)
for _id in parseRequestEntity(handler.request.query)['_ids']:
_id = urllib.unquote(_id).replace("'", "")[1:]
file_name = self.drive_client.getFileName(_id)
if file_name is None: return None
url = "%s/documents/?file_name=%s" % (buildServerURL(), file_name)
entry = None
handled_file = None
if DEBUG: print url
# look up the file in annex. (annex/documents/?file_name=file)
# if this file exists in annex, return its _id for opening in-app
try:
entry = json.loads(requests.get(
url, verify=False).content)['data']['documents'][0]
except Exception as e:
if DEBUG: print "COULD NOT GET ENTRY:\n%s" % e
if entry is not None:
if DEBUG: print type(entry['_id'])
handled_file = { '_id' : entry['_id'] }
else:
if status != 3:
if DEBUG:
print "** at this point, we would process file if you were admin"
print "** but you are not admin."
return None
entry = self.drive_client.download(_id,
save_as=file_name, save=False, return_content=True)
if entry is not None:
self.addToNetcatQueue({
'file' : entry[0],
'save_as' : entry[1],
'importer_source' : "google_drive"
})
handled_file = { 'file_name' : entry[1] }
if handled_file is not None:
if files is None: files = []
files.append(handled_file)
return files
def do_get_admin_party_status(self, handler):
status = self.do_get_status(handler)
if status == 0: return None
from conf import USER_ROOT
for _, _, files in os.walk(USER_ROOT):
for f in files: return False
return True
def do_create_new_user(self, handler):
status = self.do_get_status(handler)
if status != 3: return None
new_user = parseRequestEntity(handler.request.body)
if new_user is None: return None
if DEBUG: print new_user
n_set = sorted(['nu_username', 'nu_password'])
if sorted(list(set(n_set) & set(new_user.keys()))) != n_set:
return None
from Utils.funcs import createNewUser
return createNewUser(new_user['nu_username'], new_user['nu_password'])
def do_get_user_status(self, handler):
status = self.do_get_status(handler)
if status == 0: return None
if self.do_get_admin_party_status(handler): return 4
return status
def do_get_status(self, handler):
try:
for cookie in handler.request.cookies:
if cookie == UnveillanceCookie.PUBLIC:
print "**** VISITOR OF TYPE ZERO ENCOUNTERED: %s *****" % UnveillanceCookie.PUBLIC
return 0
except KeyError as e: pass
access = handler.get_secure_cookie(UnveillanceCookie.USER)
if access is not None:
if handler.get_secure_cookie(UnveillanceCookie.ADMIN) is not None:
return 3
return 2
return 1
def do_get_drive_status(self, handler=None):
if handler is not None:
if self.do_get_status(handler) == 0: return None
# TODO: actually, if not 3
if hasattr(self, "drive_client"):
if hasattr(self.drive_client, "service"):
return True
return False
def do_logout(self, handler):
status = self.do_get_status(handler)
if status not in [2, 3]:
if DEBUG: print "CANNOT LOG IN USER, DON'T EVEN TRY (status %d)" % status
return None
credentials = parseRequestEntity(handler.request.body)
if credentials is None: return None
if DEBUG: print credentials
return self.logoutUser(credentials, handler)
def do_login(self, handler):
status = self.do_get_status(handler)
if status != 1:
if DEBUG: print "CANNOT LOG IN USER, DON'T EVEN TRY (status %d)" % status
return None
credentials = parseRequestEntity(handler.request.body)
if credentials is None: return None
if DEBUG: print credentials
try:
return self.loginUser(credentials['username'],
credentials['password'], handler)
except KeyError as e:
if DEBUG: print "CANNOT LOG IN USER: %s missing" % e
return None
def initDriveClient(self, restart=False):
if DEBUG: print "INITING DRIVE CLIENT"
if not hasattr(self, "drive_client") or restart:
self.drive_client = UnveillanceAnnexClient()
sleep(2)
return self.do_get_drive_status()
def logoutUser(self, credentials, handler):
handler.clear_cookie(UnveillanceCookie.USER)
handler.clear_cookie(UnveillanceCookie.ADMIN)
try:
username = credentials['username']
except KeyError as e: return None
try:
password = credentials['password']
except KeyError as e: return True
try:
IV = getConfig('encryption.iv')
SALT = getConfig('encryption.salt')
USER_SALT = getConfig('encyption.user_salt')
except Exception as e:
if DEBUG: print e
return None
try:
from Utils.funcs import decryptUserData, encryptUserData
except Exception as e:
if DEBUG: print e
from lib.Frontend.Utils.funcs import decryptUserData, encryptUserData
user_root = "%s.txt" % generateMD5Hash(content=username,salt=USER_SALT)
with open(os.path.join(USER_ROOT, user_root), 'rb') as UD:
user_data = decryptUserData(UD.read, password, p_salt=SALT)
if user_data is None: return None
new_data = copy.deepcopy(user_data)
new_data['saved_searches'] = credentials['save_data']['saved_searches']
try:
new_data['annex_key_sent'] = credentials['save_data']['annex_key_sent']
except KeyError as e:
pass
with open(os.path.join(USER_ROOT, user_root), 'wb+') as UD:
UD.write(encryptUserData(new_data, password, iv=IV, p_salt=SALT))
return True
return None
def loginUser(self, username, password, handler):
try:
SALT = getConfig('encryption.salt')
USER_SALT = getConfig('encyption.user_salt')
except Exception as e:
if DEBUG: print e
return None
from base64 import b64encode
try:
from Utils.funcs import decryptUserData
except Exception as e:
if DEBUG: print e
from lib.Frontend.Utils.funcs import decryptUserData
try:
user_root = "%s.txt" % generateMD5Hash(content=username, salt=USER_SALT)
with open(os.path.join(USER_ROOT, user_root), 'rb') as UD:
user_data = decryptUserData(UD.read(), password, p_salt=SALT)
if user_data is None: return None
try:
if user_data['admin']:
del user_data['admin']
handler.set_secure_cookie(UnveillanceCookie.ADMIN,
"true", path="/", expires_days=1)
if not self.do_get_drive_status():
self.initDriveClient()
if "annex_key_sent" not in user_data.keys() or not user_data['annex_key_sent']:
if self.drive_client.checkAnnexKeyStatus():
user_data['annex_key_sent'] = True
except KeyError as e:
if DEBUG: print e
pass
handler.set_secure_cookie(UnveillanceCookie.USER,
b64encode(json.dumps(user_data)), path="/", expires_days=1)
return user_data
except Exception as e:
if DEBUG: print e
return None