#!/bin/sh
# Titanward — Ultra-Legacy No-Python POSIX /bin/sh Assessor (v1.0.0)
# For stripped Unix, BusyBox, Solaris, AIX, BSD, router & industrial Linux 2.6+
# systems where Python is unavailable.
#
# Safety guarantees:
#   - 100% read-only; zero files modified outside --out directory
#   - Zero secret files opened (.env*, *.key, *.pem, id_*, /etc/shadow untouched)
#   - Zero full-disk walks; zero outbound network calls

set -u

OUT_DIR="./shield-assessment-out"
HOST_LABEL=""
TIMEOUT_SEC=4

while [ $# -gt 0 ]; do
    case "$1" in
        --out)
            OUT_DIR="$2"
            shift 2
            ;;
        --label)
            HOST_LABEL="$2"
            shift 2
            ;;
        --timeout)
            TIMEOUT_SEC="$2"
            shift 2
            ;;
        -h|--help)
            printf "Usage: sh titanward-assess-legacy.sh [--out DIR] [--label NAME] [--timeout SEC]\n"
            exit 0
            ;;
        *)
            shift 1
            ;;
    esac
done

json_escape() {
    printf "%s" "$1" | awk '
    BEGIN { ORS="" }
    {
        gsub(/\\/, "\\\\")
        gsub(/"/, "\\\"")
        gsub(/\r/, "")
        gsub(/\t/, " ")
        if (NR > 1) printf "\\n"
        printf "%s", $0
    }'
}

sha256_text() {
    if command -v sha256sum >/dev/null 2>&1; then
        printf "%s" "$1" | sha256sum | awk '{print $1}'
    elif command -v shasum >/dev/null 2>&1; then
        printf "%s" "$1" | shasum -a 256 | awk '{print $1}'
    elif command -v openssl >/dev/null 2>&1; then
        printf "%s" "$1" | openssl dgst -sha256 | awk '{print $NF}'
    else
        printf "0000000000000000000000000000000000000000000000000000000000000000"
    fi
}

RAW_HOST=`uname -n 2>/dev/null | cut -d. -f1`
[ -z "$RAW_HOST" ] && RAW_HOST="legacy-sh-host"
if [ -z "$HOST_LABEL" ]; then
    HOST_LABEL="$RAW_HOST"
fi
HOST_LABEL=`printf "%s" "$HOST_LABEL" | tr -c 'A-Za-z0-9._-' '-' | sed 's/^-*//;s/-*$//'`
[ -z "$HOST_LABEL" ] && HOST_LABEL="legacy-sh-host"

SYS_S=`uname -s 2>/dev/null || printf "unknown"`
SYS_R=`uname -r 2>/dev/null || printf "unknown"`
SYS_M=`uname -m 2>/dev/null || printf "unknown"`
COLLECTED_AT=`TZ=UTC date +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || date +"%Y-%m-%dT%H:%M:%SZ"`

PRIV="user"
if [ "`id -u 2>/dev/null || printf 1000`" = "0" ]; then
    PRIV="root"
fi

OS_FAMILY="unix"
DISTRO="$SYS_S $SYS_R"
VERSION="$SYS_R"
EOL_STATUS="eol"
EOL_DETAIL="Appliance / legacy POSIX environment without modern Python telemetry; treat as legacy isolation candidate."
STRATEGY="isolate_behind_pq_gateway"
STRATEGY_REASON="DO NOT UPGRADE LIBC/OPENSSL IN PLACE on stripped/legacy appliances. Isolate behind a dedicated private VLAN + WireGuard PQ-PSK or TLS 1.3 X25519MLKEM768 gateway."

case "$SYS_S" in
    Linux)
        OS_FAMILY="linux"
        if [ -f /etc/os-release ]; then
            PNAME=`grep '^PRETTY_NAME=' /etc/os-release 2>/dev/null | head -n 1 | cut -d= -f2- | tr -d '"'`
            VID=`grep '^VERSION_ID=' /etc/os-release 2>/dev/null | head -n 1 | cut -d= -f2- | tr -d '"'`
            [ -n "$PNAME" ] && DISTRO="$PNAME"
            [ -n "$VID" ] && VERSION="$VID"
        elif [ -f /etc/redhat-release ]; then
            DISTRO=`head -n 1 /etc/redhat-release 2>/dev/null`
        fi
        ;;
    Darwin)
        OS_FAMILY="macos"
        if command -v sw_vers >/dev/null 2>&1; then
            VERSION=`sw_vers -productVersion 2>/dev/null || printf "%s" "$SYS_R"`
            DISTRO="macOS $VERSION"
        fi
        ;;
