#!/bin/bash
# ObfusGated VPN Kill Switch Boot Guard

set +e

CHAIN_NAME="OBFUSGATED_KS"
CHAIN_NAME6="OBFUSGATED_KS6"
PERSISTENT_DIR="${SNAP_COMMON:-/var/lib/obfusgated-vpn}"
PERSISTENT_FILE="$PERSISTENT_DIR/killswitch_persistent.json"
FWMARK="0x4F424653"
ALLOW_LAN=false

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] KILLSWITCH-BOOT: $1" >&2
    logger -t "obfusgated-killswitch" "$1"
}

find_iptables() {
    for cmd in iptables /sbin/iptables /usr/sbin/iptables; do
        if command -v "$cmd" &>/dev/null; then
            echo "$cmd"
            return 0
        fi
    done
    return 1
}

find_ip6tables() {
    for cmd in ip6tables /sbin/ip6tables /usr/sbin/ip6tables; do
        if command -v "$cmd" &>/dev/null; then
            echo "$cmd"
            return 0
        fi
    done
    return 1
}

# Wait for iptables to become available (retry up to 10 seconds)
wait_for_iptables() {
    local max_attempts=20
    local attempt=0
    local iptables
    
    log "Waiting for iptables to become available..."
    while [ $attempt -lt $max_attempts ]; do
        iptables=$(find_iptables)
        if [ $? -eq 0 ] && [ -n "$iptables" ]; then
            log "iptables found: $iptables"
            echo "$iptables"
            return 0
        fi
        attempt=$((attempt + 1))
        sleep 0.5
    done
    
    log "WARNING: iptables not found after $max_attempts attempts"
    return 1
}

wait_for_ip6tables() {
    local max_attempts=20
    local attempt=0
    local ip6tables
    
    log "Waiting for ip6tables to become available..."
    while [ $attempt -lt $max_attempts ]; do
        ip6tables=$(find_ip6tables)
        if [ $? -eq 0 ] && [ -n "$ip6tables" ]; then
            log "ip6tables found: $ip6tables"
            echo "$ip6tables"
            return 0
        fi
        attempt=$((attempt + 1))
        sleep 0.5
    done
    
    log "WARNING: ip6tables not found after $max_attempts attempts"
    return 1
}

# Rebuild only our chain and its OUTPUT hook in one table transaction. Never
# flush a live chain using individual commands: that temporarily permits traffic.
restore_blocking_rules() {
    local iptables="$1" family="$2" chain restore rules network hooks line existing=0
    [[ "$family" == 4 || "$family" == 6 ]] || return 1
    restore="${iptables}-restore"
    if ! command -v "$restore" >/dev/null 2>&1; then
        log "ERROR: Matching firewall restore command unavailable: $restore"
        return 1
    fi
    if [[ "$family" == 4 ]]; then chain="$CHAIN_NAME"; else chain="$CHAIN_NAME6"; fi
    # Reinsert at the front, retaining one hook rather than adding one on every
    # restart. A concurrent rule removal makes restore fail without committing.
    # Query the built-in chain: nft-backed iptables can return an error when
    # -C refers to our not-yet-created target chain on the first boot.
    if ! hooks=$("$iptables" -w 5 -S OUTPUT); then
        log "ERROR: Cannot inspect IPv$family firewall hook"
        return 1
    fi
    while IFS= read -r line; do
        if [[ "$line" == "-A OUTPUT -j $chain" ]]; then existing=1; fi
    done <<< "$hooks"
    rules="*filter
:$chain - [0:0]
-A $chain -o lo -j ACCEPT"
    if [[ "$family" == 4 ]]; then
        if [[ "$ALLOW_LAN" == true ]]; then
        for network in 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 169.254.0.0/16; do
            rules+=$'\n'"-A $chain -d $network -j ACCEPT"
        done
        fi
        rules+=$'\n'"-A $chain -m mark --mark $FWMARK -j ACCEPT"
        rules+=$'\n'"-A $chain -p udp --dport 67:68 -j ACCEPT"
    else
        if [[ "$ALLOW_LAN" == true ]]; then
        for network in fc00::/7 fe80::/10 ff02::/16; do
            rules+=$'\n'"-A $chain -d $network -j ACCEPT"
        done
        fi
        rules+=$'\n'"-A $chain -p udp --dport 547 -j ACCEPT"
    fi
    # No ESTABLISHED/RELATED exemption: existing direct flows remain blocked.
    rules+=$'\n'"-A $chain -j DROP"
    if (( existing )); then rules+=$'\n'"-D OUTPUT -j $chain"; fi
    rules+=$'\n'"-I OUTPUT 1 -j $chain"$'\nCOMMIT'
    if ! "$restore" --wait 5 --noflush <<< "$rules"; then
        log "ERROR: IPv$family firewall transaction failed; no sequential fallback"
        return 1
    fi
    log "IPv$family blocking policy transaction committed"
}

