Port Knocking
Port Knocking
Section titled “Port Knocking”Port knocking is a security technique that hides services from public view until a client demonstrates authorization through a predefined sequence of connection attempts. All public IP addresses are constantly being scanned by bots and services like shodan.io, which gather information for brute-force attacks and exploit attempts. Port knocking provides a cost-effective defense by not exposing any ports and simply listening to connection attempts. When the correct sequence of port connections is detected, the client is considered trusted and added to a secured address list that bypasses standard WAN firewall rules.
This approach effectively hides your services from random internet scanning while maintaining accessibility for authorized users who know the correct knock sequence. The technique is particularly valuable for administrators who need remote access to devices with public IP addresses but want to minimize their attack surface.
How Port Knocking Works
Section titled “How Port Knocking Works”The port knocking mechanism relies on firewall filter rules that monitor connection attempts on specific ports. Each port in the knock sequence acts as a validation step, where only clients who have successfully completed previous steps are allowed to proceed. This creates a layered validation system where unauthorized scanners must guess not just the correct ports, but also the correct order of connection attempts.
When a client attempts to connect to the first knock port, the firewall rule adds the source IP address to a temporary address list. The second knock port rule checks that the source IP is already in the first list before adding it to a second list, and so on. Only after completing the full sequence does the client get added to the trusted list that permits actual access to services.
The timeout mechanism ensures that incomplete sequences expire automatically. If a client starts the knock sequence but does not complete it within the specified time, the intermediate address list entries are removed and the client must start over. This prevents attackers from building up partial sequences over time.
Setup Example
Section titled “Setup Example”The following example demonstrates a three-port knock sequence. You should have an existing firewall configuration that drops all connection attempts from the WAN interface. The knock rules must be placed before the drop rules in your firewall chain to take effect.
First, create the firewall rule that listens on the first knock port and adds connected source IPs to an address list:
/ip firewall filter add action=add-src-to-address-list address-list=knock1 address-list-timeout=30s chain=input dst-port=888 in-interface-list=WAN protocol=tcpAdd a second rule that validates the second knock port, but only for IPs already in the first list:
/ip firewall filter add action=add-src-to-address-list address-list=knock2 address-list-timeout=30s chain=input dst-port=555 in-interface-list=WAN protocol=tcp src-address-list=knock1The final knock adds trusted IPs to a secured list that permits access:
/ip firewall filter add action=add-src-to-address-list address-list=secured address-list-timeout=30m chain=input dst-port=222 in-interface-list=WAN protocol=tcp src-address-list=knock2/ip firewall filter add action=accept chain=input in-interface-list=WAN src-address-list=securedThe address-list-timeout values control how long each validation state persists. The intermediate stages use shorter timeouts (30 seconds) to minimize the window for brute-force attacks, while the final secured list uses a longer timeout (30 minutes) to reduce the frequency of required knock sequences for legitimate users.
Verifying Your Configuration
Section titled “Verifying Your Configuration”Verify the rules are in the correct order:
/ip firewall filter print chain=inputYour knock rules should appear before any drop rules for the WAN interface. If needed, use the move command to reorder:
/ip firewall filter move 0 3Executing the Knock Sequence
Section titled “Executing the Knock Sequence”To access the router from WAN, authorized clients must send connection attempts to the knock ports in the correct order. While dedicated port-knocking clients are available, a simple bash one-liner using nmap can perform the sequence:
for x in 888,555,222; do nmap -p $x -Pn xx.xx.xx.xx; doneThe -Pn flag disables ping probes, which is useful when the target device may not respond to ping requests. Adjust the IP address (xx.xx.xx.xx) to match your router’s WAN address. This command attempts connections to each port in sequence, which triggers the address list additions and grants access upon successful completion.
For users on Windows systems, similar functionality can be achieved with PowerShell or by using the Nmap tool for Windows. The key requirement is that connection attempts must be made to each port in the specified order within the timeout windows defined in your firewall rules.
Verifying Access
Section titled “Verifying Access”After executing the knock sequence, verify your IP was added to the secured list:
/ip firewall address-list print where list=securedYou should see your source IP in the list. If not, check that:
- The knock sequence was completed within 30 seconds
- The correct port order was used (888 → 555 → 222)
- Your firewall isn’t blocking the responses
Blacklist Integration
Section titled “Blacklist Integration”Simple port scanning can accidentally trigger the correct ports in the correct order, so adding a blacklist mechanism provides additional protection. The blacklist identifies suspicious IPs and applies stricter rules that make automated scanning impractical.
Add a drop rule at the top of your firewall chain for blacklisted IPs:
/ip firewall filter add action=drop chain=input disabled=yes in-interface-list=WAN src-address-list=blacklistThis rule should be placed at the very top of your input chain so that blacklisted IPs are dropped immediately without processing further rules.
Create rules to add suspicious IPs to the blacklist based on their behavior:
/ip firewall filter add action=add-src-to-address-list address-list=blacklist address-list-timeout=1000m chain=input disabled=yes dst-port=666 in-interface-list=WAN protocol=tcpThis rule catches connections to “bad ports” that legitimate users would never attempt to access. The high timeout value (1000 minutes) ensures that flagged IPs remain blocked for an extended period.
/ip firewall filter add action=add-src-to-address-list address-list=blacklist address-list-timeout=1m chain=input disabled=yes dst-port=21,22,23,8291,10000-60000 in-interface-list=WAN protocol=tcp src-address-list=!securedThis rule adds IPs to the blacklist if they scan common ports (SSH, telnet, Winbox, and high-numbered ports) while not already in the secured list. The short timeout (1 minute) prevents long-term lockout of legitimate users who might accidentally probe these ports, while still being effective against sustained scanning attacks.
The blacklist rules are added with disabled=yes to avoid accidentally locking yourself out during initial configuration. Enable these rules once you have verified that your legitimate knock sequence works correctly:
/ip firewall filter enable numbers=5,6Passphrase Validation for Additional Security
Section titled “Passphrase Validation for Additional Security”For environments requiring stronger authentication, you can add passphrase validation to each knock using Layer7 protocol matching. This requires the connecting client to send specific data with the connection attempt, adding another layer of security beyond the port sequence.
Layer7 rules are resource-intensive and may impact router performance. Use this feature only when necessary and test thoroughly under expected load conditions.
Create a Layer7 protocol definition to match the passphrase:
/ip firewall layer7-protocol add name=pass regexp="^passphrase$"Apply this Layer7 rule to your knock rule:
/ip firewall filter add action=add-src-to-address-list address-list=knock1 address-list-timeout=30s chain=input dst-port=888 in-interface-list=WAN protocol=udp layer7-protocol=passThis configuration requires clients to send the exact string “passphrase” with their connection attempt. Clients attempting plain connection attempts without the correct passphrase data will not be added to the address list. This significantly increases the difficulty of brute-forcing the knock sequence, as attackers must now guess both the correct ports and the correct passphrase.
When implementing passphrase validation, ensure your knock client supports sending custom data with connection attempts. Not all port-knocking clients support this feature, so verify compatibility before relying on it for production security.
Script-Based Knock Sequences
Section titled “Script-Based Knock Sequences”While the firewall-only approach handles most use cases, RouterOS scripts add flexibility for advanced scenarios: logging knock attempts, sending notifications, applying conditional logic, or building longer sequences that would be unwieldy as pure firewall rules.
Script: Grant Access After Knock Sequence
Section titled “Script: Grant Access After Knock Sequence”This script can be called from a scheduler or triggered by an external event. It checks whether a source IP has completed the knock sequence and grants temporary access:
/system script add name=check-and-grant source={ :local knockedIPs [/ip firewall address-list find list=knock2] :foreach id in=$knockedIPs do={ :local ip [/ip firewall address-list get $id address] /ip firewall address-list add list=secured address=$ip timeout=30m comment="granted-by-script" /ip firewall address-list remove $id :log info "Port knock: granted access to $ip" }}Script: Logging and Alerting
Section titled “Script: Logging and Alerting”Track knock attempts for security auditing:
/system script add name=log-knock-attempts source={ :local stage1 [/ip firewall address-list find list=knock1] :local stage2 [/ip firewall address-list find list=knock2] :local secured [/ip firewall address-list find list=secured] :log info ("Port knock stats: stage1=" . [:len $stage1] . " stage2=" . [:len $stage2] . " secured=" . [:len $secured])}
/system scheduler add name=knock-logger interval=5m on-event=log-knock-attemptsScript: Automated Cleanup
Section titled “Script: Automated Cleanup”Remove stale entries from knock stages to keep address lists clean:
/system script add name=clean-knock-lists source={ # Address-list timeouts handle expiry automatically, but this # script can force-clean all intermediate stages on demand :foreach id in=[/ip firewall address-list find list=knock1] do={ /ip firewall address-list remove $id } :foreach id in=[/ip firewall address-list find list=knock2] do={ /ip firewall address-list remove $id } :log info "Knock intermediate lists cleared"}Call this script if you need to reset all in-progress knock sequences, for example after a suspected brute-force attempt on the knock sequence itself.
Limitations
Section titled “Limitations”Port knocking is security through obscurity — it reduces attack surface but is not a substitute for strong authentication. Understanding its limitations helps you deploy it appropriately.
What Port Knocking Does Not Protect Against
Section titled “What Port Knocking Does Not Protect Against”| Threat | Why Knocking Fails |
|---|---|
| Passive eavesdropping / packet capture | Knock sequence is visible in plaintext TCP/IP traffic on the wire |
| Man-in-the-middle attacks | Attacker who observes your knock can replay it immediately |
| Insider threats | Anyone who knows the sequence can use it |
| Denial of service | Legitimate services can still be targeted even if ports are hidden |
| Logic flaws in firewall rules | Misconfigured rules may expose services regardless of knock state |
Operational Constraints
Section titled “Operational Constraints”- Shared networks: On networks with NAT or CG-NAT, multiple users may share the same public IP. One user completing a knock sequence grants access for all users behind that IP.
- Timeout sensitivity: Very short timeouts (under 5 seconds) are fragile over high-latency connections; very long timeouts increase the attack window.
- Sequence length vs. usability: Adding more knock stages increases security but makes legitimate access more cumbersome and error-prone.
- Port blocking: Some ISPs, corporate firewalls, or carrier-grade networks may block connection attempts to non-standard ports, preventing the knock sequence from completing.
- Address-list size: RouterOS address lists are stored in RAM. Very large lists with long timeouts can consume memory on low-resource devices.
Not a Replacement For
Section titled “Not a Replacement For”Port knocking complements but does not replace:
- Strong passwords and SSH key authentication
- Disabling services that are not needed
- Regular firmware updates
- Proper network segmentation
Alternatives and Complementary Techniques
Section titled “Alternatives and Complementary Techniques”VPN-First Access (Recommended)
Section titled “VPN-First Access (Recommended)”The strongest approach is to place all management services behind a VPN. Administrators connect to the VPN first, then access management services over the private tunnel — no management ports are exposed to the internet at all.
# With WireGuard: only expose VPN port, all management via tunnel/interface wireguard add name=wg-admin listen-port=51820/ip firewall filter add chain=input protocol=udp dst-port=51820 action=accept comment="WireGuard VPN"/ip firewall filter add chain=input in-interface=wg-admin action=accept comment="accept management via VPN"See WireGuard for full VPN setup.
Brute-Force Prevention (Complementary)
Section titled “Brute-Force Prevention (Complementary)”Rate-limit connection attempts to reduce the effectiveness of brute-force attacks even if a port is exposed. This is orthogonal to port knocking — you can run both simultaneously.
/ip firewall filteradd chain=input protocol=tcp dst-port=22 connection-state=new \ src-address-list=ssh-brute action=drop comment="drop ssh bruteforce"add chain=input protocol=tcp dst-port=22 connection-state=new \ action=add-src-to-address-list address-list=ssh-brute \ address-list-timeout=30m connection-limit=3,32 comment="detect ssh bruteforce"See Bruteforce Prevention for a complete implementation.
IP Allowlisting
Section titled “IP Allowlisting”If your administrative source IPs are stable, simple allowlisting is more reliable than port knocking:
/ip firewall address-list add list=admin-ips address=203.0.113.10 comment="office IP"/ip firewall address-list add list=admin-ips address=198.51.100.5 comment="home IP"/ip firewall filter add chain=input src-address-list=admin-ips action=accept comment="allow admin IPs"/ip firewall filter add chain=input protocol=tcp dst-port=22 action=drop comment="drop all other SSH"Choosing the Right Approach
Section titled “Choosing the Right Approach”| Scenario | Recommended Approach |
|---|---|
| Static admin IPs | IP allowlisting — simpler and more reliable |
| Dynamic admin IPs, strong security required | VPN (WireGuard/IPsec) |
| Dynamic admin IPs, VPN not feasible | Port knocking + brute-force prevention |
| High-security environment | VPN + port knocking + brute-force prevention |
| Resource-constrained router | Port knocking only (minimal CPU/RAM overhead) |
Troubleshooting
Section titled “Troubleshooting”Locked Out After Configuration
Section titled “Locked Out After Configuration”If you accidentally lock yourself out:
- Access the router via a local interface (ethernet or console)
- Temporarily add your IP to the secured list:
/ip firewall address-list add address=YOUR_IP list=secured address-list-timeout=1d- Review and fix your knock rules
- Test thoroughly before closing local access
Knock Sequence Not Working
Section titled “Knock Sequence Not Working”- Verify all knock rules are enabled
- Check that rules are in the correct order
- Ensure timeouts haven’t expired during testing
- Confirm the in-interface-list matches your WAN interface
/interface list printAddress Lists Not Populating
Section titled “Address Lists Not Populating”- Check that the input chain has the correct in-interface-list
- Verify protocol matches (TCP vs UDP)
- Confirm src-address-list prerequisites are correct
/ip firewall address-list print/ip firewall filter print chain=inputBest Practices
Section titled “Best Practices”Port Selection
Section titled “Port Selection”- Use non-standard ports above 1024 to reduce accidental triggers
- Avoid ports commonly used by legitimate services
- Document your knock sequence securely
Timeout Tuning
Section titled “Timeout Tuning”| Stage | Recommended Timeout | Rationale |
|---|---|---|
| Knock stages | 30s | Quick expiration prevents brute force |
| Secured list | 30m - 2h | Balance between security and convenience |
| Blacklist | 1h - 1000m | Longer for confirmed attackers |
Testing
Section titled “Testing”- Always test from a secondary connection before relying on port knocking
- Keep console/serial access available during initial setup
- Enable blacklist rules only after confirming knock sequence works
Related Commands
Section titled “Related Commands”/ip firewall filter- Configure firewall filter rules/ip firewall address-list- Manage address lists/ip firewall layer7-protocol- Define Layer7 patterns/interface list- Manage interface lists