How to Secure SSH Access on Linux with iptables: Restrict by IP

Learn how to protect your Linux server by blocking default SSH access on port 22 and allowing only specific IP addresses or ranges using iptables rules, with step-by-step shell script examples, rule inspection commands, and removal procedures for robust security.

Open Source Linux
Open Source Linux
Open Source Linux
How to Secure SSH Access on Linux with iptables: Restrict by IP

Goal: Restrict Linux server login using iptables rules

By default Linux servers allow SSH login on port 22, which is insecure. This guide shows how to limit access to specific source IPs.

Method: Create a shell script (iptables.sh) to apply the rules repeatedly.

iptables -I INPUT -p tcp --dport 22 -j DROP -m comment --comment "ssh"
# Allow a range of IPs
iptables -I INPUT -p tcp -m iprange --src-range 172.18.163.227-172.18.163.232 --dport 22 -j ACCEPT -m comment --comment "ssh"

# Allow a subnet
iptables -I INPUT -p tcp -s 10.99.193.0/24 --dport 22 -j ACCEPT -m comment --comment "ssh"

Explanation: These commands use the filter table's INPUT chain; the DROP rule must be the first rule.

To view inserted rules, run:

iptables -t filter -nvL --line-number | grep ssh

To delete a rule, use its line number, for example: iptables -t filter -D INPUT 3 When deleting, specify the filter table's INPUT chain and start from the highest line number to avoid errors.

Example script (iptables-myrules.sh) that blocks all traffic and then allows specific IPs:

#! /bin/bash
# author: xiongzaiqiren
# date: 2023-03-20
# usage: sh iptables-myrules.sh
# Set server security, allow specific source IPs

# Allow ping
iptables -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT

# Drop all connections
iptables -P INPUT DROP

# Allow specific IPs or ranges
iptables -A INPUT -s 10.99.193.243 -p tcp -j ACCEPT
iptables -A INPUT -s 10.90.5.0/24 -p tcp -j ACCEPT
iptables -A INPUT -s 10.99.193.0/24 -p tcp -j ACCEPT

iptables -nvL --line-numbers

Remember to save the rules after changes with iptables-save > /etc/iptables-myrules.conf.

iptables example
iptables example
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

iptablesshell scriptSSH
Open Source Linux
Written by

Open Source Linux

Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.