Rocky 9.x Geo-Restricted SSH Access
Home > Rocky Linux or CentOS > Rocky Linux 9.x > System Administration > Rocky 9.x Geo-Restricted SSH Access
1. Install ipset and iptables-services
Run:
sudo dnf install ipset iptables-services -y
2. Download India IP Ranges
If you already have the in.zone file, skip this. Otherwise, fetch fresh:
wget https://www.ipdeny.com/ipblocks/data/countries/in.zone -O /tmp/in.zone
3. Create an ipset for India
Run:
sudo ipset create india hash:net
4. Add IP Ranges to the ipset
Run:
while read ip; do sudo ipset add india $ip; done < /tmp/in.zone
5. Add iptables Rules to Restrict SSH
Run:
sudo iptables -A INPUT -p tcp --dport 22 -m set --match-set india src -j ACCEPT sudo iptables -A INPUT -p tcp --dport 22 -j REJECT
This ensures SSH is allowed only from Indian IP ranges and rejected otherwise.
6. Save ipset and iptables for Persistence
Save ipset rules:
sudo ipset save > /etc/ipset.conf
Save iptables rules:
sudo service iptables save
(or if the above doesn’t work)
sudo iptables-save > /etc/sysconfig/iptables
7. Make ipset Load on Boot
Method 1: Using systemd (preferred)
Create /usr/local/bin/ipset-restore.sh with below contents:
#!/bin/bash /usr/sbin/ipset restore < /etc/ipset.conf
Run:
sudo chmod +x /usr/local/bin/ipset-restore.sh
Create or edit the file /etc/systemd/system/ipset-restore.service with the following content:
[Unit] Description=Restore IP sets from /etc/ipset.conf Before=network-pre.target Wants=network-pre.target [Service] Type=oneshot ExecStart=/usr/local/bin/ipset-restore.sh [Install] WantedBy=multi-user.target
Enable the service:
sudo systemctl daemon-reload sudo systemctl enable ipset-restore
Method 2: Using rc.local (alternative)
Create or edit /etc/rc.d/rc.local and add:
#!/bin/bash ipset restore < /etc/ipset.conf exit 0
Make it executable:
sudo chmod +x /etc/rc.d/rc.local sudo systemctl enable rc-local sudo systemctl start rc-local
8. Reboot Test
After reboot, check:
sudo ipset list sudo iptables -L INPUT --line-numbers
Make sure the rules and ipset are active.
Home > Rocky Linux or CentOS > Rocky Linux 9.x > System Administration > Rocky 9.x Geo-Restricted SSH Access