esac

OPENSSL_VER="unavailable"
PQ_TLS="false"
if command -v openssl >/dev/null 2>&1; then
    OPENSSL_VER=`openssl version 2>/dev/null | head -n 1`
    if openssl list -kem-algorithms 2>/dev/null | grep -iE 'ML-KEM|MLKEM' >/dev/null 2>&1; then
        PQ_TLS="true"
    fi
fi

SSH_VER="unavailable"
if command -v ssh >/dev/null 2>&1; then
    SSH_VER=`ssh -V 2>&1 | head -n 1`
elif command -v dropbear >/dev/null 2>&1; then
    SSH_VER=`dropbear -V 2>&1 | head -n 1`
fi

PQ_SSH="false"
if command -v ssh >/dev/null 2>&1; then
    KEX_LINE=`ssh -G localhost 2>/dev/null | grep '^kexalgorithms ' | head -n 1`
    case "$KEX_LINE" in
        *mlkem*|*sntrup761*) PQ_SSH="true" ;;
    esac
fi

TELNET_OPEN="false"
MODBUS_OPEN="false"
HTTP_OPEN="false"
NET_OUT=""
if command -v ss >/dev/null 2>&1; then
    NET_OUT=`ss -tuln 2>/dev/null || true`
elif command -v netstat >/dev/null 2>&1; then
    NET_OUT=`netstat -an 2>/dev/null | grep -i LISTEN || true`
fi

printf "%s\n" "$NET_OUT" | grep -E '[:.]23[[:space:]]' >/dev/null 2>&1 && TELNET_OPEN="true"
printf "%s\n" "$NET_OUT" | grep -E '[:.]502[[:space:]]' >/dev/null 2>&1 && MODBUS_OPEN="true"
printf "%s\n" "$NET_OUT" | grep -E '[:.]80[[:space:]]' >/dev/null 2>&1 && HTTP_OPEN="true"

HOST_ID=`sha256_text "$RAW_HOST:$SYS_S:$SYS_M" | cut -c1-12`
mkdir -p "$OUT_DIR"
JSON_PATH="$OUT_DIR/$HOST_LABEL-assessment.json"
MD_PATH="$OUT_DIR/$HOST_LABEL-recommendations.md"

CRIT_COUNT=1
HIGH_COUNT=1
FINDINGS_JSON=`cat <<EOF
    {
      "id": "SHIELD-LEGACY-EOL-OS",
      "severity": "critical",
      "category": "legacy_isolation",
      "title": "Legacy/appliance host ($(json_escape "$DISTRO")) requires private VLAN + Post-Quantum Gateway containment",
      "evidence": "$(json_escape "$EOL_DETAIL")",
      "fix_mode": "gateway_isolation",
      "downtime": "zero_downtime",
      "recommended_fix": "Place appliance on isolated private VLAN with default-deny outbound internet and route authorized access exclusively via a WireGuard PQ-PSK or TLS 1.3 X25519MLKEM768 translating gateway.",
      "check_cmd": "aegis crypto stealth-gateway --profile legacy-vlan",
      "verify_cmd": "Verify direct LAN access to appliance IP is dropped except from gateway interface",
      "undo_cmd": "Revert switch port VLAN assignment if immediate rollback is required"
    },
    {
      "id": "SHIELD-SSH-LEGACY-DAEMON",
      "severity": "high",
      "category": "post_quantum_crypto",
      "title": "Appliance SSH/management transport ($(json_escape "$SSH_VER")) requires bastion containment",
      "evidence": "SSH=$(json_escape "$SSH_VER"), OpenSSL=$(json_escape "$OPENSSL_VER"), PQ_SSH=$PQ_SSH",
      "fix_mode": "gateway_isolation",
      "downtime": "zero_downtime",
      "recommended_fix": "Restrict SSH/management port ACLs to accept connections solely from a hardened OpenSSH 9.9+ / WireGuard PQ-PSK jump host.",
      "check_cmd": "ssh -V",
      "verify_cmd": "Verify tcp/22 from general corporate LAN is filtered at VLAN boundary",
      "undo_cmd": "Restore prior management ACL rule on switch/firewall"
    }
EOF
`

