-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluething.py
2177 lines (1823 loc) · 81.5 KB
/
bluething.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/python
import io
import os
import re
import subprocess
import time
import stat
from contextlib import redirect_stdout
from datetime import datetime
from getpass import getpass
from secrets import compare_digest
import shlex
from textwrap import indent
from colorama import Fore
from colorama import Style
from colorama import init as colorama_init
# Variable Declaration and Initialization
if not os.path.exists('logs'):
os.makedirs('logs')
username = "admin"
# noinspection HardcodedPassword
password = "admin"
count = 0
log_ufw = []
log_services = []
log_passwords = []
log_patching = []
current_date = ""
current_datetime = ""
def banner():
print(indent("""
| ____ _ _______ _ _ |
| | _ \| | |__ __| | (_) |
| | |_) | |_ _ ___ | | | |__ _ _ __ __ _ |
| | _ <| | | | |/ _ \ | | | '_ \| | '_ \ / _` | |
\ | |_) | | |_| | __/ | | | | | | | | | | (_| | /
| |____/|_|\__,_|\___| |_| |_| |_|_|_| |_|\__, | |
| __/| |
| |___/ |
Welcome to the CIS Compliance Suite for Ubuntu 20.04
Authors: CB010695, CB010736, CB010830, CB010837
Version: 2.2.3
""", ' '))
input("\nPress Enter to continue...")
def login():
global count
print(indent("""
\033[91m|======================== Login ========================|\033[0m
""", ' '))
user_log = input("Username: ")
user_pass = getpass("Password: ")
if user_log == username and compare_digest(user_pass, password):
return True
else:
print("That is the wrong username or password. Try Again")
exit()
def y_n_choice():
while True:
try:
user_input = input("Enter your choice (yes/no): ")
if user_input is None:
print("Error: Result is None.")
return
user_input = user_input.lower()
if user_input not in ['yes', 'y', 'no', 'n']:
raise ValueError("Invalid input, please enter 'yes' or 'no'.")
return user_input
except ValueError as ve:
print("Error:", ve)
except TypeError as ve:
print("Error:", ve)
except AttributeError as ve:
print("Error:", ve)
def prerequisites():
print("""Checking prerequisites...""")
if is_debian() & has_sudo_privileges():
print("Requirements met.")
else:
print("Application requires a debian system and sudo privileges .")
exit()
def is_debian():
try:
with open('/etc/os-release') as f:
if 'debian' in f.read().lower():
return True
else:
return False
except FileNotFoundError:
return False
def has_sudo_privileges():
return os.geteuid() == 0
def log_setup():
global current_date
global current_datetime
log_file_path = 'logs/script_log.log'
current_date = datetime.now().strftime("%Y-%m-%d")
current_datetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
header = f"{'-' * 70}\nCIS Compliance Suite Logging\n{'-' * 70}\n"
if not os.path.exists(log_file_path):
with open(log_file_path, "w") as log_file:
log_file.write(header)
log_file.write(f"{current_datetime} - ============ SCRIPT INITIATION ============\n")
else:
with open(log_file_path, "a") as log_file:
log_file.write(f"{current_datetime} - ============ SCRIPT Execution ============\n")
def log_changes(changes, control):
global log_ufw, log_services, log_passwords, log_patching
if control == "ufw":
log_ufw.append(changes)
elif control == "services":
log_services.append(changes)
elif control == "pam":
log_passwords.append(changes)
elif control == "patches":
log_patching.append(changes)
def log_category(control):
log_file_path = 'logs/script_log.log'
with open(log_file_path, "a") as log_file:
if control == "ufw":
log_file.write(f"-----------------------------------------------------------------------\n")
log_file.write(f" UFW CONFIGURATIONS \n")
log_file.write(f"-----------------------------------------------------------------------\n")
for line in log_ufw:
log_file.write(f"{line}")
elif control == "services":
log_file.write(f"-----------------------------------------------------------------------\n")
log_file.write(f" SERVICES CONFIGURATIONS \n")
log_file.write(f"-----------------------------------------------------------------------\n")
for line in log_services:
log_file.write(f"{line}")
elif control == "pam":
log_file.write(f"-----------------------------------------------------------------------\n")
log_file.write(f" PASSWORD CONFIGURATIONS \n")
log_file.write(f"-----------------------------------------------------------------------\n")
for line in log_passwords:
log_file.write(f"{line}")
elif control == "patches":
log_file.write(f"-----------------------------------------------------------------------\n")
log_file.write(f" PATCHING CONFIGURATIONS \n")
log_file.write(f"-----------------------------------------------------------------------\n")
for line in log_patching:
log_file.write(f"{line}")
def control_or_date_log():
try:
print("""
\033[91m|======================== Log Generation ========================|\033[0m
\033[3mFor the above configurations do you want a log by date or by control,
hit no to skip\033[0m
""")
choice = y_n_choice().lower()
if choice == 'y' or choice == 'yes' or choice == '':
choice = input("""
Enter your choice as an integer:
1: Log by date
2: Log by control
Please enter the index of your choice: """)
choice = int(choice)
flag = False
if choice == 1:
output_filepath = f"logs/{current_date}.log"
with open(output_filepath, 'w') as output_file:
output_file.writelines(f"{'-' * 70}\nUFW Compliance\n{'-' * 70}\n")
for lines in log_ufw:
output_file.writelines(f"{str(lines)}\n")
output_file.writelines(f"{'-' * 70}\nServices Compliance\n{'-' * 70}\n")
for lines in log_services:
output_file.writelines(f"{str(lines)}\n")
output_file.writelines(f"{'-' * 70}\nPassword Compliance\n{'-' * 70}\n")
for lines in log_passwords:
output_file.writelines(f"{str(lines)}\n")
output_file.writelines(f"{'-' * 70}\nPatching Compliance\n{'-' * 70}\n")
for lines in log_patching:
output_file.writelines(f"{str(lines)}\n")
flag = True
elif choice == 2:
flag = False
log_mapping = {
"UFW CONFIGURATIONS": log_ufw,
"SERVICES CONFIGURATIONS": log_services,
"PASSWORD CONFIGURATION": log_passwords,
"PATCHING CONFIGURATIONS": log_patching
}
for control, log_list in log_mapping.items():
output_filepath = f"logs/{control}.log"
with open(output_filepath, 'a') as output_file:
for lines in log_list:
output_file.writelines(f"{str(lines)}\n")
flag = True
else:
print("Invalid choice. Please enter either 1 or 2.")
if flag:
print("\033[3mLog generated successfully\033[0m")
input("\n \033[5mHit Enter to continue...\033[0m")
os.system('clear')
home_main()
else:
print("\033[3mLog not generated\033[0m")
input("\n\033[5m Press Enter to continue...\033[0m")
os.system('clear')
home_main()
elif choice == 'n' or choice == 'no':
print("No log generated")
input("\n \033[5mHit Enter to continue...\033[0m")
os.system('clear')
home_main()
return True # without this true the function will keep on doing configurations which is also a good thing.
else:
print("Invalid choice. Please enter either 'yes' or 'no'.")
except ValueError as ve:
print("Error:", ve)
except TypeError as ve:
print("Error:", ve)
except AttributeError as ve:
print("Error:", ve)
# ================================= Services =================================== Services ===========================
# Services =================================== Services ========== Services ===================================
# Services ====
colorama_init()
def ask(name):
while True:
choice = input(
f"The script will remove {Fore.RED} " + str(name) + f"{Style.RESET_ALL} . Do you want to remove it y/n ")
if choice.lower() == "y":
return True
elif choice.lower() == "n":
return False
else:
print("Please enter a valid input")
# ==================================== U F W =========================== U F W ============================ U F W
# ================================ U F W =========================== U F W ============================ U F W
# ======================================= U F W =========================== U F W ============================ U F
# W ================================ U F W =========================== U F W ============================ U F W
# ================================
def noufwbanner():
print(indent("""
CIS recommends installing ufw; proceed with the installation in the configure section.""", ' '))
return
def is_ufw_installed():
try:
return bool(os.system("command -v ufw >/dev/null 2>&1") == 0)
except FileNotFoundError:
noufwbanner()
def ensure_ufw_installed():
print(indent("""
|================= Installing Host Firewall ==================|
A firewall utility is required to configure the Linux kernel's netfilter framework via the
iptables or nftables back-end. The Linux kernel's netfilter framework host-based firewall
can protect against threats originating from within a corporate network, including malicious
mobile code and poorly configured software on a host.
Note: Only one firewall utility should be installed and configured. UFW is dependent on
the iptables package.
""", ' '))
if not is_ufw_installed():
var = input(
"This point onwards, the configurations require the installation of UFW. Do you want to install the Host "
"firewall? (yes/no):").lower()
var.lower()
if var == 'y' or var == 'yes' or var == '':
os.system("apt-get install ufw")
line = "\nUFW INSTALLATION: ok"
log_changes(line, "ufw")
print("\n", line)
elif var == 'n' or var == 'no':
line = "\nUFW INSTALLATION: no"
log_changes(line, "ufw")
print("\n", line)
input("\033[5mExiting UFW controls... enter to continue to next configuration.\033[0m")
return False
elif var is None:
print("Error: Result is None.")
return
else:
line = "\nUFW INSTALLATION:Pre-set"
log_changes(line, "ufw")
print("\n", line)
def is_iptables_persistent_installed():
return bool(os.system("dpkg -s iptables-persistent >/dev/null 2>&1") == 0)
def ensure_iptables_persistent_packages_removed():
print(indent("""
|============== Removing IP-Persistent Tables ================|
Running both `ufw` and the services included in the `iptables-persistent` package may lead
to conflicts.
""", ' '))
if is_iptables_persistent_installed():
var = input("Do you want to remove the iptables-persistent packages? (yes/no):").lower()
var.lower()
if var == 'y' or var == 'yes' or var == '':
os.system("apt purge iptables-persistent > /dev/null 2>&1")
line = "\nIP-PERSISTENT:removed"
log_changes(line, "ufw")
print(line)
elif var == 'n' or var == 'no':
line = "\nIP-PERSISTENT: not removed"
log_changes(line, "ufw")
print("\n", line)
elif var is None:
print("Error: Result is None.")
return
else:
line = "\nIP-PERSISTENT:Pre-set"
log_changes(line, "ufw")
print("\n", line)
def is_ufw_enabled():
try:
# Run the command to check UFW status
result = subprocess.run(['ufw', 'status'], capture_output=True, text=True, check=True)
# Check if the output contains 'Status: active'
return 'Status: active' in result.stdout
except FileNotFoundError:
noufwbanner()
return False
except subprocess.CalledProcessError as e:
# If an error occurs while running the command
print(f"Error: {e}")
return False
except ValueError as ve:
print("Error:", ve)
except TypeError as ve:
print("Error:", ve)
except AttributeError as ve:
print("Error:", ve)
def enable_firewall_sequence():
print(indent("""
|======================= Enabling UFW ========================|
When running `ufw enable` or starting `ufw` via its initscript, `ufw` will flush its chains.
This is required so `ufw` can maintain a consistent state, but it may drop existing
connections (e.g., SSH). `ufw` does support adding rules before enabling the firewall.
The rules will still be flushed, but the SSH port will be open after enabling the firewall.
Please note that once `ufw` is 'enabled', it will not flush the chains when
adding or removing rules (but will when modifying a rule or changing the default policy).
By default, `ufw` will prompt when enabling the firewall while running under SSH.
""", ' '))
if not is_ufw_enabled():
print(indent("""
\nUFW is not enabled, do you want to enable it, """, ' '))
var = y_n_choice()
var.lower()
if var == 'y' or var == 'yes' or var == '':
print(indent("""
\nufw will flush its chains.This is good in maintaining a consistent state, but it may drop existing
connections (eg ssh)""", ' '))
os.system("ufw allow proto tcp from any to any port 22 > /dev/null 2>&1")
# Run the following command to verify that the ufw daemon is enabled:
print(indent("""
\nverifying that the ufw daemon is enabled:""", ' '))
os.system("systemctl is-enabled ufw.service > /dev/null 2>&1")
# following command to verify that the ufw daemon is active:
print(indent("""
\nverifying that the ufw daemon is active:""", ' '))
os.system("systemctl is-active ufw > /dev/null 2>&1")
# Run the following command to verify ufw is active
print(indent("""
\nverifying ufw is active:""", ' '))
os.system("ufw status")
# following command to unmask the ufw daemon
print(indent("""
\nunmasking ufw daemon:""", ' '))
os.system("systemctl unmask ufw.service > /dev/null 2>&1")
# following command to enable and start the ufw daemon:
print(indent("""
\nenabling and starting the ufw daemon:""", ' '))
os.system("systemctl --now enable ufw.service > /dev/null 2>&1")
# following command to enable ufw:
print(indent("""
\nEnabling the firewall...""", ' '))
os.system("ufw enable > /dev/null 2>&1")
line = """\n
UFW-ENABLING: ok, below commands were executed:
ufw allow proto tcp from any to any port 22
systemctl is-enabled ufw.service
systemctl is-active ufw
systemctl unmask ufw.service
systemctl --now enable ufw.service
ufw enable """
log_changes(line, "ufw")
print("\n", line)
elif var == 'n' or var == 'no':
line = "\nUFW-ENABLING: no"
log_changes(line, "ufw")
print(indent("""
\nExiting UFW enabling mode... continuing to next configurations""", ' '))
elif var is None:
print("Error: Result is None.")
return
else:
line = "\nUFW-ENABLING: Pre-set"
log_changes(line, "ufw")
print(""
"\n", line)
def is_loopback_interface_configured():
try:
unconfigured_rules = []
# Concatenate rules and statuses into a 2D array
ufw_rules_and_status = [
["ufw allow in on lo", "Anywhere on lo"],
["ufw allow out on lo", "ALLOW OUT Anywhere on lo"],
["ufw deny in from 127.0.0.0/8", "DENY 127.0.0.0/8 "],
["ufw deny in from ::1", "DENY ::1"]
]
# Get UFW status
result = subprocess.run(['ufw', 'status'], capture_output=True, text=True, check=True)
# Check for unconfigured rules
for rule, status in ufw_rules_and_status:
if status not in result.stdout:
unconfigured_rules.append(rule)
# Print results
if not unconfigured_rules:
print("All loopback rules are configured.")
return True
else:
print("\033[91m\U000026D4The following Loopback rules are not configured:\U000026D4")
for unconfigured_rule in unconfigured_rules:
print("\033[33m", unconfigured_rule, "\033[0m")
return False
except FileNotFoundError:
noufwbanner()
except ValueError as ve:
print("Error:", ve)
except TypeError as ve:
print("Error:", ve)
except AttributeError as ve:
print("Error:", ve)
def ensure_loopback_configured():
try:
print(indent("""
|============ Configuring the Loopback Interface =============|
Loopback traffic is generated between processes on the machine and is typically critical to
the operation of the system. The loopback interface is the only place that loopback network
(127.0.0.0/8 for IPv4 and ::1/128 for IPv6) traffic should be seen. All other interfaces
should ignore traffic on this network as an anti-spoofing measure.
""", ' '))
if not is_loopback_interface_configured():
print("\nAll loopback interfaces are not configured, do you want to configure them, ")
var = y_n_choice()
var.lower()
if var == 'y' or var == 'yes' or var == '':
line = """\n
LOOPBACK-INTERFACE: ok, below commands were executed:
ufw allow in on lo
ufw allow out on lo
ufw deny in from 127.0.0.0/8
ufw deny in from ::1
"""
log_changes(line, "ufw")
print("\nEnabling configurations on lo interfaces...")
os.system("ufw allow in on lo")
os.system("ufw allow out on lo")
os.system("ufw deny in from 127.0.0.0/8")
os.system("ufw deny in from ::1")
elif var == 'n' or var == 'no':
line = "\nLOOPBACK-INTERFACE: no"
log_changes(line, "ufw")
print("\n", line)
elif var is None:
print("Error: Result is None.")
return
else:
line = "\nLOOPBACK-INTERFACE: Pre-set"
log_changes(line, "ufw")
print("\n", line)
except ValueError as ve:
print("Error:", ve)
except TypeError as ve:
print("Error:", ve)
except AttributeError as ve:
print("Error:", ve)
except FileNotFoundError:
noufwbanner()
def is_ufw_outbound_connections_configured():
try:
result = subprocess.run("ufw status", shell=True, capture_output=True, text=True)
if "Anywhere on all" in result.stdout:
print(indent("""
All outbound connections are configured.
""", ' '))
return True
else:
print("\033[91m\U000026D4The following outbound rule is not configured: ufw allow out on all\U000026D4")
return False
except FileNotFoundError:
noufwbanner()
except subprocess.CalledProcessError as e:
print("Error:", e)
return False
except Exception as e:
print("Error:", e)
return False
def ensure_ufw_outbound_connections():
print(indent("""
|========= Configuring UFW Outbound Connections ==========|
If rules are not in place for new outbound connections, all packets will be dropped by the
default policy, preventing network usage.Do you want to configure your ufw outbound connec
tions if this set of rules are not in place
for new outbound connections all packets will be dropped by the default policy preventing
network usage.
""", ' '))
if not is_ufw_outbound_connections_configured():
print("\nAll outbound connections are not configured, do you want to configure them, ")
var = y_n_choice()
var.lower()
if var == 'y' or var == 'yes' or var == '':
# var = input("\n PLease verify all the rules whether it matches all the site policies")
print("\n implementing a policy to allow all outbound connections on all interfaces:")
line = """\n
OUTBOUND-RULES: ok, below command was executed:
ufw allow out on all
"""
log_changes(line, "ufw")
os.system("ufw allow out on all")
print("\nConfiguration successful ...")
elif var == 'n' or var == 'no':
line = "\nOUTBOUND-RULES: no"
log_changes(line, "ufw")
print(line)
elif var is None:
print("Error: Result is None.")
return
else:
line = "\nOUTBOUND-RULES:Pre-set"
log_changes(line, "ufw")
print("\n", line)
def get_validate_allow_deny():
while True:
try:
allw_dny = input("Enter rule (allow or deny): ").lower()
if allw_dny not in ['allow', 'deny']:
raise ValueError("Invalid rule. Please enter either 'allow' or 'deny'.")
elif allw_dny is None:
print("Error: Result is None.")
return
return allw_dny
except ValueError as ve:
print("Error:", ve)
except TypeError as ve:
print("Error:", ve)
except AttributeError as ve:
print("Error:", ve)
def validate_octet(value):
return 0 <= int(value) <= 255
def validate_network_address(address_parts):
return all(validate_octet(part) for part in address_parts)
def construct_network_address():
while True:
try:
netadd = input("Enter network address (in the format xxx.xxx.xxx.xxx): ")
address_parts = netadd.split('.')
# Use a regular expression to check if the input matches the expected format
if not re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', netadd) or not validate_network_address(
address_parts):
raise ValueError(
"Invalid network address format or out-of-range values. Please use xxx.xxx.xxx.xxx format.")
elif netadd is None:
print("Error: Result is None.")
return
return netadd
except ValueError as ve:
print("Error:", ve)
except TypeError as ve:
print("Error:", ve)
except AttributeError as ve:
print("Error:", ve)
def get__validate_protocol():
while True:
try:
proto = input("Enter protocol (tcp or udp): ").lower()
if proto not in ['tcp', 'udp']:
raise ValueError("Invalid protocol. Please enter either 'tcp' or 'udp'.")
elif proto is None:
print("Error: Result is None.")
return
return proto
except ValueError as ve:
print("Error:", ve)
except TypeError as ve:
print("Error:", ve)
except AttributeError as ve:
print("Error:", ve)
def get_validate_address_mask():
while True:
try:
mask = int(input("Enter the whole number value of the subnet mask (16-32): ").lower())
if 16 <= mask <= 32:
return str(mask)
elif mask is None:
print("Error: Result is None.")
return
else:
raise ValueError("\nInvalid subnet mask. Please enter a value between 16 and 32.")
except ValueError as ve:
print("\nError:", ve)
def get_ports_as_a_list(script_path):
# Ensure the script_path is a string
script_path = str(script_path)
# Use subprocess.run() instead of os.system()
subprocess.run(['dos2unix', script_path])
result = subprocess.run(['bash', script_path], capture_output=True, text=True)
if result.returncode == 0:
# If the script ran successfully, print the output
# getting numbers from string
temp = re.findall(r'\d+', result.stdout)
ports_list = list(map(int, temp))
print("Open ports with no FW rule")
for i in range(0, len(ports_list)):
print(i, ':', ports_list[i])
return ports_list
else:
# If there was an error, print the error message
print("Error:")
print(result.stderr)
def input_port_number(script_path):
while True:
try:
ports_list = get_ports_as_a_list(script_path)
p_no = int(input("Enter the index number of the port to be configured:"))
# Check if the user pressed Cancel
if 0 <= p_no <= len(ports_list) - 1:
port_number = ports_list[p_no]
return str(port_number)
elif p_no is None:
print("Error: Result is None.")
return
else:
raise ValueError(f"\nInvalid Index Number. Please enter a value between 0 and {len(ports_list) - 1}")
except ValueError as ve:
print("Error:", ve)
except TypeError as ve:
print("Error:", ve)
except AttributeError as ve:
print("Error:", ve)
def ensure_rules_on_ports(script_path):
print(indent("""
|========= Configuring Firewall Rules for Ports ==========|
To reduce the attack surface of a system,
all services and ports should be blocked unless required.
Your configuration will follow this format:
\x1B[3m ufw allow from 192.168.1.0/24 to any proto tcp port 443 \x1B[0m
Do you want to continue configuring firewall rules for a port [Y/n]:
""", ' '))
var = y_n_choice()
if var == 'y' or var == 'yes' or var == '':
port_number = input_port_number(script_path)
allow = get_validate_allow_deny()
netad = construct_network_address()
mask = get_validate_address_mask()
proto = get__validate_protocol()
rule = f"ufw {shlex.quote(allow)} from {shlex.quote(netad)}/{shlex.quote(mask)} to any proto {shlex.quote(proto)} port {shlex.quote(str(port_number))}"
line = f"PORT-RULES: \n: {rule}"
log_changes(line, "ufw")
# Refactor to pass command and arguments as a list
subprocess.run(shlex.split(rule))
input("\nHit enter to continue [enter]: ")
ensure_rules_on_ports(script_path)
elif var == 'n' or var == 'no':
line = "PORT-RULES: no"
log_changes(line, "ufw")
print("Skipping firewall rule configuration on ports...")
elif var is None:
print("Error: Result is None.")
return
def is_default_deny_policy():
# check if to deny policies are Pre-set
return bool(os.system(
"ufw status verbose | grep 'Default: deny (incoming), deny (outgoing), deny (routed)' >/dev/null 2>&1") == 0)
def ensure_default_deny_policy():
try:
print(indent("""
|================= Default Port Deny Policy ==================|
Any port and protocol not explicitly allowed will be blocked.
Do you want to configure the default deny policy? [Y/n]:
""", ' '))
is_default_deny_policy()
var = y_n_choice()
var.lower()
if var == 'y' or var == 'yes' or var == '':
print("remediation process...")
print("\n allowing Git...")
os.system("ufw allow git")
print("\nallowing http in...")
os.system("ufw allow in http")
print("\nallowing http out...")
os.system("ufw allow out http")
print("\nallowing https in...")
os.system("ufw allow in https")
print("\nallowing https out...")
os.system("ufw allow out https")
print("\nallowing port 53 out...")
os.system("ufw allow out 53")
print("\nallowing ufw logging on...")
os.system("ufw logging on")
print("\ndenying incoming by default...")
os.system("ufw default deny incoming")
print("\ndenying outgoing by default...")
os.system("ufw default deny outgoing")
print("\ndenying default routing...")
os.system("ufw default deny routed")
line = """\n
DEFAULT-DENY-POLICY: ok, below commands were executed,
ufw allow git
ufw allow in http
ufw allow out http
ufw allow in https
ufw allow out https
ufw allow out 53
ufw logging on
ufw default deny incoming
ufw default deny outgoing
ufw default deny routed
"""
log_changes(line, "ufw")
elif var == 'n' or var == 'no':
line = "\n\U000026D4DEFAULT-DENY-POLICY: no\U000026D4"
log_changes(line, "ufw")
elif var is None:
print("Error: Result is None.")
return
except ValueError as ve:
print("Error:", ve)
except TypeError as ve:
print("Error:", ve)
except AttributeError as ve:
print("Error:", ve)
def ufw_scan():
try:
print(indent("""
|================ Scanning UFW on your system ================|""", ' '))
# Check if UFW is installed
time.sleep(1)
if is_ufw_installed():
print("UFW is installed.")
else:
print("\033[91m\U000026D4UFW is not installed.\U000026D4\033[0m")
time.sleep(1)
if is_iptables_persistent_installed():
print("\033[91m\U000026D4Iptables-persistent packages are not removed.\U000026D4\033[0m")
else:
print("Iptables-persistent packages are removed.")
time.sleep(1)
if is_ufw_enabled():
print("UFW is enabled.")
else:
print("\033[91m\U000026D4UFW is not enabled.\U000026D4\033[0m")
time.sleep(1)
if is_default_deny_policy():
print("Default deny policy is configured.")
else:
print("\033[91m\U000026D4Default deny policy is not configured.\U000026D4\033[0m")
time.sleep(1)
is_loopback_interface_configured()
time.sleep(1)
if is_default_deny_policy():
print("Default deny policy is configured.")
is_ufw_outbound_connections_configured()
except FileNotFoundError:
noufwbanner()
except ValueError as ve:
print("Error:", ve)
except TypeError as ve:
print("Error:", ve)
except AttributeError as ve:
print("Error:", ve)
def ufw_configure():
try:
print(indent("""
\033[91m|=================== Configuring UFW Firewall Compliance ===================|\033[0m""", ' '))
ensure_ufw_installed()
time.sleep(1)
ensure_iptables_persistent_packages_removed()
time.sleep(1)
enable_firewall_sequence()
time.sleep(1)
# ensure_rules_on_ports_banner()
script_path = 'ufwropnprts.sh'
ensure_rules_on_ports(script_path)
time.sleep(1)
ensure_default_deny_policy()
time.sleep(1)
ensure_loopback_configured()
time.sleep(1)
ensure_ufw_outbound_connections()
time.sleep(1)
# print(indent("""
# \033[91m|============= Firewall configurations Complete ==============|\033[0m""")
except FileNotFoundError:
noufwbanner()
except KeyboardInterrupt:
print("\n\nExited unexpectedly...")
# ======================= PAM ======================= PAM ============================ PAM =======================
# PAM ============================== PAM ======================= PAM ============================ PAM
# ======================= PAM =======================
def check_package_installed(package_name):
result = subprocess.run(['dpkg', '-s', package_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
package_installed = result.returncode == 0
if package_installed:
print(f"{package_name} is already installed.")
line = f"\n- {package_name} Package is already installed on this machine.\n"
log_changes(line, "pam")
else:
print(f"{package_name} is not installed.")
return package_installed
def install_package():
package_name = 'libpam-pwquality'
if not check_package_installed(package_name):
while True:
response = input("libpam-pwquality package needs to be installed. Would you like to proceed (Y/N)? ")
if response.lower() == 'y':
print("Installing libpam-pwquality Package now...")
subprocess.run(['sudo', 'apt', 'install', package_name], check=True)
print("Installation of libpam-pwquality is complete.")
line = "\n1- libpam-pwquality Package was installed Successfully on this machine.\n"
log_changes(line, "pam")
break
elif response.lower() == 'n':
print("libpam-pwquality Package was not installed.")
line = "\n1- libpam-pwquality Package was NOT installed on this machine.\n"
log_changes(line, "pam")
break
else:
print("Invalid Choice, Please try again")
def read_file(file_path):
try:
with open(file_path, 'r') as file:
return file.readlines()
except IOError:
return []
def write_file(file_path, lines):
try:
with open(file_path, 'w') as file:
file.writelines(lines)
except IOError as e:
print(f"Error writing to {file_path}: {e}")
exit(1)
def check_pwquality_config():
lines = read_file('/etc/security/pwquality.conf')
minlen_value = 0
minclass_value = 0
for line in lines:
if 'minlen' in line and not line.startswith('#'):
try:
minlen_value = int(line.split('=')[1].strip())
except ValueError:
pass
elif 'minclass' in line and not line.startswith('#'):
try:
minclass_value = int(line.split('=')[1].strip())
except ValueError:
pass
if minlen_value < 14 or minclass_value < 4:
print("=== Warning: the current minimum length and password complexity do NOT meet requirements ===")
return False
else:
print("The current password length and complexity meet requirements. No changes are needed.")
return True
def apply_pwquality_config():
need_to_change = not check_pwquality_config()
if need_to_change:
while True:
response = input("Would you like to apply the recommended changes (Y/N)? ")
if response.lower() == 'y':
apply_pwquality(14, 4)
print("Updated pwquality.conf with minimum length=14 and complexity=4.")
line = "\n2- The password length and complexity were updated to meet the requirements.\n"
log_changes(line, "pam")
break
elif response.lower() == 'n':
print("Password requirements were not changed. No changes were made.")
line = "\n2- The password length and complexity were NOT updated to meet the requirements.\n"
log_changes(line, "pam")