Linux block ip address

Block IP addresses in Linux with iptables

Blocking IP addresses and subnets with ipset

Most system administrators will already be familiar with iptables. It is around for quite a while and is enabled by default within the Linux kernel. We can use iptables to block one, multiple IP addresses, or even full networks. This may come in handy when you get repeating port scans or see failed login attempts in your log files. Time to get started and block some IP addresses!

Check existing iptables configuration

The first step is to validate existing iptables rules. We will use an empty ruleset for test purposes.

Manually blocking a single IP address

The first option to permanently block an IP address is by creating a rule in the INPUT chain. This way traffic is no longer allowed from that particular IP address.

iptables -I INPUT -s 192.168.1.100 -j DROP

Although this option works great, it might not scale very well. You might even get a very long list of IP addresses to block after a while. Let’s have a look at ipset.

Using blacklists with iptables and ipset

Another option is creating a blacklist. This way we can add multiple systems we no longer want to connect to our systems.

Install ipset utility

Most Linux systems do not have the ipset utility installed by default. So first install that toolkit.

CentOS

You may need to install the epel-release package first.

Debian and Ubuntu

Creating a blacklist

With the newly installed ipset utility we create a new list to block IP addresses. We name it blacklist to show clearly its purpose.

Note: if you want to block based on networks, use hash:net.

After the blacklist is created, we can use the set in iptables. It is related to the –match-set option.

These commands will add the blacklist (or set) to the INPUT and FORWARD chains. As this is a blacklist, the related policy is to drop traffic. No output will be displayed when entering the commands.

Adding IP addresses to block

Next step is adding actual IP address to the list:

Show details

To confirm the blacklist contains the IP address, use the ipset list command.

In this screenshot, we can see the IP address is listed as a member of the set. Now traffic should be blocked.

Test rules and activate rules on reboot

When setting up a blacklist like this, always test it. You want to be sure that the blacklist is enforced in your specific configuration. Also, make sure it still works after a reboot of the system.

To save and restore iptables rules, use the package iptables-persistent. As the name implies, this makes the iptables rules persistent across reboots.

To also store ipset rules, create a small systemd service file: /etc/systemd/system/save-ipset-rules.service

# ipset save/restore script (see https://linux-audit.com/blocking-ip-addresses-in-linux-with-iptables/)

[Unit]
Description=ipset persistent rule service
Before=netfilter-persistent.service
ConditionFileNotEmpty=/etc/iptables/ipset

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/sbin/ipset -exist -file /etc/iptables/ipset restore
ExecStop=/sbin/ipset -file /etc/iptables/ipset save

This script helps to save and restore the ipset rules. You may need to create the /etc/iptables/ipset file.

/sbin/ipset -file /etc/iptables/ipset save

Combining ipset and IPv6

If you want to use IPv6 addresses, create the related database with the ‘inet6’ family.

ipset create blacklist6 hash:net hashsize 4096 family inet6

Then create the ip6tables rule:

ip6tables -I INPUT -m set —match-set blacklist6 src -j DROP

Keep learning

So you are interested in Linux security? Join the Linux Security Expert training program, a practical and lab-based training ground. For those who want to become (or stay) a Linux security expert.

Run automated security scans and increase your defenses. Lynis is an open source security tool to perform in-depth audits. It helps with system hardening, vulnerability discovery, and compliance.

Continue reading

Beginners Guide to nftables Traffic Filtering

Differences between iptables and nftables explained

Exporting nftables rules and configuration

30 comments

Thank you that worked out fantastic.

We should always block external traffic. Allow only required IP with port. IPTABLES is good firewall to block external traffic.

I’m using this heavy duty bash script as root for some like 15 minutes:

sort blacklist-ip | uniq -u > blacklist-ip-sorted
sort blacklist-ip-range | uniq -u > blacklist-ip-range-sorted
while read IPADDR
do
route add $IPADDR gw 127.0.0.1 lo &
done Michael Boelen

Thanks for sharing. While this is another option, it might be less efficient than dropping traffic directly.

thanks for this guide however in centos 6 these steps do not survive an iptables restart and there is no package iptables-persistent.

AND how do i unblock/deleted IP.

Remove it from the list. Example: ipset del blacklist 192.168.1.1

i want to create a blacklist but kernal is not allowing! how can i go about this?

Why is it not allowing it? Any message/error you get?

