secuditor 0.5.0__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.
secuditor/__init__.py ADDED
@@ -0,0 +1,51 @@
1
+ # Secuditor CLI – Copyright (c) 2026 Menahem Levinski
2
+
3
+ """Secuditor: Cross-platform security diagnostics and auditing library."""
4
+
5
+ from importlib import import_module
6
+
7
+ __version__ = "0.5.0"
8
+ __author__ = "Menahem Levinski"
9
+ __license__ = "MIT"
10
+
11
+ __all__ = [
12
+ "__version__",
13
+ "__author__",
14
+ "__license__",
15
+ "DomainAudit",
16
+ "InstalledApps",
17
+ "NetworkSettings",
18
+ "PasswordPolicy",
19
+ "SystemSettings",
20
+ ]
21
+
22
+ _MODULES = {
23
+ "DomainAudit": ".domain_settings",
24
+ "DomainSettingsAudit": ".domain_settings",
25
+ "InstalledApps": ".installed_apps",
26
+ "InstalledAppsAudit": ".installed_apps",
27
+ "NetworkSettings": ".network_settings",
28
+ "NetworkSettingsAudit": ".network_settings",
29
+ "PasswordPolicy": ".password_policy",
30
+ "PasswordPolicyAudit": ".password_policy",
31
+ "SystemSettings": ".system_settings",
32
+ "SystemSettingsAudit": ".system_settings",
33
+ }
34
+
35
+
36
+ def __getattr__(name: str):
37
+ """Load audit classes on demand."""
38
+ if name not in _MODULES:
39
+ raise AttributeError(
40
+ f"module {__name__!r} has no attribute {name!r}"
41
+ )
42
+
43
+ module = import_module(_MODULES[name], __name__)
44
+ value = getattr(module, name)
45
+ globals()[name] = value
46
+ return value
47
+
48
+
49
+ def __dir__() -> list[str]:
50
+ """Return public package attributes."""
51
+ return sorted(set(__all__))
secuditor/_utils.py ADDED
@@ -0,0 +1,199 @@
1
+ # Secuditor CLI – Copyright (c) 2026 Menahem Levinski
2
+
3
+ """Shared internal utilities for subprocess, PowerShell, and registry access."""
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ from typing import Any
11
+
12
+ _IS_WINDOWS = sys.platform == "win32"
13
+
14
+ _WINDOWS_BUILTIN_COMMANDS = {
15
+ "dsregcmd",
16
+ "dsregcmd.exe",
17
+ "net",
18
+ "net.exe",
19
+ "netsh",
20
+ "netsh.exe",
21
+ "powershell",
22
+ "powershell.exe",
23
+ "sc",
24
+ "sc.exe",
25
+ "secedit",
26
+ "secedit.exe",
27
+ "w32tm",
28
+ "w32tm.exe",
29
+ }
30
+
31
+ if _IS_WINDOWS:
32
+ _CREATE_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)
33
+ try:
34
+ _STARTUPINFO = subprocess.STARTUPINFO()
35
+ _STARTUPINFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW
36
+ _STARTUPINFO.wShowWindow = subprocess.SW_HIDE
37
+ except Exception:
38
+ _STARTUPINFO = None
39
+ else:
40
+ _CREATE_NO_WINDOW = 0
41
+ _STARTUPINFO = None
42
+
43
+
44
+ def _system_exe(name: str) -> str:
45
+ """Resolve Windows built-in tools from System32 to prevent PATH/CWD hijacking."""
46
+ if not _IS_WINDOWS or not name or os.path.isabs(name):
47
+ return name
48
+
49
+ lower_name = name.lower()
50
+ if lower_name not in _WINDOWS_BUILTIN_COMMANDS:
51
+ return name
52
+
53
+ sysroot = os.environ.get("SystemRoot", r"C:\Windows")
54
+ sys32 = os.path.join(sysroot, "System32")
55
+
56
+ if lower_name in ("powershell", "powershell.exe"):
57
+ ps_path = os.path.join(
58
+ sys32, "WindowsPowerShell", "v1.0", "powershell.exe"
59
+ )
60
+ if os.path.isfile(ps_path):
61
+ return ps_path
62
+
63
+ base = os.path.basename(name)
64
+ candidates = [name] if "." in base else [f"{name}.exe", f"{name}.cmd"]
65
+ for directory in (sys32, os.path.join(sys32, "wbem")):
66
+ for candidate_name in candidates:
67
+ candidate = os.path.join(directory, candidate_name)
68
+ if os.path.isfile(candidate):
69
+ return candidate
70
+
71
+ return shutil.which(name) or name
72
+
73
+
74
+ def _safe_subproc_env() -> dict[str, str]:
75
+ """Return a subprocess environment hardened against CWD exe lookup on Windows."""
76
+ env = dict(os.environ)
77
+ if _IS_WINDOWS:
78
+ env.setdefault("NoDefaultCurrentDirectoryInExePath", "1")
79
+ return env
80
+
81
+
82
+ def _windows_subproc_kwargs() -> dict[str, Any]:
83
+ """Return Windows-only kwargs to hide child console windows."""
84
+ if not _IS_WINDOWS:
85
+ return {}
86
+ kwargs: dict[str, Any] = {"creationflags": _CREATE_NO_WINDOW}
87
+ if _STARTUPINFO is not None:
88
+ kwargs["startupinfo"] = _STARTUPINFO
89
+ return kwargs
90
+
91
+
92
+ def run_command_result(
93
+ args: list[str],
94
+ timeout: float = 8.0,
95
+ ) -> tuple[int, str, str] | None:
96
+ """Run a command safely without a shell and return (returncode, stdout, stderr)."""
97
+ if not args:
98
+ return None
99
+
100
+ resolved_args = [_system_exe(str(args[0])), *args[1:]]
101
+ try:
102
+ result = subprocess.run(
103
+ resolved_args,
104
+ capture_output=True,
105
+ text=True,
106
+ errors="replace",
107
+ timeout=timeout,
108
+ check=False,
109
+ shell=False,
110
+ env=_safe_subproc_env(),
111
+ **_windows_subproc_kwargs(),
112
+ )
113
+ return result.returncode, result.stdout, result.stderr
114
+ except (OSError, subprocess.SubprocessError):
115
+ return None
116
+
117
+
118
+ def run_command(
119
+ args: list[str],
120
+ timeout: float = 8.0,
121
+ strip: bool = True,
122
+ ) -> str | None:
123
+ """Run a command without a shell and return stdout on success, else None."""
124
+ result = run_command_result(args, timeout=timeout)
125
+ if result is None:
126
+ return None
127
+ returncode, stdout, _ = result
128
+ if returncode == 0:
129
+ return stdout.strip() if strip else stdout
130
+ return None
131
+
132
+
133
+ def find_powershell() -> str | None:
134
+ """Return the path to a PowerShell executable if available."""
135
+ if _IS_WINDOWS:
136
+ resolved = _system_exe("powershell.exe")
137
+ if os.path.isabs(resolved) and os.path.isfile(resolved):
138
+ return resolved
139
+ return shutil.which("powershell") or shutil.which("pwsh")
140
+
141
+
142
+ def run_powershell(
143
+ command: str,
144
+ timeout: float = 8.0,
145
+ parse_json: bool = True,
146
+ stop_on_error: bool = False,
147
+ ) -> Any:
148
+ """Run a PowerShell command non-interactively and optionally parse JSON."""
149
+ executable = find_powershell()
150
+ if not executable:
151
+ return None
152
+
153
+ script = (
154
+ f"$ErrorActionPreference = 'Stop'; {command}"
155
+ if stop_on_error
156
+ else command
157
+ )
158
+
159
+ output = run_command(
160
+ [
161
+ executable,
162
+ "-NoLogo",
163
+ "-NoProfile",
164
+ "-NonInteractive",
165
+ "-Command",
166
+ script,
167
+ ],
168
+ timeout=timeout,
169
+ )
170
+
171
+ if not output:
172
+ return None
173
+
174
+ if not parse_json:
175
+ return output
176
+
177
+ try:
178
+ return json.loads(output)
179
+ except (json.JSONDecodeError, TypeError):
180
+ return None
181
+
182
+
183
+ def read_registry_value(root_name: str, path: str, name: str) -> Any:
184
+ """Read a Windows registry value from HKLM or HKCU using the 64-bit view."""
185
+ try:
186
+ import winreg
187
+
188
+ roots = {
189
+ "HKLM": winreg.HKEY_LOCAL_MACHINE,
190
+ "HKCU": winreg.HKEY_CURRENT_USER,
191
+ }
192
+ root = roots[root_name]
193
+ access = winreg.KEY_READ | getattr(winreg, "KEY_WOW64_64KEY", 0)
194
+
195
+ with winreg.OpenKey(root, path, 0, access) as key:
196
+ value, _ = winreg.QueryValueEx(key, name)
197
+ return value
198
+ except (OSError, ImportError, KeyError):
199
+ return None
secuditor/cli.py ADDED
@@ -0,0 +1,150 @@
1
+ # Secuditor CLI – Copyright (c) 2026 Menahem Levinski
2
+
3
+ """Command-line interface for Secuditor CLI."""
4
+
5
+ import argparse
6
+ from collections.abc import Sequence
7
+ from importlib import import_module
8
+ import json
9
+ import sys
10
+
11
+ from . import __version__
12
+
13
+ _AUDIT_SPECS = {
14
+ "dsa": (".domain_settings", "DomainAudit", "Domain Settings Audit"),
15
+ "app": (".installed_apps", "InstalledApps", "Installed Applications Audit"),
16
+ "pwd": (".password_policy", "PasswordPolicy", "Password Policy Audit"),
17
+ "sys": (".system_settings", "SystemSettings", "System Settings Audit"),
18
+ "net": (".network_settings", "NetworkSettings", "Network Settings Audit"),
19
+ }
20
+
21
+
22
+ def build_parser() -> argparse.ArgumentParser:
23
+ """Build the command-line argument parser."""
24
+ parser = argparse.ArgumentParser(
25
+ prog="secuditor",
26
+ description="Cross-platform security diagnostics and auditing toolkit.",
27
+ allow_abbrev=False,
28
+ )
29
+
30
+ parser.add_argument(
31
+ "--version",
32
+ action="version",
33
+ version=f"%(prog)s {__version__}",
34
+ )
35
+
36
+ parser.add_argument(
37
+ "--json",
38
+ action="store_true",
39
+ help="Output results as JSON",
40
+ )
41
+
42
+ group = parser.add_mutually_exclusive_group(required=True)
43
+ group.add_argument(
44
+ "-dsa",
45
+ "--domain",
46
+ dest="audit",
47
+ action="store_const",
48
+ const="dsa",
49
+ help="Audit domain settings",
50
+ )
51
+ group.add_argument(
52
+ "-app",
53
+ "--apps",
54
+ dest="audit",
55
+ action="store_const",
56
+ const="app",
57
+ help="Audit installed applications",
58
+ )
59
+ group.add_argument(
60
+ "-pwd",
61
+ "--password",
62
+ dest="audit",
63
+ action="store_const",
64
+ const="pwd",
65
+ help="Audit password policy",
66
+ )
67
+ group.add_argument(
68
+ "-sys",
69
+ "--system",
70
+ dest="audit",
71
+ action="store_const",
72
+ const="sys",
73
+ help="Audit system settings",
74
+ )
75
+ group.add_argument(
76
+ "-net",
77
+ "--network",
78
+ dest="audit",
79
+ action="store_const",
80
+ const="net",
81
+ help="Audit network settings",
82
+ )
83
+
84
+ return parser
85
+
86
+
87
+ def _print_value(value, indent: int = 0) -> None:
88
+ """Print nested dicts/lists in a readable plain-text layout."""
89
+ prefix = " " * indent
90
+ if isinstance(value, dict):
91
+ if not value:
92
+ print(f"{prefix}(none)")
93
+ return
94
+ for key, item in value.items():
95
+ label = str(key).replace("_", " ").title()
96
+ if isinstance(item, (dict, list, tuple)):
97
+ print(f"{prefix}{label}:")
98
+ _print_value(item, indent + 2)
99
+ else:
100
+ print(f"{prefix}{label}: {item}")
101
+ elif isinstance(value, (list, tuple)):
102
+ if not value:
103
+ print(f"{prefix}(none)")
104
+ return
105
+ for item in value:
106
+ if isinstance(item, (dict, list, tuple)):
107
+ print(f"{prefix}-")
108
+ _print_value(item, indent + 2)
109
+ else:
110
+ print(f"{prefix}- {item}")
111
+ else:
112
+ print(f"{prefix}{value}")
113
+
114
+
115
+ def print_results(title: str, results, as_json: bool = False) -> None:
116
+ """Print audit results in text or JSON format."""
117
+ if as_json:
118
+ print(json.dumps(results, indent=2, default=str, ensure_ascii=False))
119
+ return
120
+
121
+ print(f"\nSecuditor {title}")
122
+ print("=" * 50)
123
+ _print_value(results)
124
+
125
+
126
+ def main(argv: Sequence[str] | None = None) -> int:
127
+ """Run the selected audit command."""
128
+ parser = build_parser()
129
+ args = parser.parse_args(argv)
130
+
131
+ module_name, class_name, title = _AUDIT_SPECS[args.audit]
132
+
133
+ try:
134
+ module = import_module(module_name, package=__package__)
135
+ audit_class = getattr(module, class_name)
136
+ results = audit_class().audit()
137
+ print_results(title, results, args.json)
138
+ return 0
139
+
140
+ except KeyboardInterrupt:
141
+ print("\nAudit cancelled.", file=sys.stderr)
142
+ return 130
143
+
144
+ except Exception as exc:
145
+ print(f"Error: {exc}", file=sys.stderr)
146
+ return 1
147
+
148
+
149
+ if __name__ == "__main__":
150
+ raise SystemExit(main())