cis-benchmarks-tools 2.9.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
audit_cis.py ADDED
@@ -0,0 +1,199 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Unified CIS Benchmark Audit Engine v2.9.1
4
+ Automated security audit suite for databases and Linux operating systems (Local & SSH Remote Modes).
5
+ 100% Python Standard Library (PSL ONLY).
6
+ """
7
+
8
+ import argparse
9
+ import datetime
10
+ import json
11
+ import os
12
+ import subprocess
13
+ import sys
14
+
15
+ __version__ = "2.9.1"
16
+
17
+ TARGET_MAP = {
18
+ "mariadb106": ("audit_cis_mariadb_106.py", "MariaDB 10.6", 74),
19
+ "mariadb1011": ("audit_cis_mariadb_1011.py", "MariaDB 10.11", 75),
20
+ "mysql80": ("audit_cis_mysql_80.py", "MySQL Enterprise 8.0", 70),
21
+ "mysql-community84": ("audit_cis_mysql_community_84.py", "MySQL Community 8.4 LTS", 79),
22
+ "mysql-enterprise84": ("audit_cis_mysql_enterprise_84.py", "MySQL Enterprise 8.4 LTS", 70),
23
+ "mysql-community97": ("audit_cis_mysql_community_97.py", "MySQL Community 9.7", 70),
24
+ "mysql-enterprise97": ("audit_cis_mysql_enterprise_97.py", "MySQL Enterprise 9.7", 70),
25
+ "postgresql16": ("audit_cis_postgresql_16.py", "PostgreSQL 16", 71),
26
+ "postgresql17": ("audit_cis_postgresql_17.py", "PostgreSQL 17", 71),
27
+ "postgresql18": ("audit_cis_postgresql_18.py", "PostgreSQL 18", 71),
28
+ "mongodb7": ("audit_cis_mongodb_7.py", "MongoDB 7.0", 23),
29
+ "mongodb8": ("audit_cis_mongodb_8.py", "MongoDB 8.0", 23),
30
+ "cassandra40": ("audit_cis_cassandra_40.py", "Apache Cassandra 4.0", 20),
31
+ "cassandra41": ("audit_cis_cassandra_41.py", "Apache Cassandra 4.1", 20),
32
+ "cassandra50": ("audit_cis_cassandra_50.py", "Apache Cassandra 5.0", 20),
33
+ "rhel8": ("audit_cis_rhel_8.py", "Red Hat Enterprise Linux 8", 20),
34
+ "rhel9": ("audit_cis_rhel_9.py", "Red Hat Enterprise Linux 9", 20),
35
+ "rhel10": ("audit_cis_rhel_10.py", "Red Hat Enterprise Linux 10", 20),
36
+ }
37
+
38
+
39
+ def list_targets():
40
+ """List all supported CIS audit targets."""
41
+ print(f"\nšŸ“‹ [v{__version__}] Supported CIS Audit Targets ({len(TARGET_MAP)} Benchmarks / 887 Controls):\n")
42
+ print(f" {'Target Key':<22} {'Name':<30} {'Controls':<10} {'Script File'}")
43
+ print(f" {'-'*22} {'-'*30} {'-'*10} {'-'*30}")
44
+ for key, (script, name, count) in TARGET_MAP.items():
45
+ print(f" {key:<22} {name:<30} {count:<10} {script}")
46
+ print()
47
+
48
+
49
+ def run_single_audit(target_key, output_file=None, fmt="html", lang="en", mode="local", remote_host=None, ssh_port=22, ssh_key=None, docker_container=None, db_host=None, db_port=None, db_user=None, db_password=None, db_name=None, defaults_file=None, auth_db=None, use_sudo=False):
50
+ """Run audit for a single target in Local, SSH Remote, or Docker mode."""
51
+ if target_key not in TARGET_MAP:
52
+ print(f"āŒ Unknown target '{target_key}'. Use --list-targets to view valid keys.", file=sys.stderr)
53
+ return False
54
+
55
+ script_file, label, count = TARGET_MAP[target_key]
56
+ script_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), script_file)
57
+
58
+ if not os.path.exists(script_path):
59
+ print(f"āŒ Script not found: {script_path}", file=sys.stderr)
60
+ return False
61
+
62
+ mode_label = f"SSH Remote Mode ({remote_host})" if (mode == "ssh" or remote_host) else "Local Mode"
63
+ if docker_container:
64
+ mode_label += f" [Docker: {docker_container}]"
65
+ print(f"\nšŸš€ [v{__version__}] Running CIS Audit for {label} [{mode_label}] ({count} controls, {script_file})...")
66
+ start_time = datetime.datetime.now()
67
+
68
+ cmd = [sys.executable, script_path, "--format", fmt, "--lang", lang, "--mode", mode]
69
+ if docker_container:
70
+ cmd.extend(["--docker", docker_container])
71
+ if remote_host:
72
+ cmd.extend(["--remote", remote_host])
73
+ if ssh_port and int(ssh_port) != 22:
74
+ cmd.extend(["--ssh-port", str(ssh_port)])
75
+ if ssh_key:
76
+ cmd.extend(["--ssh-key", ssh_key])
77
+ if db_host:
78
+ cmd.extend(["--db-host", db_host])
79
+ if db_port:
80
+ cmd.extend(["--db-port", str(db_port)])
81
+ if db_user:
82
+ cmd.extend(["--db-user", db_user])
83
+ if db_password:
84
+ cmd.extend(["--db-password", db_password])
85
+ if db_name:
86
+ cmd.extend(["--db-name", db_name])
87
+ if defaults_file:
88
+ cmd.extend(["--defaults-file", defaults_file])
89
+ if auth_db:
90
+ cmd.extend(["--auth-db", auth_db])
91
+ if use_sudo:
92
+ cmd.append("--sudo")
93
+ if output_file:
94
+ cmd.extend(["--output", output_file])
95
+
96
+ try:
97
+ subprocess.run(cmd, check=True)
98
+ elapsed = (datetime.datetime.now() - start_time).total_seconds()
99
+ print(f"āœ… {label} CIS Audit completed successfully in {elapsed:.2f}s")
100
+ return True
101
+ except subprocess.CalledProcessError as e:
102
+ print(f"āŒ CIS Audit for {label} failed with exit code {e.returncode}", file=sys.stderr)
103
+ return False
104
+
105
+
106
+ def auto_detect_and_run():
107
+ """Programmatic API & CLI: Detect running database containers and execute audits."""
108
+ print(f"šŸ” [v{__version__}] Auto-detecting active database containers...")
109
+ detected = []
110
+
111
+ try:
112
+ ps_out = subprocess.check_output(["docker", "ps", "--format", "{{.Names}} {{.Image}}"], text=True)
113
+ for line in ps_out.splitlines():
114
+ line_norm = line.lower().replace(".", "").replace(":", "").replace("-", "").replace("_", "")
115
+ for key in TARGET_MAP:
116
+ key_norm = key.lower().replace(".", "").replace(":", "").replace("-", "").replace("_", "")
117
+ aliases = [
118
+ key_norm,
119
+ key_norm.replace("postgresql", "postgres"),
120
+ key_norm.replace("mongodb", "mongo"),
121
+ key.split("-")[0].lower().replace(".", "")
122
+ ]
123
+ if any(alias in line_norm for alias in aliases):
124
+ if key not in detected:
125
+ detected.append(key)
126
+ except Exception as e:
127
+ print(f"āš ļø Docker auto-detection note: {e}")
128
+
129
+ if not detected:
130
+ print("ā„¹ļø No specific containers auto-detected. Listing available targets.")
131
+ list_targets()
132
+ return
133
+
134
+ print(f"šŸŽÆ Auto-detected targets: {', '.join(detected)}")
135
+ for target in detected:
136
+ run_single_audit(target)
137
+
138
+
139
+ def main():
140
+ parser = argparse.ArgumentParser(
141
+ description=f"Unified CIS Benchmark Audit Suite v{__version__} (Local & SSH Remote Modes, PSL ONLY)",
142
+ formatter_class=argparse.RawDescriptionHelpFormatter
143
+ )
144
+ parser.add_argument("-t", "--target", choices=list(TARGET_MAP.keys()), help="Target database benchmark to audit")
145
+ parser.add_argument("-c", "--docker", "--container", dest="docker_container", default=None, help="Target Docker container name or ID")
146
+ parser.add_argument("-m", "--mode", choices=["local", "ssh"], default="local", help="Audit execution mode (local or ssh)")
147
+ parser.add_argument("-r", "--remote", "--ssh", dest="remote_host", default=None, help="Remote SSH server target (e.g. user@hostname)")
148
+ parser.add_argument("--ssh-port", type=int, default=22, help="SSH port for remote execution (default: 22)")
149
+ parser.add_argument("-i", "--ssh-key", dest="ssh_key", default=None, help="Path to SSH private key file")
150
+ parser.add_argument("--sudo", action="store_true", help="Execute remote/local commands with sudo privileges")
151
+ parser.add_argument("-H", "--host", "--db-host", dest="db_host", default="localhost", help="Database host address (default: localhost)")
152
+ parser.add_argument("-P", "--port", "--db-port", dest="db_port", type=int, default=None, help="Database port number")
153
+ parser.add_argument("-u", "--user", "--db-user", dest="db_user", default=None, help="Database username")
154
+ parser.add_argument("-p", "--password", "--db-password", dest="db_password", default=None, help="Database password")
155
+ parser.add_argument("-D", "-d", "--database", "--db-name", dest="db_name", default=None, help="Database name")
156
+ parser.add_argument("--defaults-file", "--config-file", dest="defaults_file", default=None, help="Path to database option/configuration file (.my.cnf, .pgpass, cqlshrc)")
157
+ parser.add_argument("--auth-db", dest="auth_db", default=None, help="Authentication database (MongoDB)")
158
+ parser.add_argument("--local", action="store_true", help="Force local audit execution mode")
159
+ parser.add_argument("-f", "--format", choices=["html", "json", "xml", "txt"], default="html", help="Report output format (html/json/xml/txt)")
160
+ parser.add_argument("-l", "--lang", choices=["en", "fr"], default="en", help="Language for report and CLI output (en/fr)")
161
+ parser.add_argument("-o", "--output", dest="output", default=None, help="Path to save report output")
162
+ parser.add_argument("-j", "--output-json", help="Path to save JSON summary report")
163
+ parser.add_argument("--list-targets", action="store_true", help="List all supported database targets")
164
+ parser.add_argument("-a", "--all", action="store_true", help="Run CIS audits for ALL targets sequentially")
165
+ parser.add_argument("--auto-detect", action="store_true", help="Auto-detect running database containers and execute audits")
166
+ parser.add_argument("-v", "--version", action="version", version=f"CIS Benchmarks Suite v{__version__}")
167
+
168
+ args = parser.parse_args()
169
+
170
+ if args.list_targets:
171
+ list_targets()
172
+ sys.exit(0)
173
+
174
+ if args.auto_detect:
175
+ auto_detect_and_run()
176
+ sys.exit(0)
177
+
178
+ exec_mode = "ssh" if (args.mode == "ssh" or args.remote_host) else "local"
179
+
180
+ if args.all:
181
+ print(f"🌟 [v{__version__}] Executing CIS Audit for ALL targets [Mode: {exec_mode}]...")
182
+ success_count = 0
183
+ for target_key in TARGET_MAP:
184
+ if run_single_audit(target_key, fmt=args.format, lang=args.lang, mode=exec_mode, remote_host=args.remote_host, ssh_port=args.ssh_port, ssh_key=args.ssh_key, docker_container=args.docker_container, db_host=args.db_host, db_port=args.db_port, db_user=args.db_user, db_password=args.db_password, db_name=args.db_name, defaults_file=args.defaults_file, auth_db=args.auth_db, use_sudo=args.sudo):
185
+ success_count += 1
186
+ print(f"\nšŸŽ‰ Completed: {success_count}/{len(TARGET_MAP)} CIS audits succeeded.")
187
+ sys.exit(0 if success_count == len(TARGET_MAP) else 1)
188
+
189
+ if args.target:
190
+ out = args.output or args.output_json
191
+ fmt = "json" if args.output_json and not args.output else args.format
192
+ success = run_single_audit(args.target, output_file=out, fmt=fmt, lang=args.lang, mode=exec_mode, remote_host=args.remote_host, ssh_port=args.ssh_port, ssh_key=args.ssh_key, docker_container=args.docker_container, db_host=args.db_host, db_port=args.db_port, db_user=args.db_user, db_password=args.db_password, db_name=args.db_name, defaults_file=args.defaults_file, auth_db=args.auth_db, use_sudo=args.sudo)
193
+ sys.exit(0 if success else 1)
194
+
195
+ parser.print_help()
196
+
197
+
198
+ if __name__ == "__main__":
199
+ main()