Securing Linux Servers!

Everything about Iptables - The Linux Firewall.


A Mega Thread 👇
Iptables is a command-line firewall utility for Linux. It monitors traffic from & to ur server using tables.
These tables contain sets of rules, called chains, that will filter incoming & outgoing data packets. PC: linuxkamarada
When someone tries to establish connection to and from your system iptables immediately looks for a rule in its list to match it and If it doesn’t find a matching one, it resorts to the default action (either DROP or Accept).
How to install Iptables ?

The Linux kernel comes with a built-in firewall, which is the ip_tables module. To manage it, we use the iptables command line tool.

To update/install it, just retrieve the iptables package:

# sudo apt-get install iptables
The original ip_tables module and iptables tool only handle IPv4. There are also ip6_tables and ip6tables for dealing with IPv6.

Run the following command to load ip6_tables module and list them -

# modprobe -v ip6_tables
# lsmod | grep .*tables
how iptables works ?

To understand how iptables works, we should understand - rules, chains, tables, targets, and default policy.
Rule -
A firewall rule specifies criteria for a packet (source/destination address/port/interface, protocol, etc.) & what to do with a packet that matches (such as block or allow).
A chain is a list of rules. iptables has its predefined chains and the user can also create their own chains.
Tables are sets of chains. iptables has four tables that are used at different times.

1. filter
2. nat
3. mangle
4. raw

Each table contains a number of built-in chains and may also contain user-defined chains. PC: phoenixnap
Filter Table -

This is d default table, it contains 3 built-in chains -

INPUT: queried when packets arrive at d machine

OUTPUT: queried when packets should leave d machine

FORWARD: queried when packets are to be routed through the machine
NAT Table -

This table is used to do NAT (Network Address Translation).
It contains 3 built-in chains -

MANGLE Table -

This table is used for specialized packet alteration, such as modifying the type of service (ToS) field.

It contains 5 built-in chains -

RAW Table -

This table is queried by iptables before the others and is used mainly for configuring exemptions from connection tracking

It contains 2 built-in chains -


chain names are case sensitive (e.g. INPUT, input and Input would be 3 different chains). Built-in chains names are always written in uppercase (e.g. INPUT).
When iptables rcvs a pkt, it looks for a rule that describes that pkt. Rules r examined in d order dey were added to d chain. If d pkt doesn't match d current rule, d next one in d chain is examined.Once matched, it does wat d rule says to do with d pkt, which is called d target
The target can be the name of a user-defined chain - in which case iptables continues processing the rules of that chain - or one of the following special values, which cause iptables to stop processing the current chain rules and take immediate action on the packet:
ACCEPT: let d pkt through

DROP: discard (delete, ignore) d pkt — in practice, it means to block d pkt

QUEUE: pass d pkt to a userspace process (outside d kernel) that will process d pkt

RETURN: stop traversing d current chain & resume at d next rule in d prev (calling) chain
Finally, if iptables reaches d end of a built-in chain and no rule that matches d packet was found, d target specified by the default policy of the chain determines the fate of the packet. Only one of those four special targets can be set as default policy for a built-in chain.
There is also the REJECT target, which is similar to DROP, but can be used only in filter chains rules.
Basic Commands -
Listing current rules -

# iptables -nvL

-L to list all the rules
-v verbose/detailed format
-n to produce numeric output of addresses & ports

All chains hv a default policy of ACCEPT & no rules b4hand, which means all incoming & outgoing traffic is allowed.
If the above output is different for you, maybe your system admin has already added rules for your system, or the Linux distribution you use has another default setting, or you are using firewalld, which creates its own chains.
The filter table is considered by default if no table is specified. To list rules of another table, add the -t parameter (or --table) followed by the table name.

For example:

# iptables -t nat -L
Also, if no chain is selected, all chains are listed.

To list rules of a specific chain only, add its name to the end of the command.

For example:

# iptables -t mangle -L FORWARD
Defining Chain Rules -

Defining a rule means appending it to the chain. To do this, you need to insert the -A option (Append) right after the iptables command, like so:

# iptables -A

It will alert iptables that you are adding new rules to a chain.
Then, you can combine the command with other options, such as:

-i (interface) - nw interface whose traffic you want to filter, such as eth0, lo etc.
-p (protocol) - nw protocol whr ur filtering process takes place. It can be either tcp, udp, icmp..
-s (source) - the addr from which traffic comes from. You can add a hostname or IP addr.
–dport (destination port) - the destination port number of a protocol, such as 22 (SSH), 443 (https), etc.
-j (target) — the target name (ACCEPT, DROP, RETURN).
If you want to use all of them, you must write the command in this order:

# iptables -A <chain> -i <interface> -p <protocol (tcp/udp) > -s <source> --dport <port no.> -j <target>
Here is a list of some common iptables options:

–A ––append – Add a rule to a chain (at the end).
–C ––check – Look for a rule that matches the chain’s requirements.
–D ––delete – Remove specified rules from a chain.
–F ––flush – Remove all rules.
–I ––insert – Add a rule to a chain at a given position.
–L ––list – Show all rules in a chain.
–N ––new–chain – Create a new chain.
–v ––verbose – Show more information when using a list option.
–X ––delete–chain – Delete the provided chain.
Enabling Traffic on Localhost -

# iptables -A INPUT -i lo -j ACCEPT

The command above will make sure that the connections between a database & a web application on the same machine are working properly. Now anything originating from your system will pass through your firewall.
Enabling Connections on HTTP/SSH/SSL Port -

We want http (port 80), https (port 443), and ssh (port 22) connections to work as usual.

# iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# iptables -A INPUT -p tcp --dport 443 -j ACCEPT
Filtering Packets Based on Source-

Iptables allows you to filter packets based on an IP addr or a range of IP addresses. You need to specify it after d -s option.

