/
cq_api.py
executable file
·1635 lines (1515 loc) · 63.2 KB
/
cq_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
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import logging
import os
import re
import time
import uuid
import nltk
import rq
from crackq import crackqueue, hash_modes, run_hashcat, auth
from crackq.conf import hc_conf
from datetime import datetime
from flask import (Flask, redirect, request, session, make_response, url_for)
from flask_restful import reqparse, abort, Resource
from logging.config import fileConfig
from marshmallow import Schema, fields, validate, ValidationError
from marshmallow.validate import Length, Range, Regexp
from operator import itemgetter
from pathlib import Path
from pypal import pypal
from redis import Redis
from rq import use_connection, Queue
from saml2 import BINDING_HTTP_POST
from saml2 import BINDING_HTTP_REDIRECT
from saml2 import sigver
from flask_seasurf import SeaSurf
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, login_required, login_user, logout_user, UserMixin, current_user
from flask_session import Session
from crackq.models import User
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy import create_engine, Column, ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.types import (
Boolean,
DateTime,
Integer,
String,
TypeDecorator,
JSON,
)
from sqlalchemy.ext.declarative import declarative_base
#from crackq import create_app
from crackq.db import db
import crackq
import saml2
#from crackq import app
#from wsgi import db, app
#import crackq
#from wsgi import app
# set perms
os.umask(0o077)
# Setup logging
fileConfig('log_config.ini')
logger = logging.getLogger()
login_manager = LoginManager()
app = Flask(__name__)
###***is it possible to move this to __init__?
csrf = SeaSurf()
csrf.init_app(app)
CRACK_CONF = hc_conf()
class StringContains(validate.Regexp):
"""
Custom validation class to reject any strtings matching supplied regex
See validate.Regexp for args/return values
"""
default_message = 'Invalid input for this field.'
def __call__(self, value):
if len(self.regex.findall(value)) > 0:
raise ValidationError(self._format_error(value))
return value
class parse_json_schema(Schema):
"""
Class to create the schema for parsing received JSON arguments
job_details: str
string returned from rq.job.description
Returns
------
deets_dict: dictionary
only the specified job details are returned
"""
error_messages = {
"name": "Invalid input characters",
"username": "Invalid input characters",
}
job_id = fields.UUID(allow_none=False)# validate=Length(min=1, max=32))
batch_job = fields.List(fields.Dict(fields.UUID(), fields.Int(min=0, max=1000)))
place = fields.Int(validate=Range(min=1, max=100))
hash_list = fields.List(fields.String(validate=StringContains(r'[^A-Za-z0-9\*\$\@\/\\\.\:\-\_\+\.]+\~')),
allow_none=True, error_messages=error_messages)
wordlist = fields.Str(allow_none=True, validate=[StringContains(r'[\W]\-'),
Length(min=1, max=60)])
attack_mode = fields.Int(allow_none=True, validate=Range(min=0, max=7))
rules = fields.List(fields.String(validate=[StringContains(r'[\W]\-'),
Length(min=1, max=60)]),
allow_none=True)
username = fields.Bool(allow_none=True)
notify = fields.Bool(allow_none=True)
increment = fields.Bool(allow_none=True)
disable_brain = fields.Bool(allow_none=True)
incement_min = fields.Int(allow_none=True, validate=Range(min=0, max=20))
increment_max = fields.Int(allow_none=True, validate=Range(min=0, max=20))
mask = fields.Str(allow_none=True, validate=StringContains(r'[^aldsu\?0-9a-zA-Z]'))
mask_file = fields.List(fields.String(validate=[StringContains(r'[\W]\-'),
Length(min=1, max=60)]),
allow_none=True)
name = fields.Str(allow_none=True, validate=StringContains(r'[\W]'), error_messages=error_messages)
hash_mode = fields.Int(allow_none=False, validate=Range(min=0, max=65535))
restore = fields.Int(validate=Range(min=0, max=1000000000000))
user = fields.Str(allow_none=False, validate=StringContains(r'[\W]'))
password = fields.Str(allow_none=False, validate=StringContains(r'[^\w\!\@\#\$\%\^\&\*\(\)\-\+\.\,\\\/]'))
def get_jobdetails(job_details):
"""
Function to help pull only required information from a specified redis job
description string.
job_details: str
string returned from rq.job.description
Returns
------
deets_dict: dictionary
only the specified job details are returned
"""
deets_dict = {}
deet_match_list = [
'hash_mode',
'attack_mode',
'mask',
'wordlist',
'rules',
'name',
'username',
'increment',
'increment_min',
'increment_max',
'disable_brain',
'restore']
###***make this less ugly
###***review stripping here for improvement
#review rules processing
logger.debug('Parsing job details:\n{}'.format(job_details))
# Process rules list separately as workaround for splitting on comma
if '[' in job_details:
###***add mask_file here when updating to allow list of files
rules_split = job_details[job_details.rfind('[')+1:job_details.rfind(']')].strip()
rules_list = [rule.strip().rstrip("'").lstrip("'") for rule in rules_split.split(',')]
else:
rules_list = None
deets_split = job_details[job_details.rfind('(')+1:job_details.rfind(')')].split(',')
for deets in deets_split:
deet = deets.split('=')[0].strip(' ')
if deet in deet_match_list:
deets_dict[deet] = deets.strip().split('=')[1].strip().rstrip("'").lstrip("'")
if rules_list and rules_list != '':
rule_names = []
for key, rule in dict(CRACK_CONF['rules']).items():
if rule in rules_list:
rule_names.append(key)
deets_dict['rules'] = rule_names
else:
deets_dict['rules'] = None
if deets_dict['mask'] and deets_dict['mask'] != '':
mask = deets_dict['mask']
for key, mask_file in dict(CRACK_CONF['masks']).items():
if mask in mask_file:
deets_dict['mask'] = key
if deets_dict['wordlist'] != 'None' and deets_dict['wordlist'] != '':
wordlist = deets_dict['wordlist']
for key, word in dict(CRACK_CONF['wordlists']).items():
if wordlist in word:
deets_dict['wordlist'] = key
break
else:
deets_dict['wordlist'] = None
return deets_dict
def add_jobid(job_id):
"""Add job_id to job_ids column in user table"""
user = User.query.filter_by(username=current_user.username).first()
if user.job_ids:
logger.debug('Current registered job_ids: {}'.format(user.job_ids))
jobs = json.loads(user.job_ids)
else:
logger.debug('No job_ids registered with current user')
jobs = None
logger.info('Registering new job_id to current user: {}'.format(job_id))
if isinstance(jobs, list):
if job_id not in jobs:
jobs.append(job_id)
else:
logger.warning('job_id already registered to user: {}'.format(job_id))
else:
jobs = [job_id]
user.job_ids = json.dumps(jobs)
db.session.commit()
logger.debug('user.job_ids: {}'.format(user.job_ids))
def del_jobid(job_id):
"""Delete job_id from job_ids column in user table"""
user = User.query.filter_by(username=current_user.username).first()
if user.job_ids:
jobs = json.loads(user.job_ids)
logger.debug('Registered jobs: {}'.format(jobs))
else:
logger.debug('No job_ids registered with current user')
return False
if isinstance(jobs, list):
logger.info('Unregistering job_id: {}'.format(job_id))
if job_id in jobs:
jobs.remove(job_id)
else:
return False
else:
logger.error('Error removing job_id')
return False
user.job_ids = json.dumps(jobs)
db.session.commit()
logger.debug('user.job_ids: {}'.format((user.job_ids)))
return True
def check_jobid(job_id):
"""Check user owns the job_id"""
logger.debug('Checking job_id: {} belongs to user: {}'.format(
job_id, current_user.username))
user = User.query.filter_by(username=current_user.username).first()
if user.job_ids:
if job_id in user.job_ids:
return True
else:
return False
else:
return False
def check_rules(orig_rules):
"""
Check provided rules list is sane
Arguments
---------
orig_rules: list
List of rules to check
Returns
-------
rules: list
List of rules or False if any are invalid
"""
logger.debug('Checking rules valid')
try:
if orig_rules is None:
rules = None
elif isinstance(orig_rules, list):
rules = []
for rule in orig_rules:
if rule in CRACK_CONF['rules']:
logger.debug('Using rules file: {}'.format(CRACK_CONF['rules'][rule]))
rules.append(CRACK_CONF['rules'][rule])
return rules
else:
logger.debug('Invalid rules provided')
return False
except KeyError:
logger.debug('Invalid rules provided')
return False
def check_mask(orig_masks):
"""
Check provided mask file list is sane
Arguments
---------
orig_masks: list
List of mask files to check
Returns
-------
mask_files: list
List of mask files or False if any are invalid
"""
logger.debug('Checking mask files are valid')
try:
if orig_masks is None:
mask_file = None
elif isinstance(orig_masks, list):
mask_file = []
for mask in orig_masks:
if mask in CRACK_CONF['masks']:
#mask_name = CRACK_CONF['masks'][mask]
logger.debug('Using mask file: {}'.format(mask))
mask_file.append(CRACK_CONF['masks'][mask])
return mask_file if len(mask_file) > 0 else None
else:
logger.debug('Invalid mask file provided')
return False
except KeyError:
logger.debug('Invalid mask file provided')
return False
# this is just set to use the first mask file in the list for now
#mask = mask_file[0] if mask_file else mask
def create_user(username, email=None):
if User.query.filter_by(username=username).first():
logger.debug('User already exists')
return False
else:
user = User(username=username, email=email, is_admin=False)
db.session.add(user)
db.session.commit()
logger.debug('New user added')
return True
def email_check(email):
"""
Simple regex check string is an email address
Arguments
--------
email: str
email address string to check
Returns
-------
match: boolean
true/false for valid email match
"""
regex = r'^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'
if re.search(regex, email):
logger.debug('Email address found')
return True
else:
return False
@login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
class Sso(Resource):
"""
SAML2 Single Sign On Class
Login class handles saml sso authentication responses from IDP,
validates authenticity and authenticates if successful.
"""
def __init__(self):
if CRACK_CONF['auth']['type'] == 'saml2':
self.meta_url = CRACK_CONF['auth']['saml_manifest']
self.meta_file = CRACK_CONF['auth']['meta_file']
self.entity_id = CRACK_CONF['auth']['entity_id']
self.group = CRACK_CONF['auth']['group']
self.saml_auth = auth.Saml2(self.meta_url,
self.meta_file, self.entity_id)
self.saml_client = self.saml_auth.s_client()
#self.reqid = None
def get(self):
"""
Login mechanism, using GET to redirect to SAML IDP.
"""
###***validate
if CRACK_CONF['auth']['type'] == 'saml2':
self.reqid, info = self.saml_client.prepare_for_authenticate()
redirect_url = None
for key, value in info['headers']:
if key is 'Location':
redirect_url = value
response = redirect(redirect_url, code=302)
return response
else:
return 'Method not supported', 405
@csrf.exempt
def post(self):
"""
Handle returned SAML reponse
"""
if not CRACK_CONF['auth']['type'] == 'saml2':
return 'Method not supported', 405
###***validate
###***readd/fix reqid verification
saml_resp = request.form['SAMLResponse']
logger.debug('SAML SSO reponse received:\n {}'.format(saml_resp))
try:
saml_parse = self.saml_client.parse_authn_request_response(saml_resp,
BINDING_HTTP_POST)
except sigver.SignatureError as err:
return 'Invalid Signature', 500
except saml2.validate.ResponseLifetimeExceed as err:
return 'Invalid SAML Request', 500
#if saml_parse.in_response_to not in self.reqid:
# 'Unsolicited authentication response', 500
if saml_parse.authn_statement_ok():
user_info = saml_parse.ava.items()
groups = []
for key, val in user_info:
if 'name' in key:
username = val[0]
if 'email' in key:
email = val[0]
else:
email = None
if self.group and 'Group' in key:
groups = val
if self.group:
if len(groups) > 0:
if self.group not in groups:
logger.info('User authorised, but not in valid domain group')
return 'User is not authorised to use this service', 401
else:
logger.info('No groups returned in SAML response')
return 'User is not authorised to use this service', 401
try:
username
except UnboundLocalError:
return json.dumps({'msg': 'No user returned in SAML response'}), 500
logging.info('Authenticated: {}'.format(username))
user = load_user(username)
if user:
crackq.app.session_interface.regenerate(session)
else:
if email_check(email):
create_user(username, email=email)
else:
create_user(username)
user = load_user(username)
if isinstance(user, User):
crackq.app.session_interface.regenerate(session)
login_user(user)
else:
logging.error('No user object loaded')
return {"msg": "Bad username or password"}, 401
return redirect('/')
else:
###***add error output to debug
logger.info('Login error')
return {"msg": "Bad username or password"}, 401
class Login(Resource):
"""
Authentication handler
Login class handles authentication, it's protocol agnostic
and just needs the 'authenticate' fucntion to provide a
'Success' or 'Failure' result. The 'authenticate' function
can use any supported protocols or a custom protocol can be
created.
"""
def post(self):
"""
Login mechanism, using POST.
Supply the following in the body: {"user": "xxx", "password": "xxx"}
"""
marsh_schema = parse_json_schema().loads(json.dumps(request.json))
if len(marsh_schema.errors) > 0:
logger.debug('Validation error: {}'.format(marsh_schema.errors))
return marsh_schema.errors, 500
else:
args = marsh_schema.data
if CRACK_CONF['auth']['type'] == 'ldap':
username = args['user']
password = args['password']
if not username:
return json.dumps({"msg": "Missing username parameter"}), 400
if not password:
return json.dumps({"msg": "Missing password parameter"}), 400
ldap_uri = CRACK_CONF['auth']['ldap_server']
ldap_base = CRACK_CONF['auth']['ldap_base']
authn = auth.Ldap.authenticate(ldap_uri, username, password,
ldap_base=ldap_base)
logger.debug('LDAP reply: {}'.format(authn))
if authn[0] == "Success":
logging.info('Authenticated: {}'.format(username))
if email_check(username):
logger.debug('Email address found, using for notify')
email = username
user = load_user(username)
if user:
crackq.app.session_interface.regenerate(session)
login_user(user)
else:
if authn[1]:
email = authn[1]
if email_check(email):
create_user(username, email=email)
else:
create_user(username)
else:
create_user(username)
user = load_user(username)
if isinstance(user, User):
crackq.app.session_interface.regenerate(session)
login_user(user)
else:
logging.error('No user object loaded')
return json.dumps({"msg": "Bad username or password"}), 401
return 'OK', 200
elif authn[0] is "Invalid Credentials":
return json.dumps({"msg": "Bad username or password"}), 401
else:
logger.info('Login error: {}'.format(authn))
return json.dumps({"msg": "Bad username or password"}), 401
else:
return 'Method not supported', 405
class Logout(Resource):
"""
Session Logout
Class to logout and clear flask session cookie
"""
@login_required
def get(self):
logger.info('User logged out: {}'.format(current_user.username))
user = User.query.filter_by(username=current_user.username).first()
#sid = request.cookies.get(app.session_cookie_name)
sid = request.cookies.get(crackq.app.session_cookie_name)
crackq.app.session_interface.destroy(session)
user.active = False
db.session.commit()
logout_user()
return 'Logged Out', 200
class Queuing(Resource):
"""
Class to interact with the crackqueue module
This will instantiate a crackqueue instance and use
it to manage jobs in the Redis queue using RQ
"""
def __init__(self):
self.crack_q = crackqueue.Queuer()
self.q = self.crack_q.q_connect()
self.crack = run_hashcat.Crack()
rconf = CRACK_CONF['redis']
self.log_dir = CRACK_CONF['files']['log_dir']
#self.redis_con = Redis()
self.redis_con = Redis(rconf['host'], rconf['port'])
# password=rconf['password'])
self.req_max = CRACK_CONF['misc']['req_max']
#self.report_dir = CRACK_CONF['reports']['dir']
def zombie_check(self, started, failed, cur_list):
"""
This method will check and remove zombie jobs from
the started queue.
RQ has a bug which causes multiple started jobs to exist
after a system error has occured (unplanned exeception of some sort).
This method will clean this up and requeus the affected job.
"""
logger.debug('Checking for zombie jobs')
while len(started.get_job_ids()) > 1:
logger.debug('Zombie job detected')
logger.debug('Started jobs: {}'.format(cur_list))
hung_dict = {}
for j in cur_list:
job = self.q.fetch_job(j)
if job is not None:
hung_dict[j] = job.started_at
latest = max(hung_dict, key=hung_dict.get)
for j in cur_list:
if j != latest:
job = self.q.fetch_job(j)
if job:
job.set_status('failed')
failed.add(job)
logger.debug('Cleaning state job: {}'.format(j))
started.remove(job)
try:
if job.meta['Requeue Count'] <= int(self.req_max):
failed.requeue(j)
job.meta['Requeue Count'] += 1
job.save_meta()
except KeyError:
job.meta['Requeue Count'] = 0
def get_comp_dict(self, comp_list, session=False):
"""
Function to get comlete queue information
Arguments
---------
comp_list: list
list of job IDs in complete queue
session: string
session ID to reduce returned dictionary to jobs owned by user.
Returns
-------
comp_dict: dictionary
dict containing high-level info for jobs in complete queue
"""
comp_dict = {}
for job_id in comp_list:
if session:
if check_jobid(job_id):
job = self.q.fetch_job(job_id)
else:
job = None
else:
job = self.q.fetch_job(job_id)
if job:
comp_dict[job_id] = {}
job_deets = get_jobdetails(job.description)
if job.meta and 'HC State' in job.meta.keys():
if isinstance(job.meta['HC State'], dict):
cracked = str(job.meta['HC State']['Cracked Hashes'])
total = str(job.meta['HC State']['Total Hashes'])
comp_dict[job_id]['Cracked'] = '{}/{}'.format(cracked, total)
comp_dict[job_id]['Running Time'] = job.meta['HC State']['Running Time']
try:
comp_dict[job_id]['Name'] = get_jobdetails(job.description)['name']
except KeyError:
comp_dict[job_id]['Name'] = 'No name'
except AttributeError:
comp_dict[job_id]['Name'] = 'No name'
else:
comp_dict[job_id]['Name'] = job_deets['name']
comp_dict[job_id]['Cracked'] = 'All'
###**update to redis job time?
comp_dict[job_id]['Running Time'] = '0'
else:
comp_dict[job_id]['Name'] = job_deets['name']
comp_dict[job_id]['Cracked'] = None
comp_dict[job_id]['Running Time'] = None
else:
logger.error('job.meta is missing for job: {}'.format(job_id))
return comp_dict
@login_required
def get(self, job_id):
"""
Method to get job status
job_id: str
hex reprisentation of uuid job ID
Returns
------
"""
time_now = datetime.now().strftime("%Y-%m-%d %H:%M")
time_now = datetime.strptime(time_now, '%Y-%m-%d %H:%M')
current_user.last_seen = time_now
db.session.commit()
###***clean this up, maybe remove crackqueue.py entirely?
###***re-add this for validation?
#args = marsh_schema.data
started = rq.registry.StartedJobRegistry('default',
connection=self.redis_con)
failed = rq.registry.FailedJobRegistry('default',
connection=self.redis_con)
#failed = get_failed_queue(connection=self.redis_con)
cur_list = started.get_job_ids()
###**update all connections to user get_current_connection()??
self.zombie_check(started, failed, cur_list)
q_dict = self.crack_q.q_monitor(self.q)
logger.debug('Current jobs: {}'.format(cur_list))
failed_dict = self.crack_q.check_failed()
comp_list = self.crack_q.check_complete()
last_comp = []
end_times = {}
if len(comp_list) > 0:
###***make this a function/method
for j in comp_list:
if check_jobid(j):
job = self.q.fetch_job(j)
if job:
ended = job.ended_at
if ended:
end_times[j] = ended
if len(end_times) > 0:
latest = max(end_times, key=end_times.get)
else:
latest = None
if latest:
job = self.q.fetch_job(latest)
else:
job = None
if job:
try:
job_name = get_jobdetails(job.description)['name']
except KeyError:
job_name = 'No name'
except AttributeError:
job_name = 'No name'
# just a single job for now
last_comp = [{'job_name': job_name,
'job_id': latest}]
else:
last_comp = [{'job_name': 'None'}]
q_dict['Last Complete'] = last_comp
logger.debug('Completed jobs: {}'.format(comp_list))
logger.debug('q_dict: {}'.format(q_dict))
###***check for race conditions here!!
###***apply validation here
if job_id == 'all':
###***definitely make these a function
if len(cur_list) > 0:
job = self.q.fetch_job(cur_list[0])
#if len(json.loads(current_user.job_ids)) > 0:
if current_user.job_ids:
if cur_list[0] in json.loads(current_user.job_ids):
job.meta['email_count'] = 0
job.save()
if job:
if 'HC State' in job.meta:
###***small issue here when job is added initially?
if isinstance(job.meta['HC State'], dict):
job_details = get_jobdetails(job.description)
try:
q_dict['Current Job'][cur_list[0]]['Job Details'] = job_details
except KeyError:
logger.error('No job to update - does not exist')
else:
logger.error('No Queue')
if len(q_dict) > 0:
for qjob_id in q_dict['Queued Jobs']:
job = self.q.fetch_job(qjob_id)
job_details = get_jobdetails(job.description)
q_dict['Queued Jobs'][qjob_id]['Job Details'] = job_details
return q_dict, 200
###***apply validation here
elif job_id == 'failed':
return failed_dict, 200
elif job_id == 'failedless':
failess_dict = {}
for job_id in failed_dict:
if check_jobid(job_id):
failess_dict[job_id] = failed_dict[job_id]
return failess_dict, 200
###***apply validation here
elif job_id == 'complete':
comp_dict = {}
comp_dict = self.get_comp_dict(comp_list, session=False)
return comp_dict, 200
elif job_id == 'completeless':
comp_dict = {}
comp_dict = self.get_comp_dict(comp_list, session=True)
return comp_dict, 200
else:
marsh_schema = parse_json_schema().load({'job_id': job_id})
if len(marsh_schema.errors) > 0:
logger.debug('Validation error: {}'.format(marsh_schema.errors))
return marsh_schema.errors, 500
else:
job_id = marsh_schema.data['job_id'].hex
check_job = check_jobid(job_id)
if job_id in q_dict['Queued Jobs']:
if not check_job:
###***modify this to give better response?
return 401
job = self.q.fetch_job(job_id)
if job is not None:
job_details = get_jobdetails(job.description)
q_dict['Queued Jobs'][job_id]['Job Details'] = job_details
###***add cracked passwords key/value here from file
###***add place in queue info
return q_dict['Queued Jobs'][job_id], 200
elif job_id in q_dict['Current Job']:
if not check_job:
###***modify this to give better response?
return 401
###***add results
###***REFACTOR TO REMOVE USE OF FILE
###***validate file path here?
###***fix this up, why can't we pull the id from q_dict?
job = self.q.fetch_job(job_id)
if job is not None:
job_details = get_jobdetails(job.description)
job_dict = {
'Status': job.get_status(),
'Time started': str(job.started_at),
'Time finished': str(job.ended_at),
'Job Details': job_details,
'Result': job.result,
'HC State': job.meta,
}
cracked_file = '{}{}.cracked'.format(self.log_dir, job_id)
try:
with open(cracked_file, 'r') as cracked_fh:
job_dict['Cracked'] = [crack.strip() for crack in cracked_fh]
except IOError as err:
logger.debug('Cracked file does not exist: {}'.format(err))
return job_dict, 200
else:
return 'Not Found', 404
###***dead code??
print('TEST***')
result_file = '{}.json'.format(cur_list[0])
with open(result_file, 'r') as status_json:
return (status_json.read(), q_dict['Current Job']), 200
elif job_id in comp_list:
if not check_job:
###***modify this to give better response?
return 401
###***VALIDATE??
job = self.q.fetch_job(job_id)
if job is not None:
job_details = get_jobdetails(job.description)
job_dict = {
'Status': job.get_status(),
'Time started': str(job.started_at),
'Time finished': str(job.ended_at),
'Job Details': job_details,
'Result': job.result,
'HC State': job.meta,
}
cracked_file = '{}{}.cracked'.format(self.log_dir, job_id)
try:
with open(cracked_file, 'r') as cracked_fh:
job_dict['Cracked'] = [crack.strip() for crack in cracked_fh]
except IOError as err:
logger.debug('Cracked file does not exist: {}'.format(err))
return job_dict, 200
elif job_id in failed_dict:
if not check_job:
###***modify this to give better response?
return 401
job = self.q.fetch_job(job_id)
if job is not None:
job_details = get_jobdetails(job.description)
job_dict = {
'Status': job.get_status(),
'Time started': str(job.started_at),
'Time finished': str(job.ended_at),
'Job Details': job_details,
'Result': job.result,
'HC State': job.meta,
}
#if job_dict:
return job_dict, 200
else:
return 'Not Found', 404
else:
return 'Not Found', 404
@login_required
def put(self, job_id):
"""
Method to reorder the queue
This will clear the queued jobs and re-add them in
the order specified with a JSON batch add
jobord_dict: dict
Dictionary containing batch job add details as:
{job_id: place}
job_id: str hex representation of uuid job ID
place: int indicating place in queue
Returns
------
"""
marsh_schema = parse_json_schema().load(request.json)
if len(marsh_schema.errors) > 0:
logger.debug('Validation error: {}'.format(marsh_schema.errors))
return marsh_schema.errors, 500
comp = rq.registry.FinishedJobRegistry('default',
connection=self.redis_con)
###***change this to match reports, validate job_id correctly
if job_id == "reorder":
logger.debug('Reorder queue command received')
logger.debug(marsh_schema.data['batch_job'])
try:
adder = Adder()
for job in marsh_schema.data['batch_job']:
job_id = job['job_id']
if adder.session_check(self.log_dir, job_id):
logger.debug('Valid session found')
started = rq.registry.StartedJobRegistry('default',
connection=self.redis_con)
cur_list = started.get_job_ids()
if job_id in cur_list:
logger.error('Job is already running')
return {'msg': 'Job is already running'}, 500
marsh_schema.data['batch_job'].sort(key=itemgetter('place'))
for job in self.q.jobs:
job.set_status('finished')
job.save()
comp.add(job, -1)
job.cleanup(-1)
for job in marsh_schema.data['batch_job']:
Queue.dequeue_any(self.q, None, connection=self.redis_con)
#adder.post(job_id=job['job_id'])
#adder.post(job_id=job['job_id'])
j = self.q.fetch_job(job['job_id'])
###***check this covers case when job is in requeued state
self.q.enqueue_job(j)
j.meta['CrackQ State'] = 'Run/Restored'
j.save_meta()
return {'msg': 'Queue order updated'}, 200
except Exception as err:
###***fix to specific exception types
logger.error('Reorder failed: {}'.format(err))
return {'msg': 'Reorder failed'}, 500
@login_required
def patch(self, job_id):
"""
Method to stop/remove a job from the active queue to complete
and cancel current hashcat job if it's already running
Arguments
---------
job_id: str
hex reprisentation of uuid job ID
Returns
------
HTTP 204
"""
marsh_schema = parse_json_schema().load({'job_id': job_id})
if len(marsh_schema.errors) > 0:
logger.debug('Validation error: {}'.format(marsh_schema.errors))
return marsh_schema.errors, 500
else:
job_id = marsh_schema.data['job_id'].hex
try:
logger.info('Stopping job: {:s}'.format(job_id))
job = self.q.fetch_job(job_id)
started = rq.registry.StartedJobRegistry('default',
connection=self.redis_con)
cur_list = started.get_job_ids()
comp = rq.registry.FinishedJobRegistry('default',
connection=self.redis_con)
if job_id in cur_list:
job.meta['CrackQ State'] = 'Stop'
job.save_meta()
return 'Stopping Job: Sending signal to Hashcat', 204
else:
job.set_status('finished')
job.save()
comp.add(job, -1)
job.cleanup(-1)
###***look into why lpop fails but dequeue_any works, but only against the chosen job
#Queue.lpop([job_id], None, connection=self.redis_con)
Queue.dequeue_any(self.q, None, connection=self.redis_con)
return 'Stopped Job', 200
except AttributeError as err:
logger.debug('Failed to stop job: {}'.format(err))
return 'Invalid Job ID', 404
@login_required
def delete(self, job_id):
"""
Method to remove a job from the queue completely
and cancel current hashcat job if it's already running.
This will remove all trace of the job
Arguments
---------
job_id: str
hex reprisentation of uuid job ID
Returns
------
HTTP 204
"""
marsh_schema = parse_json_schema().load({'job_id': job_id})
if len(marsh_schema.errors) > 0:
logger.debug('Validation error: {}'.format(marsh_schema.errors))
return marsh_schema.errors, 500