Search code examples
blockfirewalliptablesvpssshd

Blocking my vps from connecting to other vps/ip/port via sshd


I would like to deny any connection from my vps to other vps/ip/port via sshd.(443)

I tried using iptables and firewall rules, seems that still nothing worked.

iptables -A INPUT -s 1.1.1.1 -j DROP ;
iptables -A FORWARD -s 1.1.1.1 -j DROP ;
iptables -A OUTPUT -s 1.1.1.1 -j DROP ;
iptables -A INPUT -p tcp -s 1.1.1.1 --dport 443 -j REJECT --reject-with tcp-reset ;
iptables -A OUTPUT -p tcp -s 1.1.1.1 --dport 443 -j REJECT --reject-with tcp-reset ;
iptables -A FORWARD -p tcp -s 1.1.1.1 --dport 443 -j REJECT --reject-with tcp-reset ;
iptables -I INPUT -s 1.1.1.1 -p tcp --dport 443 -j REJECT ; 
iptables -I OUTPUT -s 1.1.1.1 -p tcp --dport 443 -j REJECT ;
iptables -I FORWARD -s 1.1.1.1 -p tcp --dport 443 -j REJECT ;
firewall-cmd --direct --add-rule ipv4 filter INPUT 1 -m tcp --source 1.1.1.1 -p tcp --dport 22 -j REJECT ;
firewall-cmd --direct --add-rule ipv4 filter OUTPUT 1 -m tcp --source 1.1.1.1 -p tcp --dport 22 -j REJECT ;
firewall-cmd --direct --add-rule ipv4 filter FORWARD 1 -m tcp --source 1.1.1.1 -p tcp --dport 22 -j REJECT ;

Solution

  • If you are on a distro that has UFW such as Ubuntu, blocking outbound connections can be easily done with the 3 commands below. What's more, this will survive reboot, unlike any iptables commands, which need iptables-save or other tool to re-apply the iptables settings after reboot.

    You didn't mention other outbound connections. The commands below block all outbound connections (but not outbound traffic for a connection that it is initiated from the outside).

    sudo ufw enable
    sudo ufw default allow incoming # allow inbound connections
    sudo ufw default deny outgoing
    

    To temporarily allow outbound connections, e.g. to download software updates:

    sudo ufw default allow outgoing
    # run your update here
    sudo ufw default deny outgoing