For e.g. to accept packets from, the cmd would be:

iptables -A INPUT -s -j ACCEPT
You can also reject packets from a specific IP address by replacing the ACCEPT target with DROP.

# iptables -A INPUT -s -j DROP
Drop a range of IP addresses -

If you want to drop packets from a range of IP addresses, you have to use the -m option and iprange module. Then, specify the IP address range with –src-range.

# iptables -A INPUT -m iprange --src-range DROP
Dropping all Other Traffic-

It is crucial to use the DROP target for all other traffic after defining –dport rules. This will prevent an unauthorized connection from accessing the server via other open ports.

To achieve this, simply type:

# iptables -A INPUT -j DROP
Deleting all current rules-

If you want to remove all rules and start with a clean slate, you can use the -F option (flush):

# iptables -F
Deleting all user-defined chains-

To delete all user-defined chains in the filter table, run:

# iptables -X

Even if you haven’t created any chains yourself, if firewalld is running, that command deletes chains created by firewalld.
Persisting Changes -

The iptables rules that we have created are saved in memory. That means we have to redefine them on reboot. To make these changes persistent after restarting the server, you can use this command:

# /sbin/iptables-save
Allowing Established and Related Incoming Connections -

To make 2way traffic work proprly we need to allow this so dat d server wil allow return traffic for outgoing connections initiated by d server itself.

iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
Allowing Established Outgoing Connections -

You may want to allow outgoing traffic of all established connections, which r typically d response to legitimate incoming connections.

# iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED -j ACCEPT
Allowing Internal Network to access External -

Assuming eth0 is your external network, and eth1 is your internal network, this will allow your internal to access the external:

# iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
Dropping Invalid Packets ->

Some network traffic packets get marked as invalid. Sometimes it can be useful to log this type of packet but often it is fine to drop them. Do so with this command:

# iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
Blocking Connections to a Network Interface -

To block connections from a specific IP address, e.g., to a specific network interface, e.g. eth1, use this command:

# iptables -A INPUT -i eth1 -s -j DROP
Setting the default policy for a chain -

To set d default policy for a chain, use d iptables -P command followed by the chain name and the target you would like to be d default policy.


# iptables -P FORWARD DROP
# iptables -P INPUT DROP
# iptables -P OUTPUT ACCEPT
Retweet the thread if you find it useful and follow me for more such content.


• • •

Missing some Tweet in this thread? You can try to force a refresh

Keep Current with Rakesh Jain

Rakesh Jain Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!


Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @devops_tech

13 Oct
Copying files and directories remotely.

Keeping Linux files and directories in sync.

Everything about "rsync"

A Thread 👇
What Is Rsync?

Rsync, or Remote Sync, is a fast, versatile and free command-line tool that lets you transfer and sync files and directories to local and remote destinations in an efficient and secure way. .
Why use Rsync?

When copying or moving large no. of files using tools like cp and mv may leave ur data in inconsistent state with part of it still in the original location and part of it in the target destination in case of any interruptions.
Read 29 tweets
9 Oct
These days we are hearing a lot about #web3.

What's that?

A short thread 👇
What was web1 or web?
The very first stage of development on the World Wide Web where only simple static websites used to exist.

Those were the times when Personal web pages (mostly static pages) used to be hosted on ISP-run web servers, or on free web hosting services.
What is web2?

Today's internet is all about web2. As per @Wikipedia Web 2.0 refers to websites that emphasize user-generated content, ease of use, participatory culture and interoperability for end users where websites and apps allow anyone to create content and share.
Read 5 tweets
9 Oct
Kubernetes security best practices in short -

A Thread 👇 PC: Threat Stack
1. Keep the Kubernetes cluster up to date.
2. Ensure That Only Authorized Images are Used in Your Environment
3. Limit Direct Access to Kubernetes Nodes
4. Create Administrative Boundaries between Resources
5. Keep Secrets Secret!
6. Define Resource Quota
7. Implement Network Segmentation
8. Apply Security Context to Your Pods and Containers
9. Restrict API access.
10. Restrict SSH access.
Read 6 tweets
9 Oct
Linux Networking Tools -

ss, nmap, dig, netcat, ping, tcpdump, socat, top, ethtool

A Thread 👇
SS -

ss command is a tool that is used for displaying network socket related information on a Linux system.
nmap -

Nmap is short for Network Mapper. It is an open-source Linux cmd-line tool that is used to scan IPs & ports in a nw & to detect installed apps. Nmap allows nw admins to find which devices r running on their nw, discover open ports & services, and detect vulnerabilities.
Read 12 tweets
7 Oct
SSL Decoded!

Everything you need to know about Secure Socket Layer.

A Thread 👇
What is SSL ?

It’s a protocol for encrypting and securing communications that take place on the Internet. It's now replaced by an updated protocol called TLS (Transport Layer Security) some time ago.
The main use case for SSL/TLS is securing communications between a client and a server, but it can also secure email, VoIP, and other communications over unsecured networks.
Read 23 tweets
7 Oct
I rarely use password login. And many folks out there even today aren't sure about ssh keys and their usage.

Everything about SSH Keys.

A Thread 👇
What is SSH?

SSH is a secure protocol used as the primary means of connecting to Linux servers remotely. It provides a text-based interface by spawning a remote shell. After connecting, all commands you type in your local terminal are sent to d remote server and executed there.
Today, the SSH protocol is widely used to login remotely from one system into another, and its strong encryption makes it ideal to carry out tasks such as issuing remote commands and remotely managing network infrastructure and other vital system components.
Read 27 tweets

Did Thread Reader help you today?

Support us! We are indie developers!

This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Too expensive? Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal Become our Patreon

Thank you for your support!

Follow Us on Twitter!