#!/usr/bin/env python3 """Generate docs/CONTROLS.md: every audited control, its references, its rule and the local data source per OS. Usage: python3 tools/build_controls_doc.py Standard library only. Keep SOURCES in step with collectors/*/audit.*. """ import json import os ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Where each check reads its evidence on the device (all read-only). SOURCES = { "password.min_length": {"windows": "secedit export: MinimumPasswordLength", "linux": "PAM pam_pwquality minlen (/etc/security/pwquality.conf, PAM args)", "macos": "pwpolicy -getaccountpolicies (minLength / regex)"}, "password.history": {"windows": "secedit export: PasswordHistorySize", "linux": "pam_pwhistory remember (PAM args, /etc/security/pwhistory.conf)", "macos": "pwpolicy: policyAttributePasswordHistoryDepth"}, "password.expiration": {"windows": "secedit export: MaximumPasswordAge", "linux": "/etc/login.defs PASS_MAX_DAYS + /etc/shadow per account", "macos": "pwpolicy: policyAttributeExpiresEveryNDays"}, "password.min_age": {"windows": "secedit export: MinimumPasswordAge", "linux": "/etc/login.defs PASS_MIN_DAYS + /etc/shadow per account", "macos": "not available on macOS (NotApplicable)"}, "password.complexity": {"windows": "secedit export: PasswordComplexity", "linux": "pam_pwquality minclass / dcredit-ucredit-lcredit-ocredit", "macos": "pwpolicy: alpha + numeric requirements"}, "lockout.threshold": {"windows": "secedit export: LockoutBadCount", "linux": "pam_faillock deny (PAM args, /etc/security/faillock.conf)", "macos": "pwpolicy: policyAttributeMaximumFailedAuthentications"}, "lockout.duration": {"windows": "secedit export: LockoutDuration", "linux": "pam_faillock unlock_time", "macos": "pwpolicy: autoEnableInSeconds"}, "lockout.observation": {"windows": "secedit export: ResetLockoutCount", "linux": "pam_faillock fail_interval", "macos": "pwpolicy: autoEnableInSeconds (counter resets with lockout)"}, "malware.antivirus": {"windows": "Security Center (root/SecurityCenter2 AntiVirusProduct)", "linux": "systemd services: clamav-daemon, mdatp, falcon-sensor, sentinelone, sophos-spl, esets", "macos": "XProtect version (xprotect version) + running third-party agents"}, "malware.service": {"windows": "Get-MpComputerStatus: AMServiceEnabled, AntivirusEnabled", "linux": "systemctl is-active clamav-daemon / clamd", "macos": "xprotect status + spctl --status (Gatekeeper)"}, "malware.realtime": {"windows": "Get-MpComputerStatus: RealTimeProtectionEnabled"}, "malware.on_access": {"windows": "Get-MpComputerStatus: OnAccessProtectionEnabled", "linux": "clamav-clamonacc service / clamonacc process", "macos": "third-party agent only (XProtect has no on-access scan)"}, "malware.tamper": {"windows": "Get-MpComputerStatus: IsTamperProtected"}, "malware.signatures": {"windows": "Get-MpComputerStatus: AntivirusSignatureAge", "linux": "age of /var/lib/clamav/daily.c[lv]d", "macos": "XProtect install date (xprotect version / XProtect.meta.plist)"}, "malware.signature_updates": {"linux": "systemctl is-active clamav-freshclam", "macos": "com.apple.SoftwareUpdate ConfigDataInstall + CriticalUpdateInstall"}, "firewall.enabled": {"linux": "ufw status / firewalld / nft list ruleset / iptables -S", "macos": "socketfilterfw --getglobalstate"}, "firewall.inbound": {"linux": "ufw default incoming / firewalld zone target / nft input policy", "macos": "socketfilterfw --getstealthmode"}, "firewall.outbound": {"linux": "ufw default outgoing / nft output policy", "macos": "application firewall is inbound-only"}, "firewall.domain.enabled": {"windows": "Get-NetFirewallProfile -PolicyStore ActiveStore (Domain)"}, "firewall.domain.inbound": {"windows": "Get-NetFirewallProfile: DefaultInboundAction (Domain)"}, "firewall.domain.outbound": {"windows": "Get-NetFirewallProfile: DefaultOutboundAction (Domain)"}, "firewall.private.enabled": {"windows": "Get-NetFirewallProfile -PolicyStore ActiveStore (Private)"}, "firewall.private.inbound": {"windows": "Get-NetFirewallProfile: DefaultInboundAction (Private)"}, "firewall.private.outbound": {"windows": "Get-NetFirewallProfile: DefaultOutboundAction (Private)"}, "firewall.public.enabled": {"windows": "Get-NetFirewallProfile -PolicyStore ActiveStore (Public)"}, "firewall.public.inbound": {"windows": "Get-NetFirewallProfile: DefaultInboundAction (Public)"}, "firewall.public.outbound": {"windows": "Get-NetFirewallProfile: DefaultOutboundAction (Public)"}, "screen_lock.enabled": {"windows": "InactivityTimeoutSecs policy or users' ScreenSaveActive/ScreenSaverIsSecure (HKU)", "linux": "gsettings org.gnome.desktop.screensaver lock-enabled + session idle-delay (per user)", "macos": "sysadminctl -screenLock status / managed com.apple.screensaver"}, "screen_lock.timeout": {"windows": "InactivityTimeoutSecs policy or users' ScreenSaveTimeOut (HKU)", "linux": "gsettings idle-delay + lock-delay (per user)", "macos": "screen saver idleTime + pmset displaysleep + password delay"}, "screen_lock.password": {"windows": "InactivityTimeoutSecs policy or users' ScreenSaverIsSecure; DisableLockWorkstation", "linux": "gsettings lock-enabled + lockdown disable-lock-screen", "macos": "sysadminctl -screenLock delay / managed askForPassword"}, "usb.device_access": {"windows": "RemovableStorageDevices Deny_All policy, USBSTOR service Start", "linux": "modprobe usb-storage install rule / blacklist / USBGuard", "macos": "managed com.apple.systemuiserver mount-controls"}, "usb.read": {"windows": "RemovableStorageDevices policies (Deny_All, Deny_Read), USBSTOR Start", "linux": "usb-storage module rules, USBGuard", "macos": "managed mount-controls (deny)"}, "usb.write": {"windows": "RemovableStorageDevices Deny_Write, StorageDevicePolicies WriteProtect", "linux": "udev read-only rules, usb-storage rules, USBGuard", "macos": "managed mount-controls (deny / read-only)"}, "admin.approved": {"windows": "Administrators group by SID S-1-5-32-544 (ADSI) + Get-LocalUser", "linux": "getent group sudo/admin/wheel, UID 0 accounts, /etc/sudoers(.d)", "macos": "dscl . -read /Groups/admin GroupMembership"}, "admin.unauthorized": {"windows": "Administrators group by SID S-1-5-32-544 (ADSI) + Get-LocalUser", "linux": "getent group sudo/admin/wheel, UID 0 accounts, /etc/sudoers(.d)", "macos": "dscl . -read /Groups/admin GroupMembership"}, "user.account_type": {"windows": "signed-in user (Win32_ComputerSystem) vs Administrators group", "linux": "session users (loginctl) vs sudo/admin/wheel", "macos": "console user (stat /dev/console) + dsmemberutil checkmembership"}, "encryption.feature": {"windows": "Get-BitLockerVolume (system drive): VolumeStatus"}, "encryption.enabled": {"windows": "Get-BitLockerVolume: VolumeStatus, EncryptionPercentage", "linux": "findmnt / + lsblk (crypt device under /)", "macos": "fdesetup status"}, "encryption.protection": {"windows": "Get-BitLockerVolume: ProtectionStatus, EncryptionMethod", "linux": "cryptsetup status (type, cipher, key size)", "macos": "fdesetup status (no encryption in progress)"}, "encryption.recovery": {"windows": "Get-BitLockerVolume: KeyProtector (RecoveryPassword)", "linux": "cryptsetup luksDump (key slots, tokens)", "macos": "fdesetup haspersonalrecoverykey / hasinstitutionalrecoverykey"}, "vuln.pending_updates": {"windows": "Windows Update Agent API (Microsoft.Update.Session search) - needs internet", "linux": "apt-get -s upgrade (security) / dnf updateinfo --security - uses local package lists", "macos": "softwareupdate -l - needs internet"}, "vuln.outdated_apps": {"windows": "winget upgrade", "linux": "apt upgradable, snap refresh --list, flatpak updates", "macos": "brew outdated (Homebrew; App Store apps not covered)"}, "vuln.known_vulnerabilities": {"windows": "installed programs (machine and per-user uninstall registry) matched by the app against the signed offline bundle (NVD ranges, CISA KEV, EPSS)", "linux": "dpkg/rpm package list (with source packages) matched by the app against the signed offline bundle (OSV: Ubuntu, Debian, RHEL, AlmaLinux, Rocky)", "macos": "app bundle versions (/Applications, ~/Applications) matched by the app against the signed offline bundle (NVD ranges, CISA KEV, EPSS)"}, "gdpr.auto_updates": {"windows": "WindowsUpdate\\AU policy (NoAutoUpdate, AUOptions), wuauserv start type", "linux": "apt-config Unattended-Upgrade / dnf-automatic timer", "macos": "com.apple.SoftwareUpdate AutomaticCheck/Download/Install keys"}, "gdpr.updates_recent": {"windows": "Windows Update history (COM) or Get-HotFix", "linux": "/var/log/apt/history.log / rpm -qa --last", "macos": "/Library/Receipts/InstallHistory.plist (softwareupdated)"}, "gdpr.os_supported": {"windows": "Win32_OperatingSystem BuildNumber vs WINDOWS_MIN_BUILD", "linux": "/etc/os-release VERSION_ID vs baseline minimum", "macos": "sw_vers -productVersion vs MACOS_MIN_MAJOR"}, "gdpr.security_logging": {"windows": "auditpol /backup (Logon, User Account Management) + legacy audit policy", "linux": "systemctl is-active auditd, journal persistence", "macos": "logd running (unified logging)"}, "gdpr.time_sync": {"windows": "W32Time Parameters Type + service start type", "linux": "timedatectl NTP / chronyd / ntpd", "macos": "systemsetup -getusingnetworktime (needs root)"}, "gdpr.backup_configured": {"windows": "OneDrive KFM policy, File History config, backup agent services", "linux": "Timeshift config, Deja Dup (gsettings), restic/borg timers", "macos": "tmutil destinationinfo, backup agent processes"}, "gdpr.backup_recent": {"windows": "not readable for most tools (Pending)", "linux": "Timeshift snapshot names, Deja Dup last-backup", "macos": "tmutil latestbackup"}, "gdpr.removable_encryption": {"windows": "FVE RDVDenyWriteAccess (BitLocker To Go) or USB write denied", "linux": "USB write denied", "macos": "USB write denied"}, "gdpr.guest_account": {"windows": "Get-LocalUser (SID -501): Enabled", "linux": "LightDM allow-guest, 'guest' account shell", "macos": "com.apple.loginwindow GuestEnabled, SMB AllowGuestAccess"}, "gdpr.remote_access": {"windows": "fDenyTSConnections (RDP), sshd/WinRM/TeamViewer/AnyDesk/chromoting services, non-admin SMB shares", "linux": "ssh/xrdp/vnc/samba/teamviewer/anydesk/chrome-remote-desktop", "macos": "launchctl print-disabled (sshd, screensharing, smbd, chromoting), ARDAgent/TeamViewer/AnyDesk"}, "gdpr.telemetry": {"windows": "DataCollection AllowTelemetry (policy / Settings)", "linux": "popularity-contest, whoopsie", "macos": "DiagnosticMessagesHistory AutoSubmit, ThirdPartyDataSubmit"}, "gdpr.personal_data_discovery": {"windows": "planned opt-in scan", "linux": "planned opt-in scan", "macos": "planned opt-in scan"}, "aiact.inventory": {"windows": "uninstall registry + Store apps (AI apps), port 11434, model folders, Claude Code CLI", "linux": "AI CLIs, snaps, flatpaks, /opt apps, port 11434, model folders", "macos": "/Applications AI apps, AI CLIs, port 11434, model folders"}, "aiact.unapproved": {"windows": "AI inventory vs APPROVED_AI_TOOLS", "linux": "AI inventory vs APPROVED_AI_TOOLS", "macos": "AI inventory vs APPROVED_AI_TOOLS"}, "aiact.risk_classification": {"windows": "AI inventory, classified by the model", "linux": "AI inventory, classified by the model", "macos": "AI inventory, classified by the model"}, "aiact.os_ai_features": {"windows": "WindowsAI policies (DisableAIDataAnalysis, AllowRecallEnablement), Recall optional feature", "linux": "none built in (NotApplicable)", "macos": "managed com.apple.applicationaccess allowExternalIntelligenceIntegrations (Apple silicon)"}, "aiact.log_retention": {"windows": "depends on AI classification", "linux": "depends on AI classification", "macos": "depends on AI classification"}, } ORG_SOURCE = "organisational.conf (answered once by the organisation)" # Phones: what the browser detects; everything else comes from catalog/mobile_questions.json (asked, self-reported). PHONE_DETECTED = { "gdpr.os_supported": "detected: OS version (Safari version on iOS 26+, client hints on Android), confirmed by the user", "vuln.known_vulnerabilities": "detected: iOS version matched against NVD iOS/iPadOS records in the signed phone bundle", "encryption.enabled": {"ios": "derived: on when a passcode is set (iOS data protection)", "android": "detected: Android 10+ encrypts by default"}, "screen_lock.enabled": "detected: WebAuthn platform authenticator available; otherwise asked", } PHONE_AI = "asked: AI apps installed (checklist); classified by the auditor model" def phone_source(check_id, os_family, questions): det = PHONE_DETECTED.get(check_id) if isinstance(det, dict): det = det.get(os_family) if check_id == "vuln.pending_updates" and os_family == "ios": return "detected: iOS version vs newest fixed release in the signed phone bundle" if det and check_id != "screen_lock.enabled": return det spec = questions["checks"].get(check_id, {}).get(os_family) if spec: return (det + "; " if det else "") + f"asked: {spec['where']}" if check_id.startswith("aiact."): return PHONE_AI return None def main(): with open(os.path.join(ROOT, "catalog", "checks.json"), encoding="utf-8") as handle: catalog = json.load(handle) with open(os.path.join(ROOT, "catalog", "mobile_questions.json"), encoding="utf-8") as handle: questions = json.load(handle) titles = catalog["references"] lines = [ "# Audited controls and data sources", "", f"Catalog version {catalog['catalog_version']} ยท {len(catalog['checks'])} checks. Generated by `tools/build_controls_doc.py` โ€” do not edit by hand.", "", "All sources are read-only. Internet is only used by *Pending security updates* on Windows and macOS, and by the app to refresh the vulnerability bundle.", "Phones are checked in the browser: a web page cannot read a phone's settings, so results are either detected by the browser or answered by the user (self-reported), and labelled as such.", "", ] for section in catalog["sections"]: checks = [c for c in catalog["checks"] if c["section"] == section["id"]] lines += [f"## {section['title']} ({len(checks)})", "", "| Check | Applies to | References | Rule | Windows source | Linux source | macOS source | iPhone source | Android source |", "|---|---|---|---|---|---|---|---|---|"] for c in checks: refs = [f"ISO {r}" for r in c["controls"]["iso27001"]] + [f"GDPR {r}" for r in c["controls"]["gdpr"]] + [f"AI Act {r}" for r in c["controls"]["ai_act"]] src = SOURCES.get(c["id"], {}) cells = [] for os_family in ("windows", "linux", "macos", "ios", "android"): if os_family not in c["os"]: cells.append("โ€”") elif section["id"] == "org": cells.append(ORG_SOURCE if os_family not in ("ios", "android") else ORG_SOURCE + "; Pending in a phone check unless passed in the link") elif os_family in ("ios", "android"): cells.append(phone_source(c["id"], os_family, questions) or "**missing**") else: cells.append(src.get(os_family, "**missing**")) names = c.get("names", {}) others = sorted(set(names.values()) - {c["name"]}) name = c["name"] + (" / " + " / ".join(others) if others else "") lines.append(f"| {name} | {', '.join(c['os'])} | {'; '.join(refs) or 'โ€”'} | {c['rule']} | " + " | ".join(cells) + " |") lines.append("") lines += ["## Reference titles", ""] for key, label in (("iso27001", "ISO/IEC 27001:2022 Annex A"), ("gdpr", "GDPR"), ("ai_act", "EU AI Act")): lines.append(f"**{label}:** " + "; ".join(f"{k} {v}" for k, v in titles[key].items())) lines.append("") os.makedirs(os.path.join(ROOT, "docs"), exist_ok=True) out = os.path.join(ROOT, "docs", "CONTROLS.md") with open(out, "w", encoding="utf-8") as handle: handle.write("\n".join(lines)) missing = [f"{c['id']} ({o})" for c in catalog["checks"] if c["section"] != "org" for o in c["os"] if (o in ("ios", "android") and not phone_source(c["id"], o, questions)) or (o not in ("ios", "android") and o not in SOURCES.get(c["id"], {}))] print(f"Wrote {out}; checks without a documented source: {missing or 'none'}") if __name__ == "__main__": main()