Thanks for sharing this information to help us all block amazon (‘;-)
But can you tell me if there’s an easier way of converting a long list of (amazon) ip’s to the set without individually doing the chore?

Читайте также:  What is ntldr in windows

Use the jq tool on the JSON file Amazon provides and block all subnets?

Been using ipset for years. Love it. Thought I pass along additional commands.

To save ips before a reboot, do the following:
Example below uses blacklist as the name, the file blacklist.txt to hold the blocked ips and is located at ‘/var/block/blacklist.txt’.

Fist, make sure iptables is not set to start automatically upon reboot. As ipset needs to be setup again with its ip lists and iptables will fail if it can’t find the ipset resources.

cd /var/block/
ipset -L blacklist > blacklist.txt

Then after a reboot, do the following:
ipset -N blacklist nethash
for i in $( cat /var/block/blacklist.txt ) ; do ipset -A blacklist $i ; done
service iptables start (Or, whatever you use to start iptables)

ipset can also be used to allow entry into a certain area. That is, if you have a private area under a designated IP. You can code to add a ip to ipset, as in this example:
Note: you will need to adjust sudoers on your system to allow for this to work.

ipset -N private nethash

Your code would send the command:
ipset -A private 111.111.111.111;

And, iptables will have a rule which is:
-A INPUT -i eth0 -d (Your Server IP that holds the private resource) -m set ! –match-set private src -j DROP

Once your user logs out or isn’t using the resource anymore, simply send the following command:
ipset -D private 111.111.111.111;

Of course, if the user is on a dynamic IP, this won’t work. Though, you could code to change the ip itself to 111.111.111.0/24 before adding to ipset and would require you to hold this info somewhere.

To add a bunch of IP’s to ipset:
This example uses the name blocklist and is located at /var/blocklist.txt
Add your ips one line at a time to the blocklist.txt file.

Then run the following:
for i in $( cat /var/blocklist.txt ) ; do ipset -A blocklist $i ; done

Then add the rule to iptables, such as:
-A INPUT –match-set blocklist src -j DROP

ipset can be used by the new firewalld system that overlays iptables in CentOS 7. It will store ipsets persistently in XML files under /etc/firewalld/ipsets. You can reference them using “direct rules” in firewalld, a way to inject raw iptables commands into firewalld. The firewalld service will create the ipsets before it installs the rules that use them.

(The firewalld documentation cautions you not to use the iptables service at the same time, but you can safely use the iptables commands to inspect the underlying rules that firewalld creates.)

i don know whats wrong, after a reboot there is no blacklist aviable.
I must do again all commands for ipset
– ipset create blacklist hash:ip hashsize 4096
– iptable -I INPUT -m set –match-set blacklist src -j DROP
– iptable -I FORWARD -m set –match-set blacklist src -j DROP
– ipset add blacklist xxx.xxx.xxx.xxx

ipset list shows me the correct output.
apt install iptables-persistent

Источник

How Do I Block an IP Address on My Linux server?

H ow do I block an IP address or subnet under Linux operating system?

In order to block an IP on your Linux server you need to use iptables tools (administration tool for IPv4 packet filtering and NAT) and netfilter firewall. First you need to log into shell as root user. To block an IP address you need to type the iptables command as follows:

Syntax to block an IP address under Linux

Replace IP-ADDRESS with your actual IP address. For example, if you wish to block an ip address 65.55.44.100 for whatever reason then type the command as follows:
# iptables -A INPUT -s 65.55.44.100 -j DROP
If you have IP tables firewall script, add the above rule to your script.

If you just want to block access to one port from an ip 65.55.44.100 to port 25 then type command:
# iptables -A INPUT -s 65.55.44.100 -p tcp —destination-port 25 -j DROP
The above rule will drop all packets coming from IP 65.55.44.100 to port mail server port 25.

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

CentOS / RHEL / Fedora Block An IP And Save It To Config File

Type the following two command:
# iptables -A INPUT -s 65.55.44.100 -j DROP
# service iptables save

How Do I Unblock An IP Address?

Use the following syntax (the -d options deletes the rule from table):
# iptables -D INPUT -s xx.xxx.xx.xx -j DROP
# iptables -D INPUT -s 65.55.44.100 -j DROP
# service iptables save

See also:

  1. You can write a shell script to block lots of IP address and subnets.
  2. Iptables: Unblock / Delete an IP Address Listed in IPtables Tables

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

