-
Notifications
You must be signed in to change notification settings - Fork 8
/
ptp.py
executable file
·1084 lines (886 loc) · 32 KB
/
ptp.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
#!/usr/bin/env python3
# Risk & Vulnerability Assessment Reporting Engine
# Copyright 2022 The Risk & Vulnerability Reporting Engine Contributors, All Rights Reserved.
# (see Contributors.txt for a full list of Contributors)
# SPDX-License-Identifier: BSD-3-Clause
# Please see additional acknowledgments (including references to third party source code, object code, documentation and other files) in the license.txt file or contact [email protected] for full terms.
# Created, in part, with funding and support from the United States Government. (see Acknowledgments file).
# DM22-1011
import argparse
import datetime
import glob
import logging
import os, getpass, zipfile
import platform
import subprocess
import sys
import shutil
from pathlib import Path
from zipfile import ZipFile
import docker as d
from pentestportal import settings
def get_mode():
if os.path.exists("mode.txt"):
with open('mode.txt', 'r') as f:
mode = f.read()
return mode
else:
return None
def set_mode(mode):
with open('mode.txt', 'w') as f:
f.write(mode)
def get_web_container():
mode = get_mode()
return mode + '-web-1'
def logger(log_file='ptportal.log', initial=None, verbosity=logging.INFO):
logger = logging.getLogger("pipeline")
logger.setLevel(verbosity)
fh = logging.FileHandler(log_file)
ch = logging.StreamHandler()
logger.addHandler(fh)
logger.addHandler(ch)
logger.info("PT Portal")
return logger
def clear_migrations():
"""Remove any dangling migrations to avoid conflicts -- completely rebuild each run"""
migrations_path = Path('ptportal/migrations')
migrations_pycache_path = Path('ptportal/migrations/__pycache__')
shutil.rmtree(migrations_pycache_path, ignore_errors=True)
shutil.rmtree(migrations_path, ignore_errors=True)
Path('ptportal/migrations').mkdir(parents=True, exist_ok=True)
Path('ptportal/migrations/__init__.py').touch()
def compose_env(proxy=None):
"""Compose environment file"""
mode = get_mode()
if not os.path.exists(f'docker/{mode}/env.txt'):
docker_env_path = Path(f'docker/{mode}/env.txt')
docker_env_backup_path = Path(f'docker/{mode}/env-backup.txt')
docker_env_backup_path.touch()
shutil.copyfile(docker_env_path, docker_env_backup_path)
if proxy and proxy != 'False':
with open(proxy, 'r') as f:
proxy_info = f.read()
with open(docker_env_path, 'w') as f:
f.write('\n')
f.write(proxy_info)
def restore_env():
"""Restore environment variable file to original state"""
mode = get_mode()
docker_env_path = Path(f'docker/{mode}/env.txt')
docker_env_backup_path = Path(f'docker/{mode}/env-backup.txt')
if os.path.exists(docker_env_backup_path):
shutil.move(docker_env_backup_path, docker_env_path)
def build_ptportal(report_type, su=True, restore=False, migrations_file=None):
"""Run commands to prep pentestportal app and run django server"""
web_container = get_web_container()
if not migrations_file:
subprocess.run(
['docker', 'exec', web_container, 'python', 'manage.py', 'makemigrations']
)
subprocess.run(['docker', 'exec', web_container, 'python', 'manage.py', 'migrate'])
subprocess.run(
[
'docker',
'exec',
web_container,
'python',
'manage.py',
'set_report_type',
'--type',
report_type,
]
)
subprocess.run(['docker', 'exec', web_container, 'python', 'manage.py', 'dbLoader'])
subprocess.run(
[
'docker',
'exec',
web_container,
'python',
'manage.py',
'collectstatic',
'--no-input',
'--verbosity',
'0',
]
)
if su:
subprocess.run(
[
'docker',
'exec',
'-it',
web_container,
'python',
'manage.py',
'createsuperuser',
]
)
def build_offline(report_type, restore=False, migrations_file=None):
web_container = get_web_container()
if not migrations_file:
subprocess.run(
['docker', 'exec', web_container, 'python', 'manage.py', 'makemigrations']
)
subprocess.run(['docker', 'exec', web_container, 'python', 'manage.py', 'migrate'])
def check_if_ptportal_exists(log_handler=None):
old_project_exists, _, _ = check_if_project_exited()
if old_project_exists:
res = input(
'Are you sure you want to build a new ptportal instance? Existing ptportal app exists. All data will be lost. [y/n]'
)
if res == 'n' or res == 'no':
if log_handler:
log_handler.info('PT Portal Exists. Resuming...')
docker_compose_up(force_recreate=False, rm_orphans=False)
sys.exit()
def build_existing_images(
compose_file='docker-compose.prod.yml',
project_name='prod',
image_path='docker/images',
):
containers = ['web', 'db']
if project_name == 'prod':
containers += ['nginx']
for container in containers:
image_file = Path(f'{image_path}/{project_name}-{container}:latest.tar')
d.load_image(image_file)
subprocess.run(
[
'docker',
'compose' '-f',
compose_file,
'-p',
project_name,
'up',
'--no-recreate',
'-d',
]
)
def check_if_project_exited():
"""Checks to see if a project was built and if the containers are exited"""
possible_project_names = [
'prod',
'dev',
'test',
'pentestportal',
'pen-testing-portal',
]
possible_docker_compose_files = ['docker-compose.prod.yml', 'docker-compose.yml']
for project_name in possible_project_names:
for docker_compose_file in possible_docker_compose_files:
process = subprocess.run(
[
'docker',
'compose',
'-f',
docker_compose_file,
'-p',
project_name,
'ps',
],
stdout=subprocess.PIPE,
encoding='utf-8',
)
exited_web_containers = [
line for line in process.stdout.split('\n') if 'web' in line
]
if exited_web_containers:
print('project name: ', project_name)
print('docker compose file: ', docker_compose_file)
print('found exited containers: ', exited_web_containers)
return True, project_name, docker_compose_file
return False, None, None
def setup(args):
log_handler = logger()
log_handler.info('Installing dependencies...')
install_dependencies()
log_handler.info('Dependency installation complete.')
def dev(args, clear_docker=True):
dev_setup(report=args.report_type)
def dev_setup(report):
log_handler = logger()
log_handler.info('Loading PT Portal with docker-compose for developers')
check_if_ptportal_exists(log_handler)
mode = 'dev'
set_mode(mode)
clear_migrations()
#if args.proxy:
# log_handler.info('composing environment variable file for docker-compose')
# compose_env(args.proxy)
docker_compose_up(force_recreate=True, rm_orphans=True)
build_ptportal(report_type=report)
restore_env()
log_handler.info('App is ready at localhost:8080!')
def run(args):
prod_setup(report=args.report_type, connectivity='online')
def prod_setup(report, connectivity):
log_handler = logger()
log_handler.info('Loading PT Portal with docker-compose')
check_if_ptportal_exists(log_handler)
has_secret_key = False
new_line = False
with open('docker/prod/env.txt', 'r') as f:
lines = f.readlines()
if "\n" in lines[-1]:
new_line = True
for line in lines:
if line.find("SECRET_KEY=") != -1:
has_secret_key = True
break
if not has_secret_key:
f=open('docker/prod/env.txt', 'a')
if not new_line:
f.write("\n")
f.write("SECRET_KEY=\'")
f.close()
secret_key_cmd = "python3 -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key(), end=\"\")' >> docker/prod/env.txt"
subprocess.run(secret_key_cmd, shell=True)
f=open('docker/prod/env.txt', 'a')
f.write("\'\n")
f.close()
if os.path.isfile("docker/prod/nginx/ssl/selfsigned.crt") and os.path.isfile("docker/prod/nginx/ssl/selfsigned.key"):
print("Using existing SSL files in docker/prod/nginx/ssl")
else:
if os.path.exists("docker/prod/nginx/ssl/"):
print("SSL directory exists. Generating SSL files...")
else:
print("SSL directory does not exist. Creating SSL directory and generating SSL files...")
make_ssl = "mkdir docker/prod/nginx/ssl"
subprocess.run(make_ssl, shell=True)
ssl_cmd = "openssl req -x509 -nodes -days 365 -subj \"/C=CA/ST=QC/O=Assessment Team/CN=reporting_engine\" -newkey rsa:2048 -keyout docker/prod/nginx/ssl/selfsigned.key -out docker/prod/nginx/ssl/selfsigned.crt"
subprocess.run(ssl_cmd, shell=True)
print("SSL files saved to: docker/prod/nginx/ssl")
mode = 'prod'
set_mode(mode)
clear_migrations()
#if args.proxy:
# compose_env(args.proxy)
if connectivity == 'offline':
docker_compose_down(rm_images=False, rm_volumes=True, rm_orphans=True)
docker_compose_up(force_recreate=False, rm_orphans=True)
build_offline(report_type=report)
else:
docker_compose_down(rm_images=True, rm_volumes=True, rm_orphans=True)
docker_compose_up(force_recreate=True, rm_orphans=True)
build_ptportal(report_type=report)
restore_env()
log_handler.info('App is ready at https://[IP_ADDRESS]:443')
def install_dependencies():
print("Installing Tailwind CSS...")
try:
tailwind_cmd = "npm install -D node/dependencies/tailwindcss-3 --legacy-peer-deps"
subprocess.run(tailwind_cmd, shell=True)
except Exception as e:
print("Error installing Tailwind CSS: " + e)
print("Installing Vue.js...")
try:
vue_cmd = "npm install -D node/dependencies/components-vue3 --legacy-peer-deps"
subprocess.run(vue_cmd, shell=True)
except Exception as e:
print("Error installing Vue.js: " + e)
def docker_compose_start():
"""Starts old containers"""
mode = get_mode()
docker_compose_file = (
'docker-compose.prod.yml' if mode == 'prod' else 'docker-compose.yml'
)
project_name = 'prod' if mode == 'prod' else 'dev'
try:
subprocess.run(
f'docker compose -f {docker_compose_file} -p {project_name} start',
shell=True,
)
except Exception as e:
print('exception handler: ', e)
subprocess.run(f'docker compose start', shell=True)
def docker_compose_down(rm_images=True, rm_volumes=True, rm_orphans=True):
"""Stops containers and removes containers, networks, volumes, and images created by up."""
mode = get_mode()
remove_images = '--rmi=local' if rm_images else ''
remove_volumes = '--volumes' if rm_volumes else ''
remove_orphans = '--remove-orphans' if rm_orphans else ''
docker_compose_file = (
'docker-compose.prod.yml' if mode == 'prod' else 'docker-compose.yml'
)
project_name = 'prod' if mode == 'prod' else 'dev'
try:
subprocess.run(
f'docker compose -f {docker_compose_file} -p {project_name} down {remove_images} {remove_volumes} {remove_orphans}',
shell=True,
)
except Exception as e:
print('exception handler: ', e)
subprocess.run(
f'docker compose -f {docker_compose_file} -p {project_name} down',
shell=True,
)
subprocess.run(f'docker compose -f {docker_compose_file} down', shell=True)
def docker_compose_up(force_recreate=True, rm_orphans=True):
"""Builds, (re)creates, starts, and attaches to containers for a service."""
mode = get_mode()
force_recreate = '--force-recreate' if force_recreate else ''
remove_orphans = '--remove-orphans' if rm_orphans else ''
docker_compose_file = (
'docker-compose.prod.yml' if mode == 'prod' else 'docker-compose.yml'
)
project_name = 'prod' if mode == 'prod' else 'dev'
try:
subprocess.run(
f'docker compose -f {docker_compose_file} -p {project_name} up -d {force_recreate} {remove_orphans}',
shell=True,
)
except Exception as e:
print('exception handler: ', e)
subprocess.run(
f'docker compose -f {docker_compose_file} -p {project_name} up -d',
shell=True,
)
subprocess.run(f'docker compose -f {docker_compose_file} up -d', shell=True)
def docker_compose_rebuild_service(service):
"""Starts rebuilds specific service"""
mode = get_mode()
docker_compose_file = (
'docker-compose.prod.yml' if mode == 'prod' else 'docker-compose.yml'
)
project_name = 'prod' if mode == 'prod' else 'dev'
try:
subprocess.run(
f'docker compose -f {docker_compose_file} -p {project_name} build {service}',
shell=True,
)
except Exception as e:
print('exception handler: ', e)
subprocess.run(f'docker compose start', shell=True)
def clear_docker_cache(args, verbose=True):
if verbose:
print('Stop Containers')
docker_compose_down()
def clear_media_content():
"""Removes subfolders from pentestportal/media/"""
media_folder = os.path.join('pentestportal', 'media')
try:
if os.path.exists(media_folder) and os.path.isdir(media_folder):
log_handler = logger()
log_handler.info(f'Removing contents from {media_folder}')
for inode in os.listdir(media_folder):
currPath = os.path.join(media_folder, inode)
try:
if os.path.isdir(currPath): # if inode is dir, remove
shutil.rmtree(currPath, ignore_errors=True)
except Exception as e:
print('exception handler: ', e)
except Exception as e:
print('exception handler: ', e)
def remove(args):
res = input(
'WARNING: If you did not back up your docker images, database, and media files to your system, you will lose your data by proceeding and will not be able to restore it. Are you sure you wish to proceed? [y/n]'
)
if res == 'y' or res == 'yes':
clear_docker_cache(args, verbose=True)
clear_media_content()
exit()
def save_containers(container_folder_path='docker/containers/'):
mode = get_mode()
container_folder_path = Path(container_folder_path)
mode = get_mode()
containers = {
mode + '-db-1': f'{container_folder_path}{mode}_db_container.tar',
mode + '-web-1': f'{container_folder_path}{mode}_web_container.tar',
}
if mode == 'prod':
containers['prod-nginx-1'] = f'{container_folder_path}prod_nginx_container.tar'
for container, name in enumerate(containers):
print(f'saving container {container} to file: {name}')
d.save_container(container, name)
def load_containers(container_folder_path='docker/containers/'):
mode = get_mode()
container_folder_path = Path(container_folder_path)
containers = [
f'{container_folder_path}{mode}_db_container.tar',
f'{container_folder_path}{mode}_web_container.tar',
]
if mode == 'prod':
containers += Path(f'{container_folder_path}prod_nginx_container.tar')
for container in containers:
print(f'loading container {container}')
d.load_container(container)
def backup_app_repo(backup_name='repo-backup'):
# Copy entire repo into folder
shutil.rmtree(backup_name, ignore_errors=True)
shutil.copytree('.', backup_name)
return backup_name
def backup_json(
container, backup_name='json-backup', json_file='datadump.json', in_docker=False
):
if in_docker:
subprocess.run(
[
'python',
'manage.py',
'dumpdata',
'--exclude=contenttypes',
'--exclude=auth.Permission',
'--indent=2',
'--format=json',
'--output=' + json_file,
]
)
_ = subprocess.run(
[
'python',
'manage.py',
'generate_DHS_JSON',
backup_name,
]
)
else:
subprocess.run(
[
'docker',
'exec',
'-it',
container,
'python',
'manage.py',
'dumpdata',
'--exclude=contenttypes',
'--exclude=auth.Permission',
'--indent=2',
'--format=json',
'--output=' + json_file,
]
)
_ = subprocess.run(
[
'docker',
'exec',
'-it',
container,
'python',
'manage.py',
'generate_DHS_JSON',
backup_name,
]
)
if not Path(backup_name).exists():
Path(backup_name).mkdir()
shutil.move(json_file, backup_name)
return backup_name
def backup_media(backup_name='media-backup'):
# using distutils copy_tree function because it
# copies a directory into an existing directory w/o problems
if os.path.exists(Path('pentestportal/media')):
shutil.copytree(Path('pentestportal/media'), backup_name)
else:
print('pentestportal/media directory does not exist or cannot be accessed due to permissions. Media may not restore properly without this directory. Continuing with remaining back up steps...')
return backup_name
def backup_migrations(backup_name='migrations-backup'):
# Only backup first migrations file since we only use the first
# migrations file
if os.path.exists(Path('ptportal/migrations/0001_initial.py')):
shutil.copy('ptportal/migrations/0001_initial.py', backup_name)
else:
print('ptportal/migrations/0001_initial.py file does not exist or cannot be accessed due to permissions. Migrations may not restore properly without this file. Continuing with remaining back up steps...')
return backup_name
def backup_mode(backup_name='mode-backup'):
if os.path.exists(Path('mode.txt')):
shutil.copy('mode.txt', backup_name)
else:
print('mode.txt file does not exist or cannot be accessed due to permissions. RE may not restore properly without this file. Continuing with remaining back up steps...')
return backup_name
def backup_env(backup_name='env-backup'):
mode = get_mode()
if os.path.exists(Path('docker/' + mode + '/env.txt')):
shutil.copy('docker/' + mode + '/env.txt', backup_name)
else:
print('docker/' + mode + '/env.txt file does not exist or cannot be accessed due to permissions. RE may not restore properly without this file. Continuing with remaining back up steps...')
return backup_name
def image_backup(args=None, in_docker=False):
mode = get_mode()
web_image = mode + '-web'
db_image = mode + '-db'
path = 'docker/' + mode + '/'
print('Backing up web image to: ' + path + 'web.tar')
subprocess.run(
[
'docker',
'save',
web_image,
'-o',
path + 'web.tar'
]
)
print('Backing up db image to: ' + path + 'db.tar')
subprocess.run(
[
'docker',
'save',
db_image,
'-o',
path + 'db.tar'
]
)
if mode == 'prod':
nginx_image = mode + '-nginx'
print('Backing up nginx image to: ' + path + 'nginx.tar')
subprocess.run(
[
'docker',
'save',
nginx_image,
'-o',
path + 'nginx.tar'
]
)
def partial_backup(args=None, in_docker=False, password=None):
"""This method only backs up the JSON data
and media images.
This data can then be ingested into a new
PT Portal instance.
The migration file is kept, so this is
comptabile with future releases that don't
rely on model changes"""
mode = get_mode()
container = mode + '-web-1'
backup_folder = 'backup_folder'
shutil.rmtree(backup_folder, ignore_errors=True)
backup_media(backup_folder)
backup_json(container, backup_folder, in_docker=in_docker)
backup_migrations(backup_folder)
backup_mode(backup_folder)
backup_env(backup_folder)
with open('backup_folder/app_info.txt', 'w+') as f:
f.write(settings.VERSION_NUMBER)
backup_file = (
'backup-' + datetime.datetime.now().strftime("%m-%d-%Y-%H-%M") + '.zip'
)
if in_docker:
# From the application interface.
# The password is the engagement password
subprocess.run(
[
'zip',
'--encrypt',
backup_file,
'-r',
backup_folder,
'--password=' + password,
]
)
else:
# From the command line interface
print('Please enter a password to encrypt the backup')
subprocess.run(
[
'docker',
'exec',
'-it',
container,
'zip',
'--encrypt',
backup_file,
'-r',
backup_folder,
]
)
shutil.rmtree(backup_folder)
return backup_file
def backup(args):
# image_backup(args)
partial_backup(args)
def partial_restore(args):
"""Takes a 'backup-XXX.zip'
backup zip that contains the datadump json, a
migrations file to rebuild the database schema,
and the media folder with all of the images"""
choice = input(
"Restoring will delete all the data currently in the portal. Make sure to backup existing data before running a restore. Are you sure you want to restore the portal from a backup? [y/n]: "
)
if choice != "y":
exit()
if args.connectivity == 'offline':
print("Restoring offline...")
docker_compose_down(rm_images=False, rm_volumes=True, rm_orphans=True)
else:
print("Restoring online...")
docker_compose_down(rm_images=True, rm_volumes=True, rm_orphans=True)
if os.path.exists(Path('backup_folder')):
shutil.rmtree(Path('backup_folder'))
try:
with zipfile.ZipFile(args.backup, 'r') as zip:
zip.extractall(pwd=bytes(getpass.getpass('Enter ZIP password: '), 'utf-8'))
zip.close()
except Exception as e:
print("Failed to open zip.")
print(e)
shutil.rmtree(Path('backup_folder'))
print("Restoring configuration files...")
if os.path.exists(Path('backup_folder/mode.txt').resolve()):
shutil.copy(Path('backup_folder/mode.txt'), Path('mode.txt'))
with open(Path('mode.txt')) as mf:
mode = mf.read()
else:
print("Unknown mode. Defaulting to prod.")
mode = 'prod'
web_container = mode + '-web-1'
if os.path.exists(Path('backup_folder/env.txt').resolve()):
shutil.copy('backup_folder/env.txt', 'docker/' + mode + '/')
if mode == 'dev':
compose_file = 'docker-compose.yml'
else:
compose_file = 'docker-compose.prod.yml'
print("Restoring media...")
if os.path.exists(Path('pentestportal/media/charts')):
shutil.rmtree(Path('pentestportal/media/charts'))
if os.path.exists(Path('pentestportal/media/screenshots')):
shutil.rmtree(Path('pentestportal/media/screenshots'))
if os.path.exists(Path('backup_folder/charts')):
shutil.copytree(
str(Path('backup_folder/charts')), str(Path('pentestportal/media/charts/'))
)
if os.path.exists(Path('backup_folder/screenshots')):
shutil.copytree(
str(Path('backup_folder/screenshots')),
str(Path('pentestportal/media/screenshots/')),
)
if mode == 'prod':
prod_setup(report=args.report_type, connectivity=args.connectivity)
else:
dev_setup(report=args.report_type)
print("Restoring database...")
subprocess.run(
[
'docker',
'exec',
web_container,
'python',
'manage.py',
'loaddata',
'backup_folder/datadump.json',
]
)
shutil.rmtree('backup_folder')
def restore(args):
partial_restore(args)
def create_super_user(args):
"""
Create Super User
"""
mode = get_mode()
subprocess.run(
[
'docker',
'exec',
'-it',
mode + '-web-1',
'python',
'manage.py',
'createsuperuser',
]
)
def change_password(args):
"""
Change password for existing user
"""
mode = get_mode()
subprocess.run(
[
'docker',
'exec',
'-it',
mode + '-web-1',
'python',
'manage.py',
'changepassword',
args.username
]
)
def reset_attempts(args):
"""
Reset attempts for login
"""
mode = get_mode()
subprocess.run(
[
'docker',
'exec',
'-it',
mode + '-web-1',
'python',
'manage.py',
'axes_reset'
]
)
def shell(args):
"""
Jump into container shell. Default to web
"""
mode = get_mode()
if args.container == 'db':
subprocess.run(['docker', 'exec', '-it', mode + '-db-1', 'sh'])
elif args.container == 'nginx':
subprocess.run(['docker', 'exec', '-it', mode + '-nginx-1', 'sh'])
else:
subprocess.run(['docker', 'exec', '-it', mode + '-web-1', 'sh'])
def show_logs(args):
mode = get_mode()
if args.container == 'db':
subprocess.run(['docker', 'logs', '-f', mode + '-db-1'])
elif args.container == 'nginx':
subprocess.run(['docker', 'logs', '-f', mode + '-nginx-1'])
else:
subprocess.run(['docker', 'logs', '-f', mode + '-web-1'])
def pause(args):
print("Pausing Reporting Engine...")
mode = get_mode()
docker_compose_file = 'docker-compose.prod.yml' if mode == 'prod' else 'docker-compose.yml'
project_name = 'prod' if mode == 'prod' else 'dev'
try:
subprocess.run(f'docker compose -f {docker_compose_file} -p {project_name} stop', shell=True)
except Exception as e:
print('exception handler: ', e)
subprocess.run(f'docker compose stop', shell=True)
def resume(args):
print('Resuming Reporting Engine...')
docker_compose_up(force_recreate=False, rm_orphans=False)
mode = get_mode()
if mode == 'prod':
print('App is ready at https://localhost')
else:
print('App is ready at http://localhost:8080')
def main():
description = "Reporting Engine"
parser = argparse.ArgumentParser(description=description)
subparsers = parser.add_subparsers(title='commands')
# install dependencies
setup_parser = subparsers.add_parser('setup', help='Install Dependencies')
setup_parser.set_defaults(func=setup)
# production version
run_parser = subparsers.add_parser(
'run', help='Build and Run PT Portal for Production'
)
run_parser.add_argument(
'-r',
'--report_type',
choices=['RVA', 'FAST', 'RPT', 'HVA'],
help='report type [RVA, FAST, RPT, HVA]. Default to RVA',
default='RVA',
required=False,
)
#run_parser.add_argument(
# '-p', '--proxy', help='File with proxy configuration' # Default for NO proxy!
#)
run_parser.add_argument(
'-v',
'--verbose',
action='count',
default=0,
help='Verbosity flag (repeat for increased verbosity)',
)
run_parser.set_defaults(func=run)
# dev version
dev_parser = subparsers.add_parser('dev', help='Build and Run for Developers')
dev_parser.add_argument(
'-r',
'--report_type',
choices=['RVA', 'FAST', 'RPT', 'HVA'],
help='report type [RVA, FAST, RPT, HVA]. Default to RVA',
default='RVA',
required=False,
)
#dev_parser.add_argument(
# '-p', '--proxy', default='proxy.txt', help='File with proxy configuration'
#)
dev_parser.add_argument(
'-v',
'--verbose',
action='count',
default=0,
help='Verbosity flag (repeat for increased verbosity)',
)
dev_parser.set_defaults(func=dev)
# tear it down
remove_parser = subparsers.add_parser('remove', help='Tear down an instance of Reporting Engine')
remove_parser.set_defaults(func=remove)
# backup the database and media directories
backup_parser = subparsers.add_parser('backup', help='Backup an instance of Reporting Engine')
backup_parser.set_defaults(func=backup)
# restore a backups
restore_parser = subparsers.add_parser(
'restore', help='Restore an instance of Reporting Engine'
)
restore_parser.add_argument(