Back to articles
Technology Insight

Securing Your VPS: The Definitive Guide to Port Knocking with nftables

June 3, 2026

Introduction to Advanced Network Defense

In the modern cybersecurity landscape, simply using strong passwords or SSH keys is no longer a definitive shield against sophisticated automated attacks. Every public-facing Virtual Private Server (VPS) is subject to relentless, automated port scanning from the moment it goes online. Traditional firewalls protect ports by filtering unauthorized IP addresses, but the port itself remains visible, showing up as "closed" or "filtered." This visibility invites targeted brute-force attacks and zero-day exploitation attempts.

What if you could make your most sensitive services, such as SSH (Port 22), Webmin, or custom database ports, completely invisible to unauthorized users? Enter Port Knocking—a method of establishing a secure connection by triggering a specific, pre-defined sequence of connection attempts to closed ports. This comprehensive guide details how to implement a robust Port Knocking mechanism using nftables, the modern successor to iptables in Linux environments.

Understanding the Mechanics of Port Knocking

Port Knocking operates on a simple yet highly secure principle: security through obscurity combined with cryptographic-like sequential verification. Think of it as a secret knock on a hidden backdoor. By default, the firewall drops all incoming traffic to a protected port without sending any response. To an outside observer or automated scanner, the service appears completely nonexistent.

The Connection Workflow

When a legitimate administrator needs to access the server, they execute a precise sequence of connection attempts. The typical lifecycle looks like this:

  1. The Knock Sequence: The client sends packet attempts (usually SYN packets) to a specific sequence of ports (e.g., Port 7000, then Port 8000, then Port 9000).
  2. Firewall Evaluation: The nftables engine monitors these silent drops. It tracks the state and source IP of the incoming knocks using dynamic sets and timeouts.
  3. Dynamic Whitelisting: If the sequence is completed in the exact order and within the allowed time window, the firewall temporarily adds the client's IP address to an authenticated group, granting access to the hidden port (e.g., Port 22).
  4. Session Termination and Auto-Lock: The administrator connects. After a predefined period, the client's IP is automatically removed from the temporary whitelist, while existing active connections remain uninterrupted.
Note: Port Knocking is not a replacement for strong authentication mechanisms like SSH keys; rather, it acts as an indispensable first layer of defense that prevents attackers from even attempting to exploit your authentication systems.

Why Choose nftables Over legacy iptables?

For years, administrators relied on iptables paired with the knockd daemon to handle port knocking. However, modern Linux distributions (including Debian, Ubuntu, CentOS Stream, and AlmaLinux) have fully transitioned to nftables. Utilizing native nftables for port knocking offers significant advantages:

  • Performance: nftables compiles rulesets into an isolated, high-performance virtual machine state machine within the Linux kernel, minimizing CPU overhead during heavy traffic or DDoS attacks.
  • Native State Management: Through the use of named sets and maps with built-in timeout attributes, nftables can natively handle sequential tracking without requiring an external user-space daemon like knockd.
  • Atomicity: Ruleset updates are atomic, meaning you can reload your entire firewall configuration as a single transaction without dropping active network states.
---

Step-by-Step Implementation Guide

Let us walk through configuring a three-stage port knocking sequence to protect SSH (Port 22). For this demonstration, our secret knock sequence will be Port 1111 -> Port 2222 -> Port 3333. A successful sequence will open Port 22 for exactly 15 seconds, giving the administrator time to initiate a connection.

Step 1: Prerequisites and Preparing the Environment

Before proceeding, ensure you have root or sudo privileges on your Linux VPS and that nftables is installed and enabled. To prevent accidental lockouts, do not close your current SSH session until the configuration is fully tested and verified.

sudo apt update && sudo apt install nftables -y
sudo systemctl enable nftables
sudo systemctl start nftables

Step 2: Designing the nftables Ruleset

We will create a clean configuration file. Open the main configuration file using your preferred text editor:

sudo nano /etc/nftables.conf

Replace or populate the file with the following production-grade configuration. Pay close attention to how the tracking sets flow into one another:

#!/usr/sbin/nft -f

flush ruleset