i have aproblem to ristrick the wab page on client side.

i have linux server to run internt. i make gateway on that server and use it on other system to run internet.

her i want to on clint system only my specify wab pages is open.

plz u can help me how i confuger it.

my network is on workgroup

Ther are two solution:

1) the best practice you use a proxy server like suqid in the gateway machine. Then define ACL on the squid.
say you want to deny access to yahoo.com and rediffmail.com.
acl all src 0.0.0.0/0.0.0.0
acl web_yahoo dest yahoo.com
acl web_rediff dest rediff.com

http_access deny web_yahoo all
http_access deny web_rediff all

2) this option is throhgh iptables, assume that your gateway acts as a firewall.

iptables -A INPUT -p tcp –destination-port 80 -d -j DROP

it will drop any request to port 80 of yahoo from any source.

i want to connect internet on local pc by user from server

Please send me the code in Linux c to block the website typed on the browser. or send the references where i can get

iptables -A INPUT -s 80.58.205.35 -j DROP

and kept checking my apache logs, after a short pause of no requests from 80.58.205.35

it resumed ?? Could this mean I have been hacked ?

You need to add iptables -A INPUT -s 80.58.205.35 -j DROP to your firewall script. Once added 80.58.205.35 cannot connect to your apache. Do you run any special firewall script such as apf?

hi,
i need an iptable rule for a website(www.webmd.com) not to go through squid(proxy).could you pls send me the iptable rule for this one?

joel, i think you do it without iptables rule using squid configuration and I don’t think its possible to have such a rule. What do you say vivek ?

Yes, nilesh is right. It all depends upon your setup. Do you have squid proxy installed? If so there is an option to skip webmd.com from squid cache using ACL. Iptables is for filtering and restricting traffic.

@vivek and S. Nilesh,

yes i have a squid transparent proxy caching server and firewall in the same box.could you kindly post here the acl rules to bypass webmd from going through squid. btw im using the old 2.5 stable 6 version.thank you very much to both of you for responding to my question.

acl webmd dstdomain .webmd.com
always_direct webmd

it should do it for you…

thank you so much.that really works!! 🙂

@ S.Nilesh and Vivek,

i thought i should ask this question. how would you allow https traffic for one particular site on the network but restrict all other https traffic with an iptable rule.i have users bypassing my proxy redirector(squidguard) using https and i cannot block port 443 on my firewall because it is being used by a remote GUI application which is also being used by my users.

im not an iptables guru, but ive fought off plenty of attacks, and hack attempts, heres how chain worx k,
# Drop
rule 1
rule 2
rule 3
end of chain default rule (drop all or accept all however)
rule4 your new rule

so if you use the -A which is the add option its going to add to the drop chain right,
which will put it after an absolute depending on who or how your iptables is setup.
after an absolute is parsed, by iptables it wont read any further into the chain, there for your add option will never work as good as the insert flag -I

rule1
rule2
rule3
rule4 – our new rule here
drop all

Are these IP table entries are permanent? Recently I had blocked an IP using the step mentioned above. ( i.e. iptables -A INPUT -s 124.118.247.4 -j DROP ) I wanted to know, if my server reboots, does that entry can withstand the reboot or will loose upon reboot?

Noop, you need to write a shell script to keep them alive after reboot.

how to block all ip and allow access to only one ip?

iptables -I INPUT -s ! -j DROP

The Bang character (!) basically means NOT, so the line above would say drop ALL packets NOT going to ip address

why it’s working only if I use it like that? (not iptables -A INPUT -s 86.34.187.86 -j DROP)
iptables -I INPUT -s 86.34.187.86 -j DROP

Hi !!
I have RHEL5 installed and i have tried the command #iptables -A INPUT -s -j DROP. i hv logged into root and opened terminal…..and then typed this… bt it didn’t work!! Plz tell me the actual way to run this command… i really need this very urgently…

Hi !!
I have RHEL5 installed and i have tried the command #iptables -A INPUT -s IP ADDRESS -j DROP. i hv logged into root and opened terminal…..and then typed this… bt it didn’t work!! Plz tell me the actual way to run this command… i really need this very urgently…

Do anyone know how to block IP like that >
202.56.***.*** that means under 202.56. all IP will be blocked.

Regards,
Admin
Centriohost.com

