search
HomeBackend DevelopmentPHP TutorialLinux firewall iptables tutorial for beginners

Iptables is an extremely flexible firewall tool specially built for Linux operating systems. For Linux geeks and system administrators, iptables is very useful. This article will show you how to configure the most versatile Linux firewall.

About iptables

Iptables is a command line based firewall tool that uses rule chains to allow/block network traffic. When a network connection is attempted to be established on your system, iptables looks for matching rules. If not found, iptables will take default action on it.
Almost all Linux distributions come with iptables pre-installed. The command to update/install iptables in Ubuntu/Debian is:

sudo apt-get install iptables

Some existing graphical interface software can also replace iptables, such as Firestarter. But iptables is not difficult to use. Be especially careful when configuring iptables rules, especially when you log in to the server remotely. Because an error at this time may cause you to permanently lose connection with the server, and you must go to the server to solve it.

Types of Iptables rule chains

Iptables rule chains are divided into three types: input, forwarding and output.

Input - This chain is used to filter connections whose destination address is the local machine. For example, if a user attempts to log into your PC/server using SSH, iptables will first match their IP address and port to the iptables input chain rules.

Forwarding - This chain is used to filter connections where both the destination address and the source address are not local. For example, most of the data received by the router needs to be forwarded to other hosts. If your system does not have router-like features enabled, such as NATing, you do not need to use this chain.
There is a safe and reliable way to detect whether your system requires forwarding chains:

iptables -L -v

Linux firewall iptables tutorial for beginners

The picture above is a screenshot of a server that has been running for a few weeks. This server does not place any restrictions on input and output. As can be seen, the input chain and output chain have processed 11GB and 17GB of data respectively, while the forwarding chain has not processed any data. This is because this server does not have a router-like forwarding function enabled.


Output - This chain is used to filter connections whose source address is the local machine. For example, when you try to ping howtogeek.com, iptables will check the output chain for rules related to ping and howtogeek.com, and then decide whether to allow or deny your connection request.

Note: When pinging an external host, it will appear as if only the output chain is working. But remember, the data returned by the external host needs to be filtered through the input chain. When configuring iptables rules, keep in mind that many protocols require bidirectional communication, so you need to configure both the input chain and the output chain. When people configure SSH, they often forget to configure it on both the input and output chains.

Default behavior of chains

Before configuring specific rules, maybe you want to configure the default behavior of these chains. In other words, what do you want iptables to do when it cannot match an existing rule?
You can run the following command to display the current iptables default action for unmatched connections:

iptables -L

Linux firewall iptables tutorial for beginners

As shown above, we can use grep to make the output more concise . In the screenshot above, all chains accept all connections by default.
Normally, you will want your system to receive all network data by default. This setting is also the default configuration of iptables. The configuration command to receive network connections is:

iptables --policy INPUT ACCEPT iptables --policy OUTPUT ACCEPT iptables --policy FORWARD ACCEPT

You can also add some commands to filter specific IP addresses or port numbers while using the default configuration. We introduce these commands later in this article.
If you want to deny all network connections by default and then add allowed IP addresses or port numbers on top of it, you can change ACCEPT in the default configuration to DROP, as shown in the image below. This is extremely useful for servers containing sensitive data. Usually these servers only allow specific IP addresses to access them.

iptables --policy INPUT DROP iptables --policy OUTPUT DROP iptables --policy FORWARD DROP

Configuration of specific connections

Let’s take a look at how to set a specific IP address or port. This article mainly introduces the three most basic and common settings.

Accept – accept all data.

Drop – Drop data. Application scenario: When you don’t want the source address of the data to be aware of the existence of your system (the best way to handle it).

Reject – Does not allow the connection to be established, but returns an error response. Application scenario: When you don't want a certain IP address to access your system, but you want them to know that your firewall blocks their access.

为了直观的区分上述三种情况,我们使用一台PC来ping一台配置了iptables的Linux电脑:

Linux firewall iptables tutorial for beginners

允许或阻止特定的连接

在配置完基本的规则链之后,你就可以配置iptables来允许或者阻止特定的IP地址或者端口。
注意:在这些例子中,我们使用iptables -A将额外的规则添加到现存的链中。Iptables在执行匹配的时候,会从列表的顶端开始搜索。你可以使用iptables -I [chain] [number]将新的规则插入到列表的指定位置。

来自同一IP地址的连接
下面这个例子展示了如何阻止来自IP地址为10.10.10.10的所有连接。

iptables -A INPUT -s 10.10.10.10 -j DROP

来自一组IP地址的连接
下面这个例子展示了如何阻止来自子网10.10.10.0/24内的任意IP地址的连接。你可以使用子网掩码或者标准的/符号来标示一个子网:

iptables -A INPUT -s 10.10.10.0/24 -j DROP

iptables -A INPUT -s 10.10.10.0/255.255.255.0 -j DROP

特定端口的连接
这个例子展示了如何阻止来自10.10.10.10的SSH连接。

iptables -A INPUT -p tcp --dport ssh -s 10.10.10.10 -j DROP

你可以将“ssh”替换成其它任何协议或者端口号。上述命令中的-p tcp告诉iptables连接使用的是何种协议。

下面这个例子展示了如何阻止来自任意IP地址的SSH连接。

iptables -A INPUT -p tcp --dport ssh -j DROP

连接状态

我们之前提到过,许多协议均需要双向通信。例如,如果你打算允许SSH连接,你必须同时配置输入和输出链。但是,如果你只想允许来自外部的SSH请求,那该怎么做?
下面这个例子展示了如何允许源IP地址为10.10.10.10同时阻止目的地址为10.10.10.10的SSH连接:

iptables -A INPUT -p tcp --dport ssh -s 10.10.10.10 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp --sport 22 -d 10.10.10.10 -m state --state ESTABLISHED -j ACCEPT

保存更改

上述方法对iptables规则作出的改变是临时的。如果你想永久保存这些更改,你需要运行额外的命令(不同Linux发行版下的保存命令也不相同):

Ubuntu:

sudo /sbin/iptables-save

Red Hat / CentOS:

/sbin/service iptables save

或者

/etc/init.d/iptables save

其它命令

列出iptables的当前配置:

iptables -L

使用-v选项将显示数据包和字节信息;使用-n选项将以数字形式列出信息,即不将IP地址解析为域名。
换句话讲,主机名,协议和网络都以数字的形式列出。

清除当前所有的配置规则:

iptables -F

原文 The Beginner’s Guide to iptables, the Linux Firewall


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use