table inet filter {
    # Dynamic sets to track knocking progression
    set stage1 {
        type ipv4_addr
        flags timeout
        timeout 10s
    }
    set stage2 {
        type ipv4_addr
        flags timeout
        timeout 10s
    }
    set secure_access {
        type ipv4_addr
        flags timeout
        timeout 15s
    }

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

        # Allow loopback interface and established connections
        iifname "lo" accept
        ct state established,related accept

        # Handle SSH Access based on successful knocking
        tcp dport 22 ip saddr @secure_access accept

        # Port Knocking Sequence Logic
        # Knock 1: Target Port 1111 -> Moves IP to stage1
        tcp dport 1111 add @stage1 { ip saddr } drop

        # Knock 2: Target Port 2222 -> Verifies stage1, moves to stage2, removes stage1
        tcp dport 2222 ip saddr @stage1 add @stage2 { ip saddr } delete @stage1 { ip saddr } drop

        # Knock 3: Target Port 3333 -> Verifies stage2, unlocks SSH, removes stage2
        tcp dport 3333 ip saddr @stage2 add @secure_access { ip saddr } delete @stage2 { ip saddr } drop

        # Explicitly drop everything else reaching this point
        drop
    }

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

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

Step 3: Applying and Activating the Firewall

Once you have saved the configuration file, validate the syntax to ensure no errors were introduced. If the syntax check passes, apply the ruleset immediately:

sudo nft -c -f /etc/nftables.conf
sudo nft -f /etc/nftables.conf

Verify that your rulesets and dynamic tracking sets are actively loaded into the kernel memory by querying the nft list command:

sudo nft list table inet filter
---

Testing Your Port Knocking Setup

Now that the firewall completely drops unauthenticated traffic to port 22, attempting a standard connection from a client machine will result in a connection timeout:

ssh user@your_vps_ip
# Result: ssh: connect to host your_vps_ip port 22: Connection timed out

Executing the Knock Sequence from a Client

To unlock access, we must generate packets to our target ports in the precise sequence. You can accomplish this easily from a Linux or macOS terminal using nmap, nc (netcat), or a basic bash loop. Here is how to do it efficiently using standard netcat with a short timeout:

nc -z -w 1 your_vps_ip 1111
nc -z -w 1 your_vps_ip 2222
nc -z -w 1 your_vps_ip 3333

Alternatively, a highly precise single-line bash loop can execute the sequence seamlessly:

for port in 1111 2222 3333; do nc -z -w 1 your_vps_ip $port; done

Connecting to the Unlocked Port

Immediately after executing the knock sequence, initiate your SSH connection within the 15-second window:

ssh user@your_vps_ip

Once the TCP handshake for your SSH session is established, the ct state established,related accept rule takes over. You can stay connected for hours; the 15-second timeout only restricts the window allowed to initiate a new connection.

---

Best Practices for Production Environments

While port knocking significantly minimizes attack surfaces, implementing these operational best practices guarantees long-term stability and resilience:

  • Choose Unconventional Ports: Do not use easily predictable sequences like 1000, 2000, 3000. Choose high, random, non-standard ephemeral ports that do not conflict with running services.
  • Incorporate UDP and TCP Mixes: To further confuse network sniffers, design your sequence to alternate between TCP and UDP flags (e.g., TCP 4503 -> UDP 9122 -> TCP 6112).
  • Monitor Firewall Logs: Regularly inspect your system logs to track successful knocks and detect anomalies. You can add a logging clause within your nftables chains to send authentication events directly to syslog.
  • Establish a Backup Access Method: Always preserve a secondary, restricted access method (such as a provider management console or a restricted VPN gateway) in case you forget your knock sequence or experience network latency that breaks sequence timing.

Conclusion

Implementing Port Knocking with nftables changes the dynamics of server hardening. By transitioning your system from a defensive state that continuously deflects attacks to a state of absolute invisibility, you eliminate malicious automated traffic entirely. Leveraging the kernel-level efficiency of nftables ensures that your VPS remains robust, highly performant, and invisible to the public internet.

Securing Your VPS: The Definitive Guide to Port Knocking with nftables | DPTCloud