Use a mask – so to block, say, 202.101.*.* you would specify the address in CIDR format as 202.101.0.0/16

Plenty of CIDR calculators on Google if you need help or just remember ranges as :
192.168.1.0/24 = 192.168.1.0 to 192.168.1.255
192.168.0.0/16 = 192.168.0.0 to 192.168.255.255
192.0.0.0/8 = 192.0.0.0 to 192.255.255.255.

how to setup youtube access for specific ip through acl .

i am not able block one particuler ip address plz suggest me

Try $IPT -I INPUT -s IP_ADDRESS -j DROP

I am having some problems leaving a remark. I’ve attempted refreshing several times as well as closing and opening opera. Is anyone else having a problem on this article?

Do you see any specific error?

iptables rules explained very clearly. Thank you.

Hi Vivek
This site is very useful and provides “to the point” information. Keep up the good work.

Aditya
Unix aficionado

I tested this and blocked the ip from my phone through ip tables. It didn’t block anything i could still ssh in i could still browse the website I host on this server and connect via ftp so I went into my iptables file
and typed this
-A PREROUTING -s PhoneIPAddress -j DROP
saved closed
service restart iptables
and then my phone had no access what so ever. Is this just a different way or am I going to run into problems by blocking ip addresses at the PREROUTING level

hi
i am new with IP tables stuff and i have a problem….
i have a pc Contain a fedora OS and i want to make a small network (4 PCs Contain XP OS) and using the pc of fedora OS as a firewall
i want to Prevent the ping (i think it called(ICMP)) in the privat network and prevent one of the PCs from Browsing internet(prevent port 80 and 81 as i think)
and i still don’t know how to make the internet go Through the firewall to the private network…

note: WAN = eth0
LAN = eth1
any one can help plz.

how can i check whether the iptables is blocked or not

How can I block connections ONLY TO port 80 of a range of addresses?

I do not want to create 300 single rules for.port 80. Port constraint required as must allow traffic to port 443

Not blocking any of the addresses in the range:

iptables -A INPUT -s 5.5.5.0/22 -p tcp –destination-port 80 -j DROP

iptables 1.4.10 (android)

thanks for the short lesson of the command. very help full.

i want my client with ip 192.168.1.1 can access http://www.google.com only not else.
whats is the iptables command?

I have a csv file with the ip list, I can block all ip in this file?

I want to Block IPs
an easy step in cpanel to block ip

If you have other rules in your INPUT chain you do need to use the -I option to insert your block at the top of the chain.

iptables -I INPUT -s 6.7.8.9 -j DROP

to block ip-adres 6.7.8.9.

hi there,
i have an error called 705 (failure to connect web server) when i upload the website on the server .
it bocks my ip because all other net connection open it so plz give me the better solution for that.

it working fine.
i am able to block ip address and unblock it. fine working.

but how to block a user ??

as a user using same mobile and changing ip-address and able to access server.

Another way to do this is to use routing table: use a black hole route to preventing your machine from sending anything back will prevent most attacks:

ip route add dev lo

ip route add 103.41.124.22/32 dev lo # block ssh hacking host

This will block any packets from going back to 103.41.124.22 and break any TCP connections. This will not prevent a SYN flood DoS though.

I have roughly 5,000 lines in my iptables blocking all of China (at least those not using a proxy or remote). Can anyone think of any performance degradation that may be had from having so many lines in the iptables?

What if the IP isn’t blocked by iptables ? I use the same rules and my website keeps getting hundreds of thousands of pw bruteforce attempts and the iptables counter of that rule stays at zero.

Jouni “rautamiekka” Järvinen – Take a look at fail2ban as this may be more appropriate for you…

Thanks for the advice. I have a very pesky chinese ip doing a brute-force or DOS attack on my machine. Now – nothing. Thanks again.

I get these brute force attacks a lot
IPTables isn’t enough to stop them and neither is hosts.deny
I blackhole the buggers by router them to 127.0.0.1
That way their scripts hang and hang waiting for a response, but they never get one heh heh
Example I block a specific IP:
route add 45.244.2.199 gw 127.0.0.1 lo

Or I block the entire subnet (Mostly China)
route add -net 188.72.69.0/24 gw 127.0.0.1 lo

I do this from Linux command line as root.
In case you want to test it using your cell phone IP or something this is how you remove it
route delete IPADDRESS

Источник

Читайте также:  Windows android operating system
Оцените статью