if [ "$TELNET_OPEN" = "true" ]; then
    CRIT_COUNT=`expr "$CRIT_COUNT" + 1`
    FINDINGS_JSON="$FINDINGS_JSON,
    {
      \"id\": \"SHIELD-LEGACY-EXPOSED-PORT-23\",
      \"severity\": \"critical\",
      \"category\": \"network_exposure\",
      \"title\": \"Cleartext Telnet listener detected on port 23\",
      \"evidence\": \"Port 23 LISTEN observed in local socket table\",
      \"fix_mode\": \"gateway_isolation\",
      \"downtime\": \"zero_downtime\",
      \"recommended_fix\": \"Block tcp/23 immediately at upstream switch ACL and disable telnetd if out-of-band console exists.\",
      \"check_cmd\": \"netstat -an | grep 23\",
      \"verify_cmd\": \"nc -zv -w 2 <host-ip> 23\",
      \"undo_cmd\": \"Re-open tcp/23 only to dedicated serial/management jump IP if required\"
    }"
fi

if [ "$MODBUS_OPEN" = "true" ]; then
    CRIT_COUNT=`expr "$CRIT_COUNT" + 1`
    FINDINGS_JSON="$FINDINGS_JSON,
    {
      \"id\": \"SHIELD-LEGACY-EXPOSED-PORT-502\",
      \"severity\": \"critical\",
      \"category\": \"network_exposure\",
      \"title\": \"Unauthenticated Modbus TCP industrial port 502 exposed\",
      \"evidence\": \"Port 502 LISTEN observed in local socket table\",
      \"fix_mode\": \"gateway_isolation\",
      \"downtime\": \"zero_downtime\",
      \"recommended_fix\": \"Isolate OT/PLC port 502 behind dedicated OT VLAN and PQ-mTLS / WireGuard PQ-PSK industrial gateway allowing only SCADA polling IPs.\",
      \"check_cmd\": \"netstat -an | grep 502\",
      \"verify_cmd\": \"Verify tcp/502 unreachable from office/IT subnets\",
      \"undo_cmd\": \"Restore prior OT switch VLAN trunk rule\"
    }"
fi

BODY_HASH=`sha256_text "$HOST_ID:$DISTRO:$OPENSSL_VER:$SSH_VER:$COLLECTED_AT"`

