#!/usr/sbin/nft -f
# ==============================================================================
# /etc/nftables.conf
# ThinkPad T490 Zero-Leak Edge Gateway Firewall & NAT Configuration
# ==============================================================================

flush ruleset

table inet homelab_filter {
    # Flowtable fastpath hardware/software offloading
    flowtable fastpath {
        hook ingress priority 0;
        devices = { wlan0, enp0s31f6 };
    }

    chain input {
        type filter hook input priority filter; policy drop;

        # Local loopback
        iifname "lo" accept

        # Connection tracking: established/related
        ct state established,related accept
        ct state invalid drop

        # Transit network management & local DNS/DHCP
        iifname "enp0s31f6" ip protocol icmp accept
        iifname "enp0s31f6" udp dport { 53, 67 } accept
        iifname "enp0s31f6" tcp dport 53 accept
        iifname "enp0s31f6" ip saddr { 172.16.100.0/24, 192.168.45.0/24 } tcp dport 22 accept

        # Tailscale VPN Management
        iifname "tailscale0" accept
        udp dport 41641 accept

        # Upstream Wi-Fi: Allow DHCP client replies from Friend router
        iifname "wlan0" udp sport 67 udp dport 68 accept

        # Stealth Mode: Drop all unsolicited inbound from Wi-Fi
        iifname "wlan0" drop
    }

    chain forward {
        type filter hook forward priority filter; policy drop;

        # Offload established TCP/UDP streams to kernel fastpath
        ip protocol { tcp, udp } flow offload @fastpath

        # TCP MSS Clamping to PMTU (Prevents packet fragmentation blackholes)
        tcp flags syn tcp option maxseg size set rt mtu

        ct state established,related accept
        ct state invalid drop

        # Block lateral scanning/attacks against Friend's private subnets
        iifname "enp0s31f6" oifname "wlan0" ip daddr { 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12 } drop

        # Allow internal homelab subnets outbound to WAN
        iifname "enp0s31f6" oifname "wlan0" ip saddr { 172.16.100.0/24, 192.168.45.0/24 } accept

        # Tailscale Forwarding
        iifname "tailscale0" oifname "enp0s31f6" accept
        iifname "enp0s31f6" oifname "tailscale0" accept

        drop
    }

    chain output {
        type filter hook output priority filter; policy accept;

        # ZERO-LEAK: Drop discovery and multicast/broadcast frames egressing wlan0
        oifname "wlan0" udp dport { 5353, 5355, 137, 138, 1900, 3702 } drop
        oifname "wlan0" tcp dport { 139, 445 } drop
        oifname "wlan0" ip daddr { 224.0.0.0/4, 255.255.255.255 } drop
    }
}

table inet homelab_nat {
    chain postrouting {
        type nat hook postrouting priority srcnat; policy accept;

        # Single Edge Source NAT: Masquerade homelab subnets leaving via Wi-Fi
        oifname "wlan0" ip saddr { 172.16.100.0/24, 192.168.45.0/24 } masquerade
    }
}
