forked from hashtopolis/agent-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashtopolis.py
More file actions
411 lines (320 loc) · 12.2 KB
/
Copy pathhashtopolis.py
File metadata and controls
411 lines (320 loc) · 12.2 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# PoC testing/development framework for APIv2
# Written in python to work on creation of hashtopolis APIv2 python binding.
#
import json
import requests
import unittest
import datetime
from pathlib import Path
from io import BytesIO
import requests
import unittest
import logging
from pathlib import Path
import abc
import http
import confidence
import tusclient.client
#logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
HTTP_DEBUG = False
# Monkey patching to allow http debugging
if HTTP_DEBUG:
http_logger = logging.getLogger('http.client')
http.client.HTTPConnection.debuglevel = 0
def print_to_log(*args):
http_logger.debug(" ".join(args))
http.client.print = print_to_log
cls_registry = {}
class HashtopolisConfig(object):
def __init__(self):
# Request access TOKEN, used throughout the test
load_order = confidence.DEFAULT_LOAD_ORDER + (str(Path(__file__).parent.joinpath('{name}.{extension}')),)
self._cfg = confidence.load_name('hashtopolis-test', load_order=load_order)
self._hashtopolis_uri = self._cfg['hashtopolis_uri']
self._api_endpoint = self._hashtopolis_uri + '/api/v2'
self.username = self._cfg['username']
self.password = self._cfg['password']
class HashtopolisConnector(object):
# Cache authorisation token per endpoint
token = {}
token_expires = {}
def __init__(self, model_uri, config):
self._model_uri = model_uri
self._api_endpoint = config._api_endpoint
self._hashtopolis_uri = config._hashtopolis_uri
self.config = config
def authenticate(self):
if not self._api_endpoint in HashtopolisConnector.token:
# Request access TOKEN, used throughout the test
logger.info("Start authentication")
auth_uri = self._api_endpoint + '/auth/token'
auth = (self.config.username, self.config.password)
r = requests.post(auth_uri, auth=auth)
HashtopolisConnector.token[self._api_endpoint] = r.json()['token']
HashtopolisConnector.token_expires[self._api_endpoint] = r.json()['token']
self._token = HashtopolisConnector.token[self._api_endpoint]
self._token_expires = HashtopolisConnector.token_expires[self._api_endpoint]
self._headers = {
'Authorization': 'Bearer ' + self._token,
'Content-Type': 'application/json'
}
def filter(self, expand, filter):
self.authenticate()
uri = self._api_endpoint + self._model_uri
headers = self._headers
filter_list = []
cast = {
'__gt': '>',
'__gte': '>=',
'__lt': '<',
'__lte': '<=',
}
for k,v in filter.items():
l = None
for k2,v2 in cast.items():
if k.endswith(k2):
l = f'{k[:-len(k2)]}{v2}{v}'
break
# Default to equal assignment
if l == None:
l = f'{k}={v}'
filter_list.append(l)
payload = {
'filter': filter_list,
'expand': expand
}
r = requests.get(uri, headers=headers, data=json.dumps(payload))
if r.status_code != 201:
logger.exception("Filter failed: %s", r.text)
return r.json().get('values')
def patch_one(self, obj):
if not obj.has_changed():
logger.debug("Object '%s' has not changed, no PATCH required", obj)
return
self.authenticate()
uri = self._hashtopolis_uri + obj._self
headers = self._headers
payload = {}
for k,v in obj.diff().items():
logger.debug("Going to patch object '%s' property '%s' from '%s' to '%s'", obj, k, v[0], v[1])
payload[k] = v[1]
r = requests.patch(uri, headers=headers, data=json.dumps(payload))
if r.status_code != 201:
logger.exception("Patching failed: %s", r.text)
# TODO: Validate if return objects matches digital twin
obj.set_initial(r.json().copy())
def create(self, obj):
# Check if object to be created is new
assert(not hasattr(obj, '_self'))
self.authenticate()
uri = self._api_endpoint + self._model_uri
headers = self._headers
payload = dict([(k,v[1]) for (k,v) in obj.diff().items()])
r = requests.post(uri, headers=headers, data=json.dumps(payload))
if r.status_code != 201:
logger.exception("Creation of object failed: %s", r.text)
# TODO: Validate if return objects matches digital twin
obj.set_initial(r.json().copy())
def delete(self, obj):
""" Delete object from database """
# TODO: Check if object to be deleted actually exists
assert(hasattr(obj, '_self'))
self.authenticate()
uri = self._hashtopolis_uri + obj._self
headers = self._headers
payload = {}
r = requests.delete(uri, headers=headers, data=json.dumps(payload))
if r.status_code != 204:
logger.exception("Deletion of object failed: %s", r.text)
# TODO: Cleanup object to allow re-creation
class ManagerBase(type):
conn = {}
# Cache configuration values
config = None
@classmethod
def get_conn(cls):
if cls.config is None:
cls.config = HashtopolisConfig()
if cls._model_uri not in cls.conn:
cls.conn[cls._model_uri] = HashtopolisConnector(cls._model_uri, cls.config)
return cls.conn[cls._model_uri]
@classmethod
def all(cls, expand=None):
"""
Retrieve all backend objects
TODO: Make iterator supporting loading of objects via pages
"""
return cls.filter(expand)
@classmethod
def patch(cls, obj):
cls.get_conn().patch_one(obj)
@classmethod
def create(cls, obj):
cls.get_conn().create(obj)
@classmethod
def delete(cls, obj):
cls.get_conn().delete(obj)
@classmethod
def get_first(cls):
"""
Retrieve first object
TODO: Error handling if first object does not exists
TODO: Request object with limit parameter instead
"""
return cls.all()[0]
@classmethod
def get(cls, expand=None, **kwargs):
objs = cls.filter(expand, **kwargs)
assert(len(objs) == 1)
return objs[0]
@classmethod
def filter(cls, expand=None, **kwargs):
# Get all objects
api_objs = cls.get_conn().filter(expand, kwargs)
# Convert into class
objs = []
if api_objs:
for api_obj in api_objs:
new_obj = cls._model(**api_obj)
objs.append(new_obj)
return objs
# Build Django ORM style 'ModelName.objects' interface
class ModelBase(type):
def __new__(cls, clsname, bases, attrs, uri=None, **kwargs):
parents = [b for b in bases if isinstance(b, ModelBase)]
if not parents:
return super().__new__(cls, clsname, bases, attrs)
new_class = super().__new__(cls, clsname, bases, attrs)
setattr(new_class, 'objects', type('Manager', (ManagerBase,), {'_model_uri': uri}))
setattr(new_class.objects, '_model', new_class)
cls_registry[clsname] = new_class
return new_class
class Model(metaclass=ModelBase):
def __init__(self, *args, **kwargs):
self.set_initial(kwargs)
super().__init__()
def _dict2obj(self, dict):
# Function to convert a dict to an object.
uri = dict.get('_self')
# Loop through all the registers classes
for modelname, model in cls_registry.items():
model_uri = model.objects._model_uri
# Check if part of the uri is in the model uri
if model_uri in uri:
obj = model()
# Set all the attributes of the object.
for k2,v2 in dict.items():
setattr(obj, k2, v2)
if not k2.startswith('_'):
obj.__fields.append(k2)
return obj
# If we are here, it means that no uri matched, thus we don't know the object.
raise(TypeError('Object not valid model'))
def set_initial(self, kv):
self.__fields = []
# Store fields allowing us to detect changed values
if '_self' in kv:
self.__initial = kv.copy()
else:
# New model
self.__initial = {}
# Create attribute values
for k,v in kv.items():
# In case expand is true, there can be a attribute which also is an object.
# Example: Users in AccessGroups. This part will convert the returned data.
# Into proper objects.
if type(v) is list and len(v) > 0:
# Many-to-Many relation
obj_list = []
# Loop through all the values in the list and convert them to objects.
for dict_v in v:
if type(dict_v) is dict and dict_v.get('_self'):
# Double check that it really is an object
obj = self._dict2obj(dict_v)
obj_list.append(obj)
# Set the attribute of the current object to a set object (like Django)
# Also check if it really were objects
if len(obj_list) > 0:
setattr(self, f"{k}_set", obj_list)
continue
# This does the same as above, only one-to-one relations
if type(v) is dict:
setattr(self, f"{k}_set", self._dict2obj(v))
continue
setattr(self, k, v)
if not k.startswith('_'):
self.__fields.append(k)
def diff(self):
d1 = self.__initial
d2 = dict([(k, getattr(self, k)) for k in self.__fields])
diffs = [(k, (v, d2[k])) for k, v in d2.items() if v != d1.get(k, None)]
return dict(diffs)
def has_changed(self):
return bool(self.diff())
def save(self):
if hasattr(self, '_self'):
self.objects.patch(self)
else:
self.objects.create(self)
def delete(self):
if hasattr(self, '_self'):
self.objects.delete(self)
def serialize(self):
return [x for x in vars(self) if not x.startswith('_')]
@property
def id(self):
return self._id
class Agent(Model, uri="/ui/agents"):
def __repr__(self):
return self._self
class Task(Model, uri="/ui/tasks"):
def __repr__(self):
return self._self
class Pretask(Model, uri="/ui/pretasks"):
def __repr__(self):
return self._self
class User(Model, uri="/ui/users"):
def __repr__(self):
return self._self
class Hashlist(Model, uri="/ui/hashlists"):
def __repr__(self):
return self._self
class AccessGroup(Model, uri="/ui/accessgroups"):
def __repr__(self):
return self._self
class Cracker(Model, uri="/ui/crackers"):
def __repr__(self):
return self._self
class CrackerType(Model, uri="/ui/crackertypes"):
def __repr__(self):
return self._self
class Config(Model, uri="/ui/configs"):
def __repr__(self):
return self._self
class File(Model, uri="/ui/files"):
def __repr__(self):
return self._self
class FileImport(HashtopolisConnector):
def __init__(self):
super().__init__("/ui/files/import", HashtopolisConfig())
def __repr__(self):
return self._self
def do_upload(self, filename, file_stream):
self.authenticate()
uri = self._api_endpoint + self._model_uri
my_client = tusclient.client.TusClient(uri)
del self._headers['Content-Type']
my_client.set_headers(self._headers)
metadata = {"filename": filename,
"filetype": "application/text"}
uploader = my_client.uploader(
file_stream=file_stream,
chunk_size=1000000000,
upload_checksum=True,
metadata=metadata
)
uploader.upload()