apply_blocking_rules() { restore_blocking_rules "$1" 4; }
apply_blocking_rules_v6() { restore_blocking_rules "$1" 6; }

remove_blocking_rules() {
    local iptables="$1"
    
    log "Removing kill switch blocking rules"
    
    # Remove from OUTPUT chain
    $iptables -D OUTPUT -j "$CHAIN_NAME" 2>/dev/null || true
    
    # Flush and delete our chain
    $iptables -F "$CHAIN_NAME" 2>/dev/null || true
    $iptables -X "$CHAIN_NAME" 2>/dev/null || true
    
    log "Kill switch blocking rules removed"
}

remove_blocking_rules_v6() {
    local ip6tables="$1"
    
    log "Removing IPv6 kill switch blocking rules"
    
    $ip6tables -D OUTPUT -j "$CHAIN_NAME6" 2>/dev/null || true
    $ip6tables -F "$CHAIN_NAME6" 2>/dev/null || true
    $ip6tables -X "$CHAIN_NAME6" 2>/dev/null || true
    
    log "IPv6 kill switch blocking rules removed"
}

preference_explicitly_disabled() {
    # Deliberately limited to the existing saved-preference schema. No JSON
    # coercion, duplicate keys, escapes, unknown fields or trailing input.
    local LC_ALL=C text="$1" key value mode='' lan=false seen='|' pattern
    ALLOW_LAN=false
    (( ${#text} > 0 && ${#text} <= 4096 )) || return 1
    [[ "$text" != *$'\v'* && "$text" != *$'\f'* ]] || return 1
    pattern='^[[:space:]]*\{(.*)$'
    [[ "$text" =~ $pattern ]] || return 1
    text="${BASH_REMATCH[1]}"
    while :; do
        pattern='^[[:space:]]*"(persistentMode|allowLan|timestamp)"[[:space:]]*:[[:space:]]*(.*)$'
        [[ "$text" =~ $pattern ]] || return 1
        key="${BASH_REMATCH[1]}"; text="${BASH_REMATCH[2]}"
        [[ "$seen" != *"|$key|"* ]] || return 1
        seen+="$key|"
        if [[ "$key" == timestamp ]]; then
            pattern='^"([^"\\]{0,64})"(.*)$'
            [[ "$text" =~ $pattern ]] || return 1
            value="${BASH_REMATCH[1]}"; text="${BASH_REMATCH[2]}"
            [[ "$value" != *[!\ -~]* ]] || return 1
        else
            pattern='^(true|false)(.*)$'
            [[ "$text" =~ $pattern ]] || return 1
            value="${BASH_REMATCH[1]}"; text="${BASH_REMATCH[2]}"
            [[ "$key" != persistentMode ]] || mode="$value"
            [[ "$key" != allowLan ]] || lan="$value"
        fi
        pattern='^[[:space:]]*\}[[:space:]]*$'
        if [[ "$text" =~ $pattern ]]; then
            [[ -n "$mode" ]] || return 1
            ALLOW_LAN="$lan"
            [[ "$mode" == false ]]; return
        fi
        pattern='^[[:space:]]*,(.*)$'
        [[ "$text" =~ $pattern ]] || return 1
        text="${BASH_REMATCH[1]}"
    done
}

check_persistent_enabled() {
    ALLOW_LAN=false
    # Ensure directory exists first
    if [ ! -d "$PERSISTENT_DIR" ]; then
        if [ -e "$PERSISTENT_DIR" ] || [ -L "$PERSISTENT_DIR" ]; then
            log "Persistent directory is invalid; retaining protection"
            return 0
        fi
        log "Persistent directory does not exist: $PERSISTENT_DIR"
        return 1
    fi
    
    if [ ! -e "$PERSISTENT_FILE" ] && [ ! -L "$PERSISTENT_FILE" ]; then
        log "Persistent file does not exist: $PERSISTENT_FILE"
        return 1
    fi
    
    local LC_ALL=C text='' size=''
    if [[ -f "$PERSISTENT_FILE" && -r "$PERSISTENT_FILE" && ! -L "$PERSISTENT_FILE" ]]; then
        size=$(wc -c < "$PERSISTENT_FILE" 2>/dev/null) || size=''
        if [[ "$size" =~ ^[[:space:]]*[0-9]+[[:space:]]*$ ]] && (( size > 0 && size <= 4096 )); then
            IFS= read -r -N 4097 text < "$PERSISTENT_FILE" || true
            # Bash discards NULs: byte-count agreement also rejects those files.
            if (( ${#text} == size )) && preference_explicitly_disabled "$text"; then
                log "Persistent kill switch explicitly disabled"
                return 1
            fi
        fi
    fi
    log "Persistent preference is enabled or requires reconciliation; retaining protection"
    return 0
}

start() {
    log "Kill switch boot guard starting..."
    
    # Ensure persistent directory exists (daemon creates it, but boot guard might run first)
    if [ ! -d "$PERSISTENT_DIR" ]; then
        log "Creating persistent directory: $PERSISTENT_DIR"
        mkdir -p "$PERSISTENT_DIR" 2>/dev/null || {
            log "WARNING: Failed to create persistent directory, continuing anyway"
        }
    fi
    
    # Check if persistent kill switch was enabled
    if ! check_persistent_enabled; then
        log "Persistent kill switch not enabled, skipping rule application"
        exit 0
    fi
    
    # Wait for iptables to become available (with retry)
    local iptables
    iptables=$(wait_for_iptables)
    if [ $? -ne 0 ] || [ -z "$iptables" ]; then
        log "ERROR: iptables not found after retries, cannot apply kill switch rules"
        log "ERROR: This is critical - traffic may leak during boot"
        exit 1
    fi
    
    # Apply blocking rules BEFORE network comes up
    if ! apply_blocking_rules "$iptables"; then
        log "ERROR: Failed to apply blocking rules"
        exit 1
    fi

    # IPv6 enforcement is required before reporting successful protection.
    local ip6tables
    ip6tables=$(wait_for_ip6tables)
    if [ $? -eq 0 ] && [ -n "$ip6tables" ]; then
        if ! apply_blocking_rules_v6 "$ip6tables"; then
            log "ERROR: Failed to apply IPv6 blocking rules; protection incomplete"
            exit 1
        fi
    else
        log "ERROR: ip6tables unavailable; protection incomplete"
        exit 1
    fi
    
    log "Boot guard completed successfully - internet blocked until VPN connects"
}

stop() {
    # Service shutdown/restart is not an explicit protection-disable command.
    # In particular, a missing/unreadable preference must never remove rules.
    # The authenticated daemon disable transaction owns preference and firewall
    # removal; the boot guard only restores protection.
    log "Kill switch boot guard stopping; existing protection retained"
    return 0
}

# Allow isolated helper regression tests without applying network policy.
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
case "${1:-}" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        iptables=$(find_iptables) || exit 1
        if $iptables -L "$CHAIN_NAME" -n &>/dev/null; then
            echo "Kill switch boot guard: ACTIVE"
            $iptables -L "$CHAIN_NAME" -n --line-numbers
        else
            echo "Kill switch boot guard: INACTIVE"
        fi
        if ip6tables=$(find_ip6tables); then
            if $ip6tables -L "$CHAIN_NAME6" -n &>/dev/null; then
                echo "IPv6 kill switch: ACTIVE"
                $ip6tables -L "$CHAIN_NAME6" -n --line-numbers
            else
                echo "IPv6 kill switch: INACTIVE"
            fi
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|status}"
        exit 1
        ;;
esac
fi
