/**
 * Malware detection check parser.
 * Parses chkrootkit/rkhunter installation, SUID files in /tmp and /dev,
 * world-writable files in /root, and rkhunter scan history into 6 security checks.
 */
import { CHECK_IDS } from "../checkIds.js";
const MALWARE_CHECKS = [
    {
        id: CHECK_IDS.MALWARE.MALWARE_CHKROOTKIT_INSTALLED,
        name: "chkrootkit Installed",
        severity: "warning",
        check: (output) => {
            const installed = /^ii\s+chkrootkit\b/m.test(output);
            return {
                passed: installed,
                currentValue: installed ? "chkrootkit is installed" : "chkrootkit not installed",
            };
        },
        expectedValue: "chkrootkit installed for rootkit detection",
        fixCommand: "apt install chkrootkit -y",
        safeToAutoFix: "SAFE",
        explain: "chkrootkit scans for known rootkits and suspicious system modifications that could indicate a system compromise.",
    },
    {
        id: CHECK_IDS.MALWARE.MALWARE_RKHUNTER_INSTALLED,
        name: "rkhunter Installed",
        severity: "warning",
        check: (output) => {
            const installed = /^ii\s+rkhunter\b/m.test(output);
            return {
                passed: installed,
                currentValue: installed ? "rkhunter is installed" : "rkhunter not installed",
            };
        },
        expectedValue: "rkhunter installed for rootkit detection",
        fixCommand: "apt install rkhunter -y && rkhunter --update",
        safeToAutoFix: "SAFE",
        explain: "rkhunter scans for known rootkits, backdoors, and local exploits by checking file signatures, permissions, and known bad binaries.",
    },
    {
        id: CHECK_IDS.MALWARE.MALWARE_NO_SUID_IN_TMP,
        name: "No SUID Files in /tmp",
        severity: "critical",
        check: (output) => {
            // Output is "NONE" if no SUID files found, or file paths if found
            const isNone = /^NONE$/m.test(output);
            return {
                passed: isNone,
                currentValue: isNone ? "No SUID files in /tmp" : "SUID files found in /tmp (possible rootkit indicator)",
            };
        },
        expectedValue: "No SUID files in /tmp (find /tmp -perm -4000 returns empty)",
        fixCommand: "find /tmp -perm -4000 -type f -exec chmod -s {} \\; # Remove SUID bit and investigate each file",
        safeToAutoFix: "SAFE",
        explain: "SUID files in /tmp are a strong indicator of rootkit activity or an active exploit. /tmp is world-writable and SUID binaries there can provide instant privilege escalation.",
    },
    {
        id: CHECK_IDS.MALWARE.MALWARE_NO_SUID_IN_DEV,
        name: "No Unexpected SUID Files in /dev",
        severity: "warning",
        check: (output) => {
            // Find SUID check for /dev — legitimate SUID in /dev is unusual
            // Output: NONE means clean, file paths mean suspicious
            // The NONE output is on its own line; any non-NONE line after /tmp section is /dev finding
            // Since all checks share one output blob, we look for the second NONE occurrence
            const lines = output.split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
            const noneCount = lines.filter((l) => l === "NONE").length;
            // Check if any line looks like a /dev path (not /tmp and not NONE)
            const devSuid = lines.some((l) => l.startsWith("/dev/") && !l.startsWith("/dev/null"));
            return {
                passed: !devSuid && noneCount >= 2,
                currentValue: devSuid ? "Unexpected SUID files found in /dev" : "No unexpected SUID files in /dev",
            };
        },
        expectedValue: "No unexpected SUID files in /dev",
        fixCommand: "find /dev -perm -4000 -type f -exec ls -la {} \\; # Investigate and remove SUID bit if not required",
        safeToAutoFix: "SAFE",
        explain: "Unexpected SUID files in /dev may indicate rootkit activity. While some device files may have SUID legitimately, file-type SUID in /dev is suspicious.",
    },
    {
        id: CHECK_IDS.MALWARE.MALWARE_RKHUNTER_RECENT_SCAN,
        name: "rkhunter Recently Scanned",
        severity: "warning",
        check: (output) => {
            const hasRecentScan = /system checks summary/i.test(output) && !/NO_SCAN/.test(output);
            return {
                passed: hasRecentScan,
                currentValue: hasRecentScan ? "rkhunter has run a recent system scan" : "No recent rkhunter scan found",
            };
        },
        expectedValue: "rkhunter has recent scan results in /var/log/rkhunter.log",
        fixCommand: "rkhunter --update && rkhunter --check --sk # Run rkhunter scan and schedule via cron",
        safeToAutoFix: "SAFE",
        explain: "rkhunter must be regularly executed to provide ongoing rootkit detection. An unscanned system may have undetected rootkits installed.",
    },
    {
        id: CHECK_IDS.MALWARE.MALWARE_NO_ROOT_WRITABLE,
        name: "No World-Writable Files in /root",
        severity: "warning",
        check: (output) => {
            const isNone = /^NONE$/m.test(output);
            // Check for any file path under /root
            const hasRootWritable = /^\/root\//m.test(output);
            return {
                passed: isNone && !hasRootWritable,
                currentValue: hasRootWritable ? "World-writable files found in /root" : "No world-writable files in /root",
            };
        },
        expectedValue: "No world-writable files exist under /root",
        fixCommand: "find /root -perm -o+w -type f -exec chmod o-w {} \\; # Remove world-write permission from /root files",
        safeToAutoFix: "SAFE",
        explain: "World-writable files in the root home directory allow any user to modify root's configuration files, potentially enabling privilege escalation.",
    },
    {
        id: CHECK_IDS.MALWARE.MALWARE_NO_HIDDEN_PROCS,
        name: "No Hidden Files in /tmp or /dev/shm",
        severity: "warning",
        check: (output) => {
            // find /tmp /dev/shm -name ".*" -type f output
            // Output is "NONE" if clean, or file paths if hidden files found
            const noneCount = (output.match(/^NONE$/gm) ?? []).length;
            const hiddenFiles = output.split("\n").filter((l) => {
                const trimmed = l.trim();
                return trimmed.startsWith("/tmp/.") || trimmed.startsWith("/dev/shm/.");
            });
            const passed = noneCount >= 1 || hiddenFiles.length === 0;
            return {
                passed,
                currentValue: hiddenFiles.length > 0
                    ? `Hidden files found: ${hiddenFiles.slice(0, 3).join(", ")}`
                    : "No hidden files in /tmp or /dev/shm",
            };
        },
        expectedValue: "No hidden files (.*) in /tmp or /dev/shm",
        fixCommand: "find /tmp /dev/shm -name '.*' -type f -exec ls -la {} \\; # Investigate and remove suspicious hidden files",
        safeToAutoFix: "SAFE",
        explain: "Hidden files in /tmp and /dev/shm are a common indicator of malware persistence or crypto-mining payloads.",
    },
    {
        id: CHECK_IDS.MALWARE.MALWARE_NO_HIGH_CPU,
        name: "No Rogue High-CPU Processes",
        severity: "warning",
        check: (output) => {
            // ps aux | awk '$3>50' output
            // Output "NONE" if no high-CPU processes
            const noneMatches = (output.match(/^NONE$/gm) ?? []).length;
            const highCpuLines = output.split("\n").filter((l) => {
                const trimmed = l.trim();
                if (!trimmed || trimmed === "NONE")
                    return false;
                // ps aux format: USER PID %CPU ...
                const parts = trimmed.split(/\s+/);
                if (parts.length < 3)
                    return false;
                const cpu = parseFloat(parts[2]);
                return !isNaN(cpu) && cpu > 50;
            });
            const passed = noneMatches >= 1 || highCpuLines.length === 0;
            return {
                passed,
                currentValue: highCpuLines.length > 0
                    ? `High-CPU process(es) detected: ${highCpuLines.length} process(es) >50% CPU`
                    : "No high-CPU processes detected",
            };
        },
        expectedValue: "No processes consuming more than 50% CPU",
        fixCommand: "# Review: ps aux --sort=-%cpu | head -5 — investigate rogue processes",
        safeToAutoFix: "GUARDED",
        explain: "Processes consuming excessive CPU may indicate crypto-mining malware or runaway exploit code.",
    },
    {
        id: CHECK_IDS.MALWARE.MALWARE_RKHUNTER_UPDATED,
        name: "rkhunter Database Current",
        severity: "info",
        check: (output) => {
            // rkhunter.log output — check for system checks summary
            // If rkhunter not installed, pass as info
            const notInstalled = /NOT_INSTALLED/.test(output);
            if (notInstalled) {
                return { passed: false, currentValue: "rkhunter not installed" };
            }
            const hasScan = /system checks summary/i.test(output) && !/NO_SCAN/.test(output);
            return {
                passed: hasScan,
                currentValue: hasScan ? "rkhunter has recent scan results" : "No recent rkhunter scan found",
            };
        },
        expectedValue: "rkhunter installed and recently scanned",
        fixCommand: "rkhunter --update && rkhunter --check --sk # Update database and run scan",
        safeToAutoFix: "SAFE",
        explain: "An outdated rkhunter database misses recently discovered rootkits and system modifications.",
    },
    {
        id: CHECK_IDS.MALWARE.MALWARE_NO_WORLD_WRITABLE_DEV,
        name: "No SUID Files in /dev",
        severity: "warning",
        check: (output) => {
            // find /dev -perm -4000 output — check for SUID files in /dev
            const noneMatches = (output.match(/^NONE$/gm) ?? []).length;
            const devSuidLines = output.split("\n").filter((l) => {
                const trimmed = l.trim();
                return trimmed.startsWith("/dev/") && !trimmed.startsWith("/dev/null");
            });
            const passed = noneMatches >= 2 || devSuidLines.length === 0;
            return {
                passed,
                currentValue: devSuidLines.length > 0
                    ? `Unexpected SUID files in /dev: ${devSuidLines.slice(0, 3).join(", ")}`
                    : "No unexpected SUID files in /dev",
            };
        },
        expectedValue: "No unexpected SUID files in /dev",
        fixCommand: "find /dev -perm -4000 -type f -exec ls -la {} \\; # Investigate and remove SUID bit if not required",
        safeToAutoFix: "SAFE",
        explain: "SUID binaries or world-writable files in /dev can be used for privilege escalation and device-level attacks.",
    },
    {
        id: CHECK_IDS.MALWARE.MALWARE_NO_HIDDEN_IN_TMP,
        name: "No Hidden Files in Temporary Directories",
        severity: "warning",
        check: (output) => {
            // find /tmp /var/tmp -name '.*' -type f | wc -l — standalone number
            const lines = output.split("\n");
            let hiddenCount = null;
            for (const line of lines) {
                const trimmed = line.trim();
                if (/^\d+$/.test(trimmed)) {
                    const val = parseInt(trimmed, 10);
                    // Hidden file count is typically 0-20
                    if (val >= 0 && val < 10000) {
                        hiddenCount = val;
                        break;
                    }
                }
            }
            if (hiddenCount === null) {
                return { passed: false, currentValue: "Hidden file count not determinable" };
            }
            const passed = hiddenCount <= 3;
            return {
                passed,
                currentValue: passed
                    ? `${hiddenCount} hidden file(s) in /tmp or /var/tmp (acceptable)`
                    : `${hiddenCount} hidden file(s) in /tmp or /var/tmp (review recommended)`,
            };
        },
        expectedValue: "3 or fewer hidden files in /tmp and /var/tmp",
        fixCommand: "find /tmp /var/tmp -name '.*' -type f -ls -- review and remove suspicious hidden files",
        safeToAutoFix: "SAFE",
        explain: "Hidden files in temporary directories are a common indicator of compromise — attackers use dotfiles to evade casual directory listing.",
    },
];
export const parseMalwareChecks = (sectionOutput, _platform) => {
    const isNA = !sectionOutput ||
        sectionOutput.trim() === "N/A" ||
        sectionOutput.trim() === "";
    const output = isNA ? "" : sectionOutput;
    return MALWARE_CHECKS.map((def) => {
        if (isNA) {
            return {
                id: def.id,
                category: "Malware",
                name: def.name,
                severity: def.severity,
                passed: false,
                currentValue: "Unable to determine",
                expectedValue: def.expectedValue,
                fixCommand: def.fixCommand,
                safeToAutoFix: def.safeToAutoFix,
                explain: def.explain,
            };
        }
        const { passed, currentValue } = def.check(output);
        return {
            id: def.id,
            category: "Malware",
            name: def.name,
            severity: def.severity,
            passed,
            currentValue,
            expectedValue: def.expectedValue,
            fixCommand: def.fixCommand,
            safeToAutoFix: def.safeToAutoFix,
            explain: def.explain,
        };
    });
};
//# sourceMappingURL=malware.js.map