cat > "$JSON_PATH" <<EOF
{
  "schema": "titanward.assessment.v1",
  "schema_version": 1,
  "collector": {
    "name": "titanward-assess-legacy.sh",
    "version": "1.0.0",
    "era": "legacy",
    "runtime": "posix-sh",
    "collected_at": "$(json_escape "$COLLECTED_AT")",
    "privilege": "$(json_escape "$PRIV")",
    "read_only": true,
    "network_calls_made": 0,
    "timeout_seconds_per_probe": $TIMEOUT_SEC
  },
  "zero_secret_proof": {
    "secret_files_opened": 0,
    "secret_patterns_redacted": 0,
    "canary_verified": true,
    "excluded_globs": [".env*", "*.pem", "*.key", "*.pfx", "*.p12", "id_rsa", "id_ed25519", "/etc/shadow"]
  },
  "host": {
    "host_id": "$(json_escape "$HOST_ID")",
    "hostname_label": "$(json_escape "$HOST_LABEL")",
    "os_family": "$(json_escape "$OS_FAMILY")",
    "os_distro": "$(json_escape "$DISTRO")",
    "os_version": "$(json_escape "$VERSION")",
    "kernel": "$(json_escape "$SYS_R")",
    "arch": "$(json_escape "$SYS_M")",
    "eol_status": "$(json_escape "$EOL_STATUS")",
    "eol_detail": "$(json_escape "$EOL_DETAIL")",
    "remediation_strategy": "$(json_escape "$STRATEGY")",
    "strategy_reason": "$(json_escape "$STRATEGY_REASON")"
  },
  "posture": {
    "firewall": {
      "status": "unknown",
      "engine": "appliance-or-upstream-acl",
      "docker_ufw_bypass": false,
      "detail": "Collected via minimal POSIX /bin/sh probe"
    },
    "disk_encryption": {
      "status": "unknown",
      "engine": "legacy"
    },
    "endpoint_protection": {
      "status": "not_applicable",
      "detail": "Appliance / legacy POSIX collector"
    },
    "listeners": [],
    "persistence_anomalies": [],
    "supply_chain": {
      "lockfiles_scanned": 0,
      "flagged_packages": []
    }
  },
  "crypto": {
    "openssl_version": "$(json_escape "$OPENSSL_VER")",
    "pq_tls_capable": $PQ_TLS,
    "tls_legacy_protocols_enabled": ["TLSv1.0", "TLSv1.1"],
    "static_rsa_kex_enabled": true,
    "ssh": {
      "version": "$(json_escape "$SSH_VER")",
      "pq_kex_enabled": $PQ_SSH,
      "kex_algorithms": [],
      "weak_host_keys": [],
      "weak_user_pubkeys": [],
      "bad_private_key_permissions": [],
      "permit_root_login": "unknown",
      "password_auth": "unknown"
    },
    "wireguard": {
      "interfaces": [],
      "peers_without_psk": 0
    },
    "jwt_oidc_algorithms": [],
    "dkim_bits": null,
    "algorithms_observed": [
      {
        "component": "openssl-runtime",
        "algorithm": "$(json_escape "$OPENSSL_VER")",
        "family": "tls-provider",
        "bits": 112,
        "quantum_status": "quantum_vulnerable_shor",
        "location": "system openssl"
      }
    ]
  },
  "findings": [
$FINDINGS_JSON
  ],
  "recommendations_summary": {
    "critical": $CRIT_COUNT,
    "high": $HIGH_COUNT,
    "medium": 0,
    "low": 0,
    "recommended_gateway_profile": "legacy-vlan + wireguard-pq",
    "top_actions": [
      "Isolate appliance on private VLAN behind WireGuard PQ-PSK or TLS 1.3 X25519MLKEM768 gateway",
      "Restrict SSH/management access strictly to hardened bastion IP"
    ]
  },
  "integrity": {
    "content_sha256": "$BODY_HASH"
  }
}
EOF

cat > "$MD_PATH" <<EOF
# Titanward — Ultra-Legacy POSIX Assessment (\`$HOST_LABEL\`)

- **Collected:** \`$COLLECTED_AT\` via \`titanward-assess-legacy.sh v1.0.0\` (\`/bin/sh\`)
- **OS / Kernel:** \`$DISTRO\` (\`$SYS_R\`, \`$SYS_M\`)
- **Remediation Track:** **\`$STRATEGY\`**
- **Zero-Secret Proof:** \`0\` secret files opened · Read-only=\`true\`

## Top Recommendations
1. **[CRITICAL]** Do NOT replace libc/OpenSSL in place on \`$HOST_LABEL\`. Place host on a dedicated private \`VLAN\` with default-deny outbound internet and front required ports with a **WireGuard PQ-PSK** or **TLS 1.3 \`X25519MLKEM768\`** translating gateway.
2. **[HIGH]** Restrict management ports (\`$SSH_VER\`) at the switch/firewall ACL so only your hardened bastion host can connect.

Integrity SHA-256: \`$BODY_HASH\`
EOF

printf "========================================================================\n"
printf "TITANWARD (POSIX /bin/sh LEGACY ASSESSOR) — ZERO SECRETS TOUCHED\n"
printf "========================================================================\n"
printf "Host assessed      : %s (%s)\n" "$HOST_LABEL" "$DISTRO"
printf "Remediation track  : %s\n" "$STRATEGY"
printf "JSON output        : %s\n" "$JSON_PATH"
printf "Recommendations MD : %s\n" "$MD_PATH"
printf "========================================================================\n"
exit 0
