I need rules that :

  1. Block all incoming traffic ( internet > server) but allow outgoing ( server > internet ) and allow local services to run too

  2. Only accept incoming traffic from ports I want.

I also need to this while in a ssh session ( I've been locked before ).

The reason I'm asking is because I'm unable to use UFW with my VPS provider... apparently because their kernel / OpenVZ...

While I tried to learn the commands by myself that is like learning to use a tool and trying to build a house. And would be really nice if I could have some productivity today instead of spending hours and hours trying to fix this. If someone could help me I would really appreciate.


First allow your specific port then block all incoming traffice

# iptables -A INPUT -p tcp --dport 22 -j ACCEPT

where 22 your demo port change it on your demand

Block all incoming traffic

# iptables -A INPUT -j REJECT

Allow all outgoing packet

# iptables -A OUTPUT -j ACCEPT
# iptables -A OUTPUT -o lo -j ACCEPT
  • You should also include the ip6tables commands, as iptables won't apply rules for IPv6, and half of your firewall will be wide open. – Michael Mol Apr 13 '17 at 4:33
  • I'm getting iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT iptables: No chain/target/match by that name. I wish I could just change my vps provider but i already paid for 3 months :/ – Freedo Apr 13 '17 at 4:33
  • also how can I accept tcp and udp on the port I selected? do i need to add 2 rules? – Freedo Apr 13 '17 at 4:42
  • yes . After this rules iptables -A INPUT -p tcp --dport 22 -j ACCEPT you add another rules for udp packet iptables -A INPUT -p udp --dport 22 -j ACCEPT – Rakib Apr 13 '17 at 4:45
  • I tried this but it wont allow reply from the outside. I can't use apt-get for example – Freedo Apr 13 '17 at 4:56

@Rakib provided a great answer, and I think it should be the accepted one. The answer I am giving just adds onto his. I recommend making a shell script so that you can have it run automatically when the OS is booted, or on demand without having to type it all out again:


IPT = iptables

#allowing the specific port
$IPT -A INPUT -p tcp --dport 22 -j ACCEPT

#block all incoming traffic


#same thing for ip6tables (IPv6)
IPT = ip6tables
$IPT -A INPUT -p tcp --dport 22 -j ACCEPT

Also the script was done twice, with the only difference being that ip6tables was included, so that the apply for IPv6 as well, as @Michael Mol said in his comment under @Rakib's answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.