Table of Contents
, netfilter and iptables
2. Four tables of filter, nat, mangle and other rules
(1) Understand the architecture and functions of Netfilter and Iptables, and learn to control Netfilter behavior The structure of the Xtables table, so how does this Xtables table play a role in the packet routing of the kernel protocol stack?
5. IPTABLES writing rules
Home Operation and Maintenance Linux Operation and Maintenance Detailed graphic explanation of the principle of iptables in Linux

Detailed graphic explanation of the principle of iptables in Linux

Jul 26, 2017 pm 04:00 PM
iptables linux Detailed explanation

, netfilter and iptables


(1) Netfilter is a Linux 2.4 kernel firewall framework proposed by Rusty Russell. The framework is both simple and flexible and can implement security policies. Many features in the application, such as packet filtering, packet processing, address masquerading, transparent proxy, dynamic Network Address Translation (NAT), and filtering based on user and Media Access Control (MAC) addresses and state-based filtering, packet rate limiting, etc. These rules of Iptables/Netfilter can be flexibly combined to form a large number of functions, covering all aspects, all thanks to its excellent design ideas.

Netfilter is a packet processing module within the core layer of the Linux operating system. It has the following functions:

  • Network Address Translate

  • Data packet content modification

  • Packet filtering firewall

 (2) Data packets are formulated in the Netfilter platform Five mount points (Hook Point, we can understand it as a callback function point. When the data packet reaches these locations, our function will be actively called, giving us the opportunity to change their direction and content when the data packet is routed) , these 5 mount points are PRE_ROUTING, INPUT, OUTPUT, FORWARD, POST_ROUTING.

  (3) The rules set by Netfilter are stored in the kernel memory, and iptables is an application layer application that passes Netfilter The released interface is used to modify the XXtables (Netfilter configuration table) stored in the kernel memory. This XXtables consists of tables tables, chains chains, and rules rules. iptables is responsible for modifying this rule file at the application layer. A similar application is firewalld.

 


2. Four tables of filter, nat, mangle and other rules


(1) table has filter , nat, mangle and other rule tables;

 filter table

Mainly used to filter data packets and decide whether to release them based on specific rules The data packet (such as DROP, ACCEPT, REJECT, LOG). The kernel module corresponding to the filter table is iptable_filter, which contains three rule chains:

    • ##INPUT chain: INPUT targets those destinations It is a local packet

    • ##FORWARDChain: FORWARD filters all packets that are not generated locally and the destination is not local (that is, the local machine is only responsible for forwarding )

    • OUTPUT chain: OUTPUT is used to filter all locally generated packets

 

nat table

 

is mainly used to modify the IP address, port number and other information of the data packet (network address translation, such as SNAT, DNAT, MASQUERADE, REDIRECT). Packets belonging to a flow (data may be divided into multiple packets due to packet size restrictions) will only pass through this table once. If the first packet is allowed to be NAT or Masqueraded, then the remaining packets will automatically be subjected to the same operation, that is, the remaining packets will not pass through this table. The kernel module corresponding to the table is iptable_nat, which contains three chains <strong></strong>

    ##PREROUTING
      chain:
    • is used when the packet just reaches the firewall Change its destination address

      OUTPUT
    • Chain:
    • Change the destination address of locally generated packets

      POSTROUTING
    • Chain:
    • Change the source address of the packet just before it leaves the firewall

      ## 

      mangle Table

Mainly used to modify the TOS (Type Of Service, service type), TTL (Time To Live, life cycle) of the data packet and set the Mark mark for the data packet to achieve Applications such as Qos (Quality Of Service) adjustment and policy routing are not widely used because they require corresponding routing equipment support. Contains five rule chains - PREROUTING, POSTROUTING, INPUT, OUTPUT, FORWARD.  raw table

                                 around over through down is a new table added to iptables since version 1.2.9. It is mainly used to determine whether the data packet is tracked by the state. Mechanism processing. When matching data packets, the rules of the raw table take precedence over other tables. Contains two rule chains - OUTPUT, PREROUTING

<strong></strong>

(2) 4 different states of data packets and 4 types of tracked connections in iptables:

    • NEW: This package wants to start a connection (reconnect or redirect the connection)

    • RELATED: This package is a new connection established by an already established connection. For example: FTP data transmission connection is the connection RELATED from the control connection. --icmp-type 0 (ping response) is RELATED by --icmp-type 8 (ping request).

    • ESTABLISHED:As long as a data connection is sent and a response is received, a data connection changes from NEW to ESTABLISHED, and the status will continue to match the connection. subsequent packets.

    • INVALIDThe data packet cannot be identified to which connection it belongs or has no status such as memory overflow, and an ICMP message indicating that it does not belong to which connection is received. The error message should generally DROP any data in this state.


##Three, INPUT, FORWARD and other rules five chains and rules


(1) When processing various data packets, iptables provides 5 default rule chains according to different intervention timings of firewall rules. Understand these chains from the perspective of application time point:

    • INPUTChain: Rules in this chain are applied when a packet is received (inbound) for the firewall's native address.

    • #OUTPUTChain: When the firewall natively When sending packets outbound (outbound), the rules in this chain are applied.

    • ##FORWARDChain: When received, it needs to pass The firewall applies the rules in this chain when it sends (forwards) packets to other addresses.

    • #PREROUTING

      Chain: is processing the data packet Rules in this chain, such as DNAT, are applied before routing.

      #POSTROUTING
    • Chain:

      is operating on the data packet After routing, the rules in this chain, such as SNAT, are applied.

(2) Among them, the INPUT and OUTPUT chains are more commonly used in the "host firewall". That is, it is mainly aimed at the security control of data entering and exiting the server itself; and the FORWARD, PREROUTING, and POSTROUTING chains are more commonly used in "network firewalls", especially when the firewall server is used as a gateway.

4. Principles of Linux Packet Routing


(1) Understand the architecture and functions of Netfilter and Iptables, and learn to control Netfilter behavior The structure of the Xtables table, so how does this Xtables table play a role in the packet routing of the kernel protocol stack?


Work flow: The network port data packet is received by the underlying network card NIC. After being unpacked by the data link layer (removing the data link frame header), it enters the TCP/IP protocol stack (essentially a The kernel driver that processes network packets) and Netfilter are mixed in the packet processing process. The process of receiving, processing, and forwarding data packets constitutes a finite state vector machine. After passing through a series of kernel processing functions and Netfilter Hook points, it is finally forwarded or digested by the upper-layer application this time.

As shown in the picture:

From the above picture, we can summarize the following rules:

When a data packet enters the network card, the data packet first enters the

PREROUTING chain
    . In the PREROUTING chain we have the opportunity to modify the DestIP (destination IP) of the data packet, and then the kernel's "routing module" passes the "data packet" "Destination IP" and "routing table in the kernel" determine whether it needs to be forwarded (note that the DestIP of the data packet may have been modified by us at this time)
    • If the data packet is When entering the local machine (that is, the destination IP of the data packet is the network port IP of the local machine), the data packet will move downward along the diagram and reach the INPUT chain

      . After the packet reaches the INPUT chain, any process will - receive it
    • Programs running on this machine can also send data packets. These data packets go through the OUTPUT chain, and then reach the POSTROTING chain output(note that at this time The SrcIP of the data packet may have been modified by us)

    • If the data packet is to be forwarded (that is, the destination IP address is no longer in the current subnet), and the kernel allows forwarding , the data packet will move to the right, pass through the FORWARD chain, and then reach the POSTROUTING chain output (select the network port corresponding to the subnet to send out)

 When writing iptables rules, always keep this routing sequence diagram in mind, and flexibly configure the rules according to the different Hook points


5. IPTABLES writing rules


# command Format:

示 Example: <strong></strong>

    

1 iptables -I INPUT -s 0/0 -d 192.168.42.153 -p tcp -m multiport --dports 22,80,3306 -j ACCEPT   1 iptables -t filter -I INPUT -d 192.168.42.153 -p tcp --dport 80 -j ACCEPT

 1.[-t table name]

: Which table this rule operates on, you can use filter, nat, etc., if not specified, the default is filter<strong></strong><strong></strong>

    -A
      : Add a rule to the last line of the rule chain list
    • -I
    • : Insert a rule to the original rule at this position It will move backwards in sequence. If no number is specified, it will be 1
    • -D
    • : To delete a rule from the rule chain, either enter the complete rule or specify the rule number. Delete
    • -R
    • : Replace a rule. Rule replacement will not change the order, and the number must be specified.
    • -P
    • : Set the default action of a certain rule chain
    • -nL
    • :
    • -L

      , -n, view the list of currently running firewall rules

       
    • 2.
    chain name
: Specify which chain of the rule table, such as INPUT, OUPUT, FORWARD, PREROUTING, etc.

    [Rule number]
      : Insert Use when deleting or replacing rules,
    • --line-numbers

      display numbers

      [-i|o network card name]
    • : i is Specify which network card the data packet enters from, o specifies which network card the data packet outputs from
    • [-p protocol type]
    • : You can specify the protocol to which the rule applies , including tcp, udp and icmp, etc.
    • [-s source IP address]
    • : IP address or subnet address of the source host
    • [--sport source port number]
    • : Source port number of the IP of the packet
    • [-d destination IP address]
    • : The IP address or subnet address of the target host
    • [--dport target port number]
    • : The target port number of the IP of the data packet
    •  
    3.-m

:extend matches, this option is used to provide more matching parameters, such as: <strong></strong><strong></strong>


  • ##-m state --state ESTABLISHED,RELATED

    • -m tcp --dport 22

    • -m multiport --dports 80,8080

    • -m icmp --icmp- type 8

    •  
    • 4.<-j Action>

: Action to process the data packet, including ACCEPT , DROP, REJECT, etc.<strong></strong><strong></strong>


  • #ACCEPT
    • Allow the data packet to pass
    • DROP

      :
    • Drop the data packet directly without giving any response information
    • REJECT

      :
    • Reject the data packet to pass through, and will send a response message to the data sending end if necessary.
    • SNAT

      :
    • Source address translation. After entering the route at the routing level and before exiting the local network stack, the source address is rewritten, the destination address remains unchanged, and a NAT table entry is established on the local machine. When the data is returned, the destination address data is rewritten as data according to the NAT table and sent out. source address and sent to the host. Solve the problem of intranet users using the same public address to access the Internet.
    • MASQUERADE is a special form of SNAT, suitable for IPs that change temporarily like adsl

    • DNAT:Destination address translation. Contrary to SNAT, before the IP packet passes through the route, the destination address is re-modified, and the source address remains unchanged. A NAT entry is established on the local machine. When the data is returned, the source address is modified according to the NAT table to the destination address when the data was sent. Concurrently to the remote host. The real address of the backend server can be hidden. (Thanks to the netizen for pointing out that this place was written backwards with SNAT)
      REDIRECT: It is a special form of DNAT that forwards network packets to the local host (regardless of the target address specified in the IP header) What), it is convenient to do port forwarding on this machine.

    • LOG: Record log information in the /var/log/messages file and then pass the packet to the next rule

## ​​Except for the last

LOG, after the first three rules match the data packet, the data packet will not continue to match, so the order of writing the rules Extremely critical.

The above is the detailed content of Detailed graphic explanation of the principle of iptables in Linux. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use docker desktop How to use docker desktop Apr 15, 2025 am 11:45 AM

How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

Difference between centos and ubuntu Difference between centos and ubuntu Apr 14, 2025 pm 09:09 PM

The key differences between CentOS and Ubuntu are: origin (CentOS originates from Red Hat, for enterprises; Ubuntu originates from Debian, for individuals), package management (CentOS uses yum, focusing on stability; Ubuntu uses apt, for high update frequency), support cycle (CentOS provides 10 years of support, Ubuntu provides 5 years of LTS support), community support (CentOS focuses on stability, Ubuntu provides a wide range of tutorials and documents), uses (CentOS is biased towards servers, Ubuntu is suitable for servers and desktops), other differences include installation simplicity (CentOS is thin)

What to do if the docker image fails What to do if the docker image fails Apr 15, 2025 am 11:21 AM

Troubleshooting steps for failed Docker image build: Check Dockerfile syntax and dependency version. Check if the build context contains the required source code and dependencies. View the build log for error details. Use the --target option to build a hierarchical phase to identify failure points. Make sure to use the latest version of Docker engine. Build the image with --t [image-name]:debug mode to debug the problem. Check disk space and make sure it is sufficient. Disable SELinux to prevent interference with the build process. Ask community platforms for help, provide Dockerfiles and build log descriptions for more specific suggestions.

How to view the docker process How to view the docker process Apr 15, 2025 am 11:48 AM

Docker process viewing method: 1. Docker CLI command: docker ps; 2. Systemd CLI command: systemctl status docker; 3. Docker Compose CLI command: docker-compose ps; 4. Process Explorer (Windows); 5. /proc directory (Linux).

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

How to switch Chinese mode with vscode How to switch Chinese mode with vscode Apr 15, 2025 pm 11:39 PM

VS Code To switch Chinese mode: Open the settings interface (Windows/Linux: Ctrl, macOS: Cmd,) Search for "Editor: Language" settings Select "Chinese" in the drop-down menu Save settings and restart VS Code

See all articles