Port Knocking and Dynamic Port Management

Port Knocking and Dynamic Port Management

Port knocking provides an additional security layer by hiding services behind closed ports until a specific sequence of connection attempts opens them temporarily. This technique effectively shields services from automated scanning and opportunistic attacks while maintaining accessibility for authorized users.

Implement basic port knocking on Linux using knockd:

# Install knockd
sudo apt-get install knockd

# Configure /etc/knockd.conf
[openSSH]
    sequence    = 7000,8000,9000
    seq_timeout = 5
    command     = /sbin/iptables -A INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
    tcpflags    = syn

[closeSSH]
    sequence    = 9000,8000,7000
    seq_timeout = 5
    command     = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
    tcpflags    = syn

# Enable and start knockd
sudo systemctl enable --now knockd

# Client-side knocking
knock server.example.com 7000 8000 9000
ssh server.example.com

Single Packet Authorization (SPA) provides more secure alternatives to port knocking:

# Install fwknop (FireWall KNock OPerator)
sudo apt-get install fwknop-server fwknop-client

# Server configuration /etc/fwknop/access.conf
SOURCE: ANY
OPEN_PORTS: tcp/22
KEY: generated_key_here
HMAC_KEY: generated_hmac_key_here

# Client usage
fwknop -A tcp/22 -a 192.168.1.100 -D server.example.com

Dynamic port management enables just-in-time access for administrative tasks:

# Windows PowerShell function for temporary port access
function Enable-TempRDPAccess {
    param(
        [string]$SourceIP,
        [int]$Duration = 30  # minutes
    )
    
    # Create temporary firewall rule
    $ruleName = "Temp-RDP-$SourceIP-$(Get-Date -Format yyyyMMddHHmmss)"
    New-NetFirewallRule -DisplayName $ruleName -Direction Inbound -Protocol TCP -LocalPort 3389 -RemoteAddress $SourceIP -Action Allow
    
    # Schedule removal
    $action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-Command Remove-NetFirewallRule -DisplayName '$ruleName'"
    $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes($Duration)
    Register-ScheduledTask -TaskName $ruleName -Action $action -Trigger $trigger -RunLevel Highest
    
    Write-Host "RDP access granted to $SourceIP for $Duration minutes"
}