Skip to content

Instantly share code, notes, and snippets.

@zicodhkbd
Created November 1, 2019 18:13
Show Gist options
  • Save zicodhkbd/f1d62f5f2d2066380d1abc8ded3e282a to your computer and use it in GitHub Desktop.
Save zicodhkbd/f1d62f5f2d2066380d1abc8ded3e282a to your computer and use it in GitHub Desktop.
iptables is a command line utility for configuring Linux kernel firewall implemented within the Netfilter project. The term iptables is also commonly used to refer to this kernel-level firewall. It can be configured directly with iptables
#!/bin/sh
Installing Iptables
sudo apt-get update
sudo apt-get install iptables
Checking current Iptables status
sudo iptables -L
Example output:
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
Filters table has three chains (sets of rules).
• INPUT – This chain is used to control incoming packets to the server. You can block/allow connections based on port, protocol or source IP address.
• FORWARD – This chain is used to filter packets that are incoming to the server but are to be forwarded somewhere else.
• OUTPUT – This chain is used to filter packets that are going out from your server.
By default, iptables allows four targets:
1. ACCEPT - Accept the packet and stop processing rules in this chain.
2. REJECT - Reject the packet and notify the sender that we did so, and stop processing rules in this chain.
3. DROP - Silently ignore the packet, and stop processing rules in this chain.
4. LOG - Log the packet, and continue processing more rules in this chain. Allows the use of the --log-prefix and --log-level options.
Enabling traffic on localhost
sudo iptables -A INPUT -i lo -j ACCEPT
To accept all traffic on your loopback interface:
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A OUTPUT -o lo -j ACCEPT
Block an IP Address
sudo iptables -A INPUT -s 15.15.15.51 -j DROP
If I want to reject the connection instead, which will respond to the connection request with a “connection refused” error:
sudo iptables -A INPUT -s 15.15.15.51 -j REJECT
To allow all incoming SSH connections
sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -p tcp --sport 22 -m conntrack --ctstate ESTABLISHED -j ACCEPT
To allow incoming SSH connections from a specific IP address or subnet
sudo iptables -A INPUT -p tcp -s 15.15.15.0/24 --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -p tcp --sport 22 -m conntrack --ctstate ESTABLISHED -j ACCEPT
To remove all rules and start with a clean slate, the flush command
sudo sudo iptables -F
or
sudo sudo iptables -F --line-numbers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment