-
Notifications
You must be signed in to change notification settings - Fork 81
/
cis_audit.py
executable file
·2674 lines (2074 loc) · 139 KB
/
cis_audit.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
# Copyright (C) 2022 Andy Dustin <andy.dustin@gmail.com>
# This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
# https://creativecommons.org/licenses/by-nc-sa/4.0/
# This unofficial tool checks for your system against published CIS Hardening Benchmarks and offers an indication of your system's preparedness for compliance to the official standard.
# You can obtain a copy of the CIS Benchmarks from https://www.cisecurity.org/cis-benchmarks/
# Use of the CIS Benchmarks are subject to the Terms of Use for Non-Member CIS Products - https://www.cisecurity.org/terms-of-use-for-non-member-cis-products
__version__ = '0.20.0-alpha.3'
### Imports ###
import json # https://docs.python.org/3/library/json.html
import logging # https://docs.python.org/3/library/logging.html
import os # https://docs.python.org/3/library/os.html
import pdb # noqa https://docs.python.org/3/library/pdb.html
import re # https://docs.python.org/3/library/re.html
import stat # https://docs.python.org/3/library/stat.html
import subprocess # https://docs.python.org/3/library/subprocess.html
import sys # https://docs.python.org/3/library/sys.html
from argparse import (
ArgumentParser, # https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser
)
from argparse import (
RawTextHelpFormatter, # https://docs.python.org/3/library/argparse.html#argparse.RawTextHelpFormatter
)
from datetime import (
datetime, # https://docs.python.org/3/library/datetime.html#datetime.datetime
)
from grp import getgrgid # https://docs.python.org/3/library/grp.html#grp.getgrgid
from pwd import getpwuid # https://docs.python.org/3/library/pwd.html#pwd.getpwuid
from types import (
SimpleNamespace, # https://docs.python.org/3/library/types.html#types.SimpleNamespace
)
from typing import Generator
from tests.integration import (
shellexec, # https://docs.python.org/3/library/typing.html#typing.Generator
)
### Classes ###
class CISAudit:
def __init__(self, config=None):
if config:
self.config = config
else:
self.config = SimpleNamespace(includes=None, excludes=None, level=0, system_type='server', log_level='DEBUG')
logging.basicConfig(
format='%(asctime)s [%(levelname)s]: %(funcName)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
)
self.log = logging.getLogger(__name__)
self.log.setLevel(self.config.log_level)
def _get_homedirs(self) -> "Generator[str, int, str]":
cmd = R"awk -F: '($1!~/(halt|sync|shutdown|nfsnobody)/ && $7!~/^(\/usr)?\/sbin\/nologin(\/)?$/ && $7!~/(\/usr)?\/bin\/false(\/)?$/) { print $1,$3,$6 }' /etc/passwd"
r = self._shellexec(cmd)
for row in r.stdout:
if row != "":
user, uid, homedir = row.split(' ')
yield user, int(uid), homedir
def _get_utcnow(self) -> datetime:
return datetime.utcnow()
def _is_test_included(self, test_id, test_level) -> bool:
"""Check whether a test_id should be tested or not
Parameters
----------
test_id : string, required
test_id of be checked
test_level : int, required
Hardening level of the test_id, per the CIS Benchmarks
config : namespace, required
Script configuration from parse_args()
Returns
-------
bool
Returns a boolean indicating whether a test should be executed (True), or not (False)
"""
self.log.debug(f'Checking whether to run test {test_id}')
is_test_included = True
## Check if the level is one we're going to run
if self.config.level != 0:
if test_level != self.config.level:
self.log.debug(f'Excluding level {test_level} test {test_id}')
is_test_included = False
## Check if there were explicitly included tests:
if self.config.includes:
is_parent_test = False
is_child_test = False
## Check if include starts with test_id
for include in self.config.includes:
if include.startswith(test_id):
is_parent_test = True
break
## Check if test_id starts with include
for include in self.config.includes:
if test_id.startswith(include):
is_child_test = True
break
## Check if the test_id is in the included tests
if test_id in self.config.includes:
self.log.debug(f'Test {test_id} was explicitly included')
is_test_included = True
elif is_parent_test:
self.log.debug(f'Test {test_id} is the parent of an included test')
is_test_included = True
elif is_child_test:
self.log.debug(f'Test {test_id} is the child of an included test')
is_test_included = True
elif self.config.level == 0:
self.log.debug(f'Excluding test {test_id} (Not found in the include list)')
is_test_included = False
## If this test_id was included in the tests, check it wasn't then excluded
if self.config.excludes:
is_parent_excluded = False
for exclude in self.config.excludes:
if test_id.startswith(exclude):
is_parent_excluded = True
break
if test_id in self.config.excludes:
self.log.debug(f'Test {test_id} was explicitly excluded')
is_test_included = False
elif is_parent_excluded:
self.log.debug(f'Test {test_id} is the child of an excluded test')
is_test_included = False
if is_test_included:
self.log.debug(f'Including test {test_id}')
else:
self.log.debug(f'Not including test {test_id}')
return is_test_included
def _shellexec(self, command: str) -> "SimpleNamespace[str, str, int]":
"""Execute shell command on the system. Supports piped commands
Parameters
----------
command : string, required
Shell command to execute
Returns
-------
Namespace:
"""
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
output = result.stdout.decode('UTF-8').split('\n')
error = result.stderr.decode('UTF-8').split('\n')
returncode = result.returncode
if len(output) > 1:
output.pop(-1)
if len(error) > 1:
error.pop(-1)
data = SimpleNamespace(stdout=output, stderr=error, returncode=returncode)
self.log.debug(f"'{command}', {data}")
return data
def audit_access_to_su_command_is_restricted(self) -> int:
state = 0
cmd = R"grep -Pi '^\h*auth\h+(?:required|requisite)\h+pam_wheel\.so\h+(?:[^#\n\r]+\h+)?((?!\2)(use_uid\b|group=\H+\b))\h+(?:[^#\n\r]+\h+)?((?!\1)(use_uid\b|group=\H+\b))(\h+.*)?$' /etc/pam.d/su"
r = self._shellexec(cmd)
if r.stdout[0] == '':
state += 1
else:
for entry in r.stdout[0].split():
if entry.startswith('group='):
group = entry.split('=')[1]
break
cmd = f'grep {group} /etc/group'
r = self._shellexec(cmd)
regex = re.compile('^[a-z-]+:x:[0-9]+:$')
if not regex.match(r.stdout[0]):
state += 2
return state
def audit_at_is_restricted_to_authorized_users(self) -> int:
state = 0
if os.path.exists('/etc/at.deny'):
state += 1
if self.audit_file_permissions(file="/etc/at.allow", expected_user="root", expected_group="root", expected_mode="0600") != 0:
state += 2
return state
def audit_audit_config_is_immutable(self) -> int:
cmd = R'grep -h "^\s*[^#]" /etc/audit/rules.d/*.rules | tail -1'
r = self._shellexec(cmd)
if r.stdout[0] == '-e 2':
state = 0
else:
state = 1
return state
def audit_audit_log_size_is_configured(self) -> int:
cmd = R"grep -P '^max_log_file\s*=\s*[0-9]+' /etc/audit/auditd.conf"
r = self._shellexec(cmd)
if r.returncode == 0:
state = 0
else:
state = 1
return state
def audit_audit_logs_not_automatically_deleted(self) -> int:
cmd = R"grep '^max_log_file_action\s*=\s*keep_logs' /etc/audit/auditd.conf"
r = self._shellexec(cmd)
if r.returncode == 0:
state = 0
else:
state = 1
return state
def audit_auditing_for_processes_prior_to_start_is_enabled(self) -> int:
r"""
#!/bin/bash
efidir=$(find /boot/efi/EFI/* -type d -not -name 'BOOT')
gbdir=$(find /boot -maxdepth 1 -type d -name 'grub*')
if [ -f "$efidir"/grub.cfg ]; then
grep "^\s*linux" "$efidir"/grub.cfg | grep -Evq "audit=1\b" && echo "FAILED" || echo "PASSED"
elif [ -f "$gbdir"/grub.cfg ]; then
grep "^\s*linux" "$gbdir"/grub.cfg | grep -Evq "audit=1\b" && echo "FAILED" || echo "PASSED"
else
echo "FAILED"
fi
"""
state = 0
efidirfile = self._shellexec(R"find /boot/efi/EFI/ -type f -name 'grub.cfg' | grep -v BOOT").stdout[0]
grubdirfile = self._shellexec(R"find /boot -mindepth 1 -maxdepth 2 -type f -name 'grub.cfg'").stdout[0]
if efidirfile != '':
cmd = Rf'grep "^\s*linux" "{efidirfile}" | grep -Evq "audit=1\b" && echo "FAILED" || echo "PASSED"'
r = self._shellexec(cmd)
elif grubdirfile != '':
cmd = Rf'grep "^\s*linux" "{grubdirfile}" | grep -Evq "audit=1\b" && echo "FAILED" || echo "PASSED"'
r = self._shellexec(cmd)
else:
r = self._shellexec("echo FAILED")
if r.stdout[0] != 'PASSED':
state += 1
return state
def audit_auth_for_single_user_mode(self) -> int:
state = 0
success_strings = [
'ExecStart=-/bin/sh -c "/sbin/sulogin; /usr/bin/systemctl --fail --no-block default"',
'ExecStart=-/bin/sh -c "/sbin/sulogin; /usr/bin/systemctl --job-mode=fail --no-block default"',
'ExecStart=-/bin/sh -c "/usr/sbin/sulogin; /usr/bin/systemctl --fail --no-block default"',
'ExecStart=-/bin/sh -c "/usr/sbin/sulogin; /usr/bin/systemctl --job-mode=fail --no-block default"',
]
cmd = R"grep ExecStart= /usr/lib/systemd/system/rescue.service"
r = self._shellexec(cmd)
if r.stdout[0] not in success_strings:
state += 1
cmd = R"grep ExecStart= /usr/lib/systemd/system/rescue.service"
r = self._shellexec(cmd)
if r.stdout[0] not in success_strings:
state += 2
return state
def audit_bootloader_password_is_set(self) -> int:
state = 0
cmd = R'grep "^\s*GRUB2_PASSWORD" /boot/grub2/user.cfg'
r = self._shellexec(cmd)
if not r.stdout[0].startswith('GRUB2_PASSWORD='):
state += 1
return state
def audit_chrony_is_configured(self) -> int:
state = 0
cmd = R"systemctl is-enabled chronyd"
r = self._shellexec(cmd)
if r.stdout[0] != "enabled":
state += 1
cmd = R"systemctl is-active chronyd"
r = self._shellexec(cmd)
if r.stdout[0] != "active":
state += 2
cmd = R'grep -E "^(server|pool)" /etc/chrony.conf'
r = self._shellexec(cmd)
if r.stdout[0] == "":
state += 4
cmd = R"ps aux | grep chronyd | grep -Ev 'awk|grep' | awk '/chronyd/ {print $1}'"
r = self._shellexec(cmd)
if r.stdout[0] != "chrony":
state += 8
return state
def audit_core_dumps_restricted(self) -> int:
state = 0
cmd = R'grep -hE "^\s*\*\s+hard\s+core" /etc/security/limits.conf /etc/security/limits.d/*'
r = self._shellexec(cmd)
if not re.match(r'\s*\*\s+hard\s+core\s+0', r.stdout[0]):
state += 1
cmd = R"sysctl fs.suid_dumpable"
r = self._shellexec(cmd)
if r.stdout[0] != "fs.suid_dumpable = 0":
state += 2
cmd = R'grep -h "fs\.suid_dumpable" /etc/sysctl.conf /etc/sysctl.d/*'
r = self._shellexec(cmd)
if r.stdout[0] != "fs.suid_dumpable = 0":
state += 4
return state
def audit_cron_is_restricted_to_authorized_users(self) -> int:
state = 0
if os.path.exists('/etc/cron.deny'):
state += 1
if not os.path.exists('/etc/cron.allow'):
state += 2
else:
if self.audit_file_permissions(file="/etc/cron.allow", expected_user="root", expected_group="root", expected_mode="0600") != 0:
state += 4
return state
def audit_default_group_for_root(self) -> int:
cmd = 'grep "^root:" /etc/passwd | cut -f4 -d:'
r = self._shellexec(cmd)
if r.stdout[0] == '0':
state = 0
else:
state = 1
return state
def audit_duplicate_gids(self) -> int:
state = 0
cmd = R'cut -d: -f3 /etc/group | sort | uniq -d'
r = self._shellexec(cmd)
if r.stdout[0] != '':
state = 1
return state
def audit_duplicate_group_names(self) -> int:
state = 0
cmd = R'cut -d: -f1 /etc/group | sort | uniq -d'
r = self._shellexec(cmd)
if r.stdout[0] != '':
state = 1
return state
def audit_duplicate_uids(self) -> int:
state = 0
cmd = R'cut -d: -f3 /etc/passwd | sort | uniq -d'
r = self._shellexec(cmd)
if r.stdout[0] != '':
state = 1
return state
def audit_duplicate_user_names(self) -> int:
state = 0
cmd = R'cut -d: -f1 /etc/passwd | sort | uniq -d'
r = self._shellexec(cmd)
if r.stdout[0] != '':
state = 1
return state
def audit_etc_passwd_accounts_use_shadowed_passwords(self) -> int:
"""audit_etc_passwd_accounts_use_shadowed_passwords _summary_
Returns
-------
int
_description_
"""
"""
Refer to passwd(5) for details on the fields in the file
"""
state = 0
## Note: the 'awk' command from the benchmark would be the better/tidier way to do it, but I couldn't get the mixed quote marks to work from Python, so I ended up with the following:
## Original - awk -F: '($2 != "x" ) {print $1}' /etc/passwd
cmd = R"grep -Ev '^[a-z-]+:x:' /etc/passwd"
r = self._shellexec(cmd)
if r.stdout[0] != '':
state += 1
return state
def audit_etc_passwd_gids_exist_in_etc_group(self) -> int:
gids_from_etc_group = self._shellexec("awk -F: '{print $3}' /etc/group | sort -un").stdout
gids_from_etc_passwd = self._shellexec("awk -F: '{print $4}' /etc/passwd | sort -un").stdout
state = 0
for gid in gids_from_etc_passwd:
if gid not in gids_from_etc_group:
self.log.warning(f'GID {gid} exists in /etc/passwd but not in /etc/group')
state = 1
return state
def audit_etc_shadow_password_fields_are_not_empty(self) -> int:
state = 0
cmd = R"grep -E '^[a-z-]+::' /etc/shadow"
r = self._shellexec(cmd)
if r.stdout[0] != '':
state += 1
return state
def audit_events_for_changes_to_sysadmin_scope_are_collected(self) -> int:
state = 0
cmd1 = R"grep -h scope /etc/audit/rules.d/*.rules"
cmd2 = R"auditctl -l | grep scope"
expected_output = [
'-w /etc/sudoers -p wa -k scope',
'-w /etc/sudoers.d -p wa -k scope',
]
r1 = self._shellexec(cmd1)
r2 = self._shellexec(cmd2)
if r1.stdout != expected_output:
state += 1
if r2.stdout != expected_output:
state += 2
return state
def audit_events_for_discretionary_access_control_changes_are_collected(self) -> int:
state = 0
cmd1 = R"grep -h perm_mod /etc/audit/rules.d/*.rules"
cmd2 = R"auditctl -l | grep perm_mod"
expected_file_output = [
'-a always,exit -F arch=b64 -S chmod -S fchmod -S fchmodat -F auid>=1000 -F auid!=4294967295 -k perm_mod',
'-a always,exit -F arch=b32 -S chmod -S fchmod -S fchmodat -F auid>=1000 -F auid!=4294967295 -k perm_mod',
'-a always,exit -F arch=b64 -S chown -S fchown -S fchownat -S lchown -F auid>=1000 -F auid!=4294967295 -k perm_mod',
'-a always,exit -F arch=b32 -S chown -S fchown -S fchownat -S lchown -F auid>=1000 -F auid!=4294967295 -k perm_mod',
'-a always,exit -F arch=b64 -S setxattr -S lsetxattr -S fsetxattr -S removexattr -S lremovexattr -S fremovexattr -F auid>=1000 -F auid!=4294967295 -k perm_mod',
'-a always,exit -F arch=b32 -S setxattr -S lsetxattr -S fsetxattr -S removexattr -S lremovexattr -S fremovexattr -F auid>=1000 -F auid!=4294967295 -k perm_mod',
]
expected_auditctl_output = [
'-a always,exit -F arch=b64 -S chmod,fchmod,fchmodat -F auid>=1000 -F auid!=-1 -F key=perm_mod',
'-a always,exit -F arch=b32 -S chmod,fchmod,fchmodat -F auid>=1000 -F auid!=-1 -F key=perm_mod',
'-a always,exit -F arch=b64 -S chown,fchown,lchown,fchownat -F auid>=1000 -F auid!=-1 -F key=perm_mod',
'-a always,exit -F arch=b32 -S lchown,fchown,chown,fchownat -F auid>=1000 -F auid!=-1 -F key=perm_mod',
'-a always,exit -F arch=b64 -S setxattr,lsetxattr,fsetxattr,removexattr,lremovexattr,fremovexattr -F auid>=1000 -F auid!=-1 -F key=perm_mod',
'-a always,exit -F arch=b32 -S setxattr,lsetxattr,fsetxattr,removexattr,lremovexattr,fremovexattr -F auid>=1000 -F auid!=-1 -F key=perm_mod',
]
r1 = self._shellexec(cmd1)
r2 = self._shellexec(cmd2)
if r1.stdout != expected_file_output:
state += 1
if r2.stdout != expected_auditctl_output:
state += 2
return state
def audit_events_for_file_deletion_by_users_are_collected(self) -> int:
state = 0
cmd1 = R"grep -h delete /etc/audit/rules.d/*.rules"
cmd2 = R"auditctl -l | grep delete"
expected_file_output = [
'-a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295 -k delete',
'-a always,exit -F arch=b32 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295 -k delete',
]
expected_auditctl_output = [
'-a always,exit -F arch=b64 -S rename,unlink,unlinkat,renameat -F auid>=1000 -F auid!=-1 -F key=delete',
'-a always,exit -F arch=b32 -S unlink,rename,unlinkat,renameat -F auid>=1000 -F auid!=-1 -F key=delete',
]
r1 = self._shellexec(cmd1)
r2 = self._shellexec(cmd2)
if r1.stdout != expected_file_output:
state += 1
if r2.stdout != expected_auditctl_output:
state += 2
return state
def audit_events_for_kernel_module_loading_and_unloading_are_collected(self) -> int:
state = 0
cmd1 = R"grep -h modules /etc/audit/rules.d/*.rules"
cmd2 = R"auditctl -l | grep modules"
expected_file_output = [
'-w /sbin/insmod -p x -k modules',
'-w /sbin/rmmod -p x -k modules',
'-w /sbin/modprobe -p x -k modules',
'-a always,exit -F arch=b64 -S init_module -S delete_module -k modules',
]
expected_auditctl_output = [
'-w /sbin/insmod -p x -k modules',
'-w /sbin/rmmod -p x -k modules',
'-w /sbin/modprobe -p x -k modules',
'-a always,exit -F arch=b64 -S init_module,delete_module -F key=modules',
]
r1 = self._shellexec(cmd1)
r2 = self._shellexec(cmd2)
if r1.stdout != expected_file_output:
state += 1
if r2.stdout != expected_auditctl_output:
state += 2
return state
def audit_events_for_login_and_logout_are_collected(self) -> int:
state = 0
cmd1 = R"grep -h logins /etc/audit/rules.d/*.rules"
cmd2 = R"auditctl -l | grep logins"
expected_output = [
'-w /var/log/lastlog -p wa -k logins',
'-w /var/run/faillock -p wa -k logins',
]
r1 = self._shellexec(cmd1)
r2 = self._shellexec(cmd2)
if r1.stdout != expected_output:
state += 1
if r2.stdout != expected_output:
state += 2
return state
def audit_events_for_session_initiation_are_collected(self) -> int:
state = 0
cmd1 = R"grep -h '[buw]tmp' /etc/audit/rules.d/*.rules"
cmd2 = R"auditctl -l | grep '[buw]tmp'"
expected_output = [
'-w /var/run/utmp -p wa -k session',
'-w /var/log/wtmp -p wa -k logins',
'-w /var/log/btmp -p wa -k logins',
]
r1 = self._shellexec(cmd1)
r2 = self._shellexec(cmd2)
if r1.stdout != expected_output:
state += 1
if r2.stdout != expected_output:
state += 2
return state
def audit_events_for_successful_file_system_mounts_are_collected(self) -> int:
state = 0
cmd1 = R"grep -h mounts /etc/audit/rules.d/*.rules"
cmd2 = R"auditctl -l | grep mounts"
expected_file_output = [
'-a always,exit -F arch=b64 -S mount -F auid>=1000 -F auid!=4294967295 -k mounts',
'-a always,exit -F arch=b32 -S mount -F auid>=1000 -F auid!=4294967295 -k mounts',
]
expected_auditctl_output = [
'-a always,exit -F arch=b64 -S mount -F auid>=1000 -F auid!=-1 -F key=mounts',
'-a always,exit -F arch=b32 -S mount -F auid>=1000 -F auid!=-1 -F key=mounts',
]
r1 = self._shellexec(cmd1)
r2 = self._shellexec(cmd2)
if r1.stdout != expected_file_output:
state += 1
if r2.stdout != expected_auditctl_output:
state += 2
return state
def audit_events_for_system_administrator_commands_are_collected(self) -> int:
state = 0
cmd1 = R"grep -h actions /etc/audit/rules.d/*.rules"
cmd2 = R"auditctl -l | grep actions"
expected_file_output = [
'-a exit,always -F arch=b64 -C euid!=uid -F euid=0 -F auid>=1000 -F auid!=4294967295 -S execve -k actions',
'-a exit,always -F arch=b32 -C euid!=uid -F euid=0 -F auid>=1000 -F auid!=4294967295 -S execve -k actions',
]
expected_auditctl_output = [
'-a always,exit -F arch=b64 -S execve -C uid!=euid -F euid=0 -F auid>=1000 -F auid!=-1 -F key=actions',
'-a always,exit -F arch=b32 -S execve -C uid!=euid -F euid=0 -F auid>=1000 -F auid!=-1 -F key=actions',
]
r1 = self._shellexec(cmd1)
r2 = self._shellexec(cmd2)
if r1.stdout != expected_file_output:
state += 1
if r2.stdout != expected_auditctl_output:
state += 2
return state
def audit_events_for_unsuccessful_file_access_attempts_are_collected(self) -> int:
state = 0
cmd1 = R"grep -h access /etc/audit/rules.d/*.rules"
cmd2 = R"auditctl -l | grep access"
expected_file_output = [
'-a always,exit -F arch=b64 -S creat -S open -S openat -S truncate -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -k access',
'-a always,exit -F arch=b32 -S creat -S open -S openat -S truncate -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -k access',
'-a always,exit -F arch=b64 -S creat -S open -S openat -S truncate -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -k access',
'-a always,exit -F arch=b32 -S creat -S open -S openat -S truncate -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -k access',
]
expected_auditctl_output = [
'-a always,exit -F arch=b64 -S open,truncate,ftruncate,creat,openat -F exit=-EACCES -F auid>=1000 -F auid!=-1 -F key=access',
'-a always,exit -F arch=b32 -S open,creat,truncate,ftruncate,openat -F exit=-EACCES -F auid>=1000 -F auid!=-1 -F key=access',
'-a always,exit -F arch=b64 -S open,truncate,ftruncate,creat,openat -F exit=-EPERM -F auid>=1000 -F auid!=-1 -F key=access',
'-a always,exit -F arch=b32 -S open,creat,truncate,ftruncate,openat -F exit=-EPERM -F auid>=1000 -F auid!=-1 -F key=access',
]
r1 = self._shellexec(cmd1)
r2 = self._shellexec(cmd2)
if r1.stdout != expected_file_output:
state += 1
if r2.stdout != expected_auditctl_output:
state += 2
return state
def audit_events_that_modify_datetime_are_collected(self) -> int:
state = 0
cmd1 = R"grep -h time-change /etc/audit/rules.d/*.rules"
cmd2 = R"auditctl -l | grep time-change"
expected_file_output = [
'-a always,exit -F arch=b64 -S adjtimex -S settimeofday -k time-change',
'-a always,exit -F arch=b32 -S adjtimex -S settimeofday -S stime -k time-change',
'-a always,exit -F arch=b64 -S clock_settime -k time-change',
'-a always,exit -F arch=b32 -S clock_settime -k time-change',
'-w /etc/localtime -p wa -k time-change',
]
expected_auditctl_output = [
'-a always,exit -F arch=b64 -S adjtimex,settimeofday -F key=time-change',
'-a always,exit -F arch=b32 -S stime,settimeofday,adjtimex -F key=time-change',
'-a always,exit -F arch=b64 -S clock_settime -F key=time-change',
'-a always,exit -F arch=b32 -S clock_settime -F key=time-change',
'-w /etc/localtime -p wa -k time-change',
]
r1 = self._shellexec(cmd1)
r2 = self._shellexec(cmd2)
if r1.stdout != expected_file_output:
state += 1
if r2.stdout != expected_auditctl_output:
state += 2
return state
def audit_events_that_modify_mandatory_access_controls_are_collected(self) -> int:
state = 0
cmd1 = R"grep -h MAC-policy /etc/audit/rules.d/*.rules"
cmd2 = R"auditctl -l | grep MAC-policy"
expected_output = [
'-w /etc/selinux -p wa -k MAC-policy',
'-w /usr/share/selinux -p wa -k MAC-policy',
]
r1 = self._shellexec(cmd1)
r2 = self._shellexec(cmd2)
if r1.stdout != expected_output:
state += 1
if r2.stdout != expected_output:
state += 2
return state
def audit_events_that_modify_network_environment_are_collected(self) -> int:
state = 0
cmd1 = R"grep -h system-locale /etc/audit/rules.d/*.rules"
cmd2 = R"auditctl -l | grep system-locale"
expected_file_output = [
'-a always,exit -F arch=b64 -S sethostname -S setdomainname -k system-locale',
'-a always,exit -F arch=b32 -S sethostname -S setdomainname -k system-locale',
'-w /etc/issue -p wa -k system-locale',
'-w /etc/issue.net -p wa -k system-locale',
'-w /etc/hosts -p wa -k system-locale',
'-w /etc/sysconfig/network -p wa -k system-locale',
]
expected_auditctl_output = [
'-a always,exit -F arch=b64 -S sethostname,setdomainname -F key=system-locale',
'-a always,exit -F arch=b32 -S sethostname,setdomainname -F key=system-locale',
'-w /etc/issue -p wa -k system-locale',
'-w /etc/issue.net -p wa -k system-locale',
'-w /etc/hosts -p wa -k system-locale',
'-w /etc/sysconfig/network -p wa -k system-locale',
]
r1 = self._shellexec(cmd1)
r2 = self._shellexec(cmd2)
if r1.stdout != expected_file_output:
state += 1
if r2.stdout != expected_auditctl_output:
state += 2
return state
def audit_events_that_modify_usergroup_info_are_collected(self) -> int:
state = 0
cmd1 = R"grep -h identity /etc/audit/rules.d/*.rules"
cmd2 = R"auditctl -l | grep identity"
expected_file_output = [
'-w /etc/group -p wa -k identity',
'-w /etc/passwd -p wa -k identity',
'-w /etc/gshadow -p wa -k identity',
'-w /etc/shadow -p wa -k identity',
'-w /etc/security/opasswd -p wa -k identity',
]
expected_auditctl_output = [
'-w /etc/group -p wa -k identity',
'-w /etc/passwd -p wa -k identity',
'-w /etc/gshadow -p wa -k identity',
'-w /etc/shadow -p wa -k identity',
'-w /etc/security/opasswd -p wa -k identity',
]
r1 = self._shellexec(cmd1)
r2 = self._shellexec(cmd2)
if r1.stdout != expected_file_output:
state += 1
if r2.stdout != expected_auditctl_output:
state += 2
return state
def audit_file_permissions(self, file: str, expected_mode: str, expected_user: str = None, expected_group: str = None) -> int:
"""Check that a file's ownership matches the expected_user and expected_group, and that the file's permissions match or are more restrictive than the expected_mode.
Parameters
----------
test_id: str, required
The ID of the recommendation to be tested, per the CIS Benchmarks
file: str, required
The file to be tested
expected_user: str, required
The expected user for the file
expected_group: str, required
The expected group membership for the file
expected_mode: str, required
The octal file mode that the file should not exceed. e.g. 2750, 664, 0400.
Response
--------
int:
Exit state for tests as a sum of individual failures:
-1 >= Error
0 == Pass
1 <= Fail
"""
"""
When looping over each of the permission bits. If the bits do not match or are not more restrictive, increment the failure state value by a unique amount, per below. This allows us to determine from the return value, which permissions did not match:
index | penalty | description
-------|---------|-------------
- | 1 | User did not match
- | 2 | Group did not match
0 | 4 | SetUID bit did not match
1 | 8 | SetGID bit did not match
2 | 16 | Sticky bit did not match
3 | 32 | User Read bit did not match
4 | 64 | User Write bit did not match
5 | 128 | User Execute bit did not match
6 | 256 | Group Read bit did not match
7 | 512 | Group Write bit did not match
8 | 1024 | Group Execute bit did not match
9 | 2048 | Other Read bit did not match
10 | 4096 | Other Write bit did not match
11 | 8192 | Other Execute bit did not match
"""
state = 0
## Convert expected_mode to binary string
if len(expected_mode) in [3, 4]:
if expected_mode[0] == '0':
expected_mode = expected_mode[-3:] # Strip leading zero otherwise it can break things, e.g. 0750 -> 750
else:
raise ValueError(f'The "expected_mode" for {file} should be 3 or 4 characters long, not {len(expected_mode)}')
octal_expected_mode = oct(int(expected_mode, 8)) # Convert octal (base8) file mode to decimal (base10)
binary_expected_mode = str(format(int(octal_expected_mode, 8), '012b')) # Convert decimal (base10) to binary (base2) for bit-by-bit comparison
## Get file stats and user/group
try:
file_stat = os.stat(file)
except Exception as e:
self.log.warning(f'Error trying to stat file {file}: "{e}"')
return -1
file_user = getpwuid(file_stat.st_uid).pw_name
file_group = getgrgid(file_stat.st_gid).gr_name
## Convert file_mode to binary string
file_mode = int(stat.S_IMODE(file_stat.st_mode))
octal_file_mode = oct(file_mode)
binary_file_mode = str(format(int(file_mode), '012b'))
if expected_user is not None:
## Set fail state if user does not match expectation
if file_user != expected_user:
state += 1
self.log.debug(f'Test failure: file_user "{file_user}" for {file} did not match expected_user "{expected_user}"')
if expected_group is not None:
## Set fail state if group does not match expecation
if file_group != expected_group:
state += 2
self.log.debug(f'Test failure: file_group "{file_group}" for {file} did not match expected_group "{expected_group}"')
## Iterate over all bits in the binary_file_mode to ensure they're equal to, or more restrictive than, the expected_mode. Refer to the table in the description above for what the individual 'this_failure_score' values refer to.
for i in range(len(binary_file_mode)):
if binary_expected_mode[i] == '0':
if binary_file_mode[i] != '0':
## Add unique state so we can identify which bit a permission failed on, for debugging
this_failure_score = 2 ** (i + 2)
state += this_failure_score
self.log.debug(f'Test comparison for {file}, {octal_expected_mode}>={octal_file_mode} {binary_expected_mode[i]} == {binary_file_mode[i]}. Failed at index {i}. Adding {this_failure_score} to state')
else:
self.log.debug(f'Test comparison for {file}, {octal_expected_mode}>={octal_file_mode} {binary_expected_mode[i]} == {binary_file_mode[i]}. Passed at index {i}')
return state
def audit_filesystem_integrity_regularly_checked(self) -> int:
state = 1
cmd = R"grep -Ers '^([^#]+\s+)?(\/usr\/s?bin\/|^\s*)aide(\.wrapper)?\s(--?\S+\s)*(--(check|update)|\$AIDEARGS)\b' /etc/cron.* /etc/crontab /var/spool/cron/root /etc/anacrontab"
r = self._shellexec(cmd)
if r.stdout[0] != '':
state = 0
else:
cmd1 = 'systemctl is-enabled aidecheck.service'
cmd2 = 'systemctl is-enabled aidecheck.timer'
cmd3 = 'systemctl is-active aidecheck.timer'
r1 = self._shellexec(cmd1)
r2 = self._shellexec(cmd2)
r3 = self._shellexec(cmd3)
if all(
[
r1.stdout[0] == 'enabled',
r2.stdout[0] == 'enabled',
r3.stdout[0] == 'active',
]
):
state = 0
return state
def audit_firewalld_default_zone_is_set(self) -> int:
cmd = 'firewall-cmd --get-default-zone'
r = self._shellexec(cmd)
if r.stdout[0] != '':
state = 0
else:
state = 1
return state
def audit_gdm_last_user_logged_in_disabled(self) -> int:
state = 0
if self.audit_package_is_installed(package="gdm") == 0:
## Test contents of /etc/dconf/profile/gdm if it exists
file = "/etc/dconf/profile/gdm"
if os.path.exists(file):
with open(file) as f:
contents = f.read()
if "user-db:user" not in contents:
state += 2
if "system-db:gdm" not in contents:
state += 4
if "file-db:/usr/share/gdm/greeter-dconf-defaults" not in contents:
state += 8
else:
state += 1
## Test contents of /etc/dconf/db/gdm.d/01-banner-message, if it exists
file = "/etc/dconf/db/gdm.d/00-login-screen"
if os.path.exists(file):
with open(file) as f:
contents = f.read()
if "[org/gnome/login-screen]\ndisable-user-list=true" not in contents:
state += 32
else:
state += 16
else: