How can I effectively (so do it fast when talking about firewall level and can do it with many-many IP's) block an IP address for a given time, ex.: a month if it tried to contact port 22 TCP in any manner, so port check, connect via ssh, etc.

How can I do it with iptables, OpenBSD pf?

The main idea is that SSHD is running on a non-default port and with this blocking method, we could harden our protection without any extra software.

It should block the IP with DROP, not RFC REJECT

UPDATE: I mean it should do it automatically. I don't want to give every IP address manually.

  • 1
    I do not think blocking random IPs connecting to a port is the best of the ideas, and not over a long time. The iptables list can become rather long, and also running an SSHD in a different port is accounted for by many bots nowadays. Granted, less bad agents will find it. I do prefer to not expose SSH ports to the Internet, and use VPNs to get to ssh. Do not forget to use fail2ban applied to the port where the real service is running. – Rui F Ribeiro Mar 2 '16 at 11:47

You could use fail2ban or similar software, with a custom rule that blocked any IP address that tries to connect to port 22.

fail2ban manages automated blocking of hosts making unwanted connections (based on all sorts of criteria, including number of connection attempts, error messages in specific log files, attempts to fetch a particular URL, or pretty nearly anything you can think of and write a script to test for) as well as automated expiry of such blocks.

fail2ban is available packaged for most/all linux distros, and the home page is at: http://www.fail2ban.org/


Block Incoming Request From IP

The following command will drop any packet coming from the IP address

/sbin/iptables -A INPUT -i eth0 -p tcp --destination-port {PORT-NUMBER-HERE} -s {IP-ADDRESS-HERE} -j DROP

Example port 22:

/sbin/iptables -A INPUT -i eth0 -p tcp --destination-port 22 -s -j DROP

Block outcoming

/sbin/iptables -A OUTPUT -i eth0 -p tcp --destination-port {PORT-NUMBER-HERE} -s {IP-ADDRESS-HERE} -j DROP

Example port 22:

/sbin/iptables -A OUTPUT -i eth0 -p tcp --destination-port 22 -s -j DROP
  • 1
    I updated the question. – nyipeter Mar 2 '16 at 11:02

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.