Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction and usage of Iptables

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "introduction and use of Iptables". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Connection tracking (conntrack)

Connection tracking is the foundation of many network applications. For example, Kubernetes Service, ServiceMesh sidecar, software layer 4 load balancer LVS/IPVS, Docker network, OVS, iptables host firewall, and so on, all rely on connection tracking.

Connection tracking, as the name implies, tracks (and records) the status of the connection. For example, figure 1.1 shows a Linux machine with IP address 10.1.1.2, and we can see that there are three connections on this machine:

Connection for machines to access external HTTP services (destination port 80)

External access to FTP services within the machine (destination port 21)

Connection for machines to access external DNS services (destination port 53)

What connection tracking does is discover and track the status of these connections, including:

The tuple (tuple) information is extracted from the data packet to identify the data stream (flow) and the corresponding connection (connection).

Maintains a state database (conntrack table) for all connections, such as connection creation time, number of packets sent, number of bytes sent, and so on.

Reclaim expired connections (GC).

Provide services for higher-level functions, such as NAT.

It should be noted that the concept of "connection" in connection tracking is not exactly the same as the "connection-oriented" (connection oriented) "connection" in the TCP/IP protocol. To put it simply:

In the TCP/IP protocol, connectivity is a four-layer (Layer 4) concept. TCP is connection-oriented, or connection-oriented (connection oriented). Packets sent out require a peer-to-peer reply (ACK) and have a retransmission mechanism. UDP is connectionless, and the packets sent do not require a peer-to-peer reply and there is no retransmission mechanism.

In conntrack (CT), a data stream (flow) defined by a tuple (tuple) represents a connection. You will see later that UDP and even layer 3 protocols such as ICMP have connection records in CT, but not all protocols are tracked by connections.

Netfilter

Connection tracking for Linux is implemented in Netfilter.

Netfilter is a framework for controlling, modifying, and filtering (manipulation and filtering) packets in the Linux kernel. It sets several hook points in the kernel protocol stack to intercept, filter or otherwise process data packets.

When it comes to connection tracking (conntrack), you may first think that Netfilter,Netfilter is just a connection tracking implementation in the Linux kernel. In other words, as long as you have the hook capability, you can intercept every packet entering and leaving the host, and you can implement a set of connection tracking on this basis.

Cloud native network solution Cilium implements such an independent connection tracking and NAT mechanism in version 1.7.4 + (full functionality requires Kernel 4.19 +). The basic principles are as follows:

Implement packet interception function based on BPF hook (equivalent to hook mechanism in netfilter)

Implement a new set of conntrack and NAT on the basis of BPF hook, so even if Netfilter is uninstalled, it will not affect Cilium's support for Kubernetes ClusterIP, NodePort, ExternalIPs, and LoadBalancer. Because this connection tracking mechanism is independent of Netfilter, its conntrack and NAT information is not stored in the kernel's (that is, Netfilter's) conntrack table and NAT table. So you can't see regular conntrack/netstats/ss/lsof and other tools, so use Cilium commands, such as:

$cilium bpf nat list$ cilium bpf ct list globalIptables

Iptables is a user space tool for configuring Netfilter filtering. Netfilter is the real security framework (framework) of firewalls, and netfilter is located in kernel space. Iptables is actually a command-line tool located in user space, and we use this tool to manipulate the real framework. Iptable processes packets according to the methods defined by the rules, such as accept, reject, drop, and so on.

For example, when the client accesses the server's web service, the client sends a message to the network card, and the tcp/ip protocol stack is part of the kernel, so the client's information is transmitted to the web service in user space through the kernel's TCP protocol. At this time, the destination of the client message is on the socket (IP:Port) that the web service listens to. When the web service needs to respond to client requests, The destination of the response message sent by the web service is the client. At this time, the IP and port monitored by the web service become the origin. As we said, netfilter is the real firewall and it is a part of the kernel. Therefore, if we want the firewall to achieve the purpose of "fire prevention", we need to set up checkpoints in the kernel. All incoming and outgoing messages have to pass through these checkpoints. Those who meet the conditions for release can be released, while those who meet the conditions for obstruction need to be stopped.

Iptables contains 4 tables and 5 chains. The table is distinguished according to the operation of the packet (filtering, NAT, etc.), the chain is distinguished according to different Hook points, and the table and the chain are actually the two dimensions of netfilter.

The four tables of iptables are filter,mangle,nat,raw, and the default table is filter.

Filter table: used to filter packets, specific rules that determine how to handle a packet.

Nat table: mainly used to modify the IP address and port number information of the packet.

Mangle table: mainly used to modify the service type and life cycle of data packets, set tags for packets, realize traffic shaping, policy routing, and so on.

Raw table: mainly used to determine whether to trace the status of the packet.

The five strands of iptables are PREROUTING,INPUT,FORWARD,OUTPUT,POSTROUTING.

Input chain: when a packet is received that accesses the local address, the rules in this chain are applied.

Output chain: when a packet is sent out locally, the rules in this chain are applied.

Forward chain: when you receive a packet that needs to be forwarded to another address, the rules in this chain will be applied. Note that if you need to achieve forward forwarding, you need to enable the ip_forward function in the Linux kernel.

Prerouting chain: the rules in this chain are applied before routing a packet.

Postrouting chain: after the packet is routed, the rules in this chain are applied.

The correspondence between the table and the chain is shown in the following figure:

We can imagine the flow of messages in some common scenarios:

Message to a process on the local machine: PREROUTING-> INPUT.

Messages forwarded by this machine: PREROUTING-> FORWARD-> POSTROUTING.

A message (usually a response message) is sent by a process on this machine: OUTPUT-> POSTROUTING.

We can summarize the process of packets passing through the firewall into the following figure:

Query rules

-t: table name

-n: IP address is not resolved

-v: displays the counter information, the number and size of packets

-x: the option indicates the exact value of the display counter

-- line-numbers: displays the serial number of the rule (abbreviated as-- line)

-L: chain name

# iptables-t filter-nvxL DOCKER-- lineChain DOCKER (1 references) num pkts bytes target prot opt in out source destination1 5076 321478 ACCEPT tcp -! docker0 docker0 0.0.0.0 ACCEPT tcp 0 172.17.0.2 tcp dpt:84432 37233 54082508 ACCEPT tcp -! docker0 docker0 0.0.0.0 ACCEPT tcp 0 172.17.0.2 tcp dpt:223 1712 255195 ACCEPT tcp -! docker0 docker0 0.0.0.0 tcp dpt:90004 0 172.17.0.3 tcp dpt:90004 00 ACCEPT tcp -! docker0 docker0 0.0.0.0 tcp dpt:80005 40224 6343104 ACCEPT tcp -! docker0 docker0 0.0.0.0 docker0 docker0 0 172.17.0.4 tcp dpt:34436 21034 2227009 ACCEPT tcp -! docker0 docker0 0.0.0.0 ACCEPT tcp 0 172.17.0.5 tcp dpt:33067 58 5459 ACCEPT tcp -! docker0 docker0 0.0.0.0 ACCEPT tcp 0 172.17.0.6 tcp dpt:808 826 70081 ACCEPT tcp -! docker0 docker0 0.0.0.0 tcp dpt:330610 0 172.17.0.6 tcp dpt:4439 10306905 1063612492 ACCEPT tcp -! docker0 docker0 0.0.0.0 tcp dpt:330610 159775 12297727 ACCEPT tcp- ! docker0 docker0 0.0.0.0 tcp dpt:11111 0 172.17.0.7 increase rule

Add a rule to the end of the specified chain of the specified table. The-An option means that the rule is added at the end of the corresponding chain, and when the-t option is omitted, it indicates the default operation of the rule in the filter table:

Command syntax: iptables-t table name-A chain name matching condition-j action example: iptables-t filter-An INPUT-s 192.168.1.146-j DROP

Add a rule at the beginning of the specified chain of the specified table, and-I selection means to add a rule at the beginning of the corresponding chain:

Command syntax: iptables-t table name-I chain name matching condition-j action example: iptables-t filter-I INPUT-s 192.168.1.146-j ACCEPT

Adds a rule at the specified position in the specified chain of the specified table:

Command syntax: iptables-t table name-I chain name rule ordinal matching condition-j action example: iptables-t filter-I INPUT 5-s 192.168.1.146-j REJECT delete rule

Deletes the rule according to the rule number, deletes the specified rule of the specified chain of the specified table, and the-D option deletes the rule in the corresponding chain. The example deletes the rule with the serial number 3 in the INPUT chain in the filter table. :

Command syntax: iptables-t table name-D chain name rule serial number example: iptables-t filter-D INPUT 3

Delete rules according to specific matching conditions and actions, and delete the specified rules of the specified chain of the specified table. The example removes the rule in the filter table where the source address is 192.168.1.146 and the action is DROP in the INPUT chain. :

Command syntax: iptables-t table name-D chain name matching condition-j action example: iptables-t filter-D INPUT-s 192.168.1.146-j DROP

Deletes all rules in the specified chain of the specified table, and the-F option empties the rules in the corresponding chain:

Command syntax: iptables-t table name-F chain name example: iptables-t filter-F INPUT modification rule

Modify the specified rule of the specified chain in the specified table. The-R option means to modify the rule in the corresponding chain. Use the-R option to specify both the corresponding chain and the corresponding sequence number of the rule, and the original matching condition in the rule cannot be omitted. The example indicates that the third rule of the INPUT chain in the filter table is modified, and the action of this rule is changed to ACCEPT.-s 192.168.1.146 is the original matching condition in this rule. If this matching condition is omitted, the source address in the modified rule may become 0.0.0.0max 0:

Command syntax: iptables-t table name-R chain name rule ordinal rule original matching condition-j action example: iptables-t filter-R INPUT 3-s 192.168.1.146-j ACCEPT

Sets the default policy (default action) for the specified chain of the specified table:

Command syntax: iptables-t table name-P chain name action example: iptables-t filter-P FORWARD ACCEPT save rule mode 1

After we have made changes to the rules, if we want the changes to take effect permanently, we must save the rules using the following command:

Service iptables save

Of course, if you mismanipulate the rule but don't save it, then when you restart iptables with the service iptables restart command, the rule will go back to the last time the / etc/sysconfig/iptables file was saved.

In centos7, instead of using init-style scripts to start services, we use unit files, so commands like service iptables start can no longer be used in centos7, so service iptables save cannot be executed. At the same time, in centos7, firewall is used instead of the original iptables service, but don't worry, we just need to install iptables and iptables-services through the yum source (iptables is usually installed by default However, iptables-services is generally not installed by default in centos7). After installing iptables-services in centos7, you can save the rules through the service iptables save command as in centos6, and the rules are also saved in the / etc/sysconfig/iptables file. Here are the steps to configure iptables-service in centos7:

# install iptables-serviceyum install-y iptables-services# after configuring the yum source, stop firewalldsystemctl stop firewalld#, prohibit firewalld from automatically starting systemctl disable firewalld#, start iptablessystemctl start iptables#, set iptables to boot automatically, and then you can control the iptables service systemctl enable iptables through iptables-service

The above configuration process takes only one time, and the iptables rules can be saved later using the service iptables save command in centos7.

Mode two

Another way to save iptables rules is to use the iptables-save command. Using iptables-save does not save the current iptables rule, but you can output the current iptables rule to the screen in "saved format".

So, we can use the iptables-save command, combined with redirection, to redirect the rules to the / etc/sysconfig/iptables file.

Iptables-save > / etc/sysconfig/iptables loading rules

We can also reload the rules in / etc/sysconfig/iptables as the current iptables rules, but note that changes that are not saved in the / etc/sysconfig/iptables file will be lost or overwritten.

Rules can be overloaded from a specified file using the iptables-restore command, as shown in the following example

Iptables-restore < / etc/sysconfig/iptables matching condition

When there are multiple matching conditions in the rule, there is a "and" relationship between the multiple conditions by default, that is, the message must meet all the conditions at the same time in order to be matched by the rule.

-s is used to match the source address of the message. Multiple source addresses can be specified at the same time. Each IP is separated by a comma, or it can be specified as a network segment.

# example is as follows: iptables-t filter-I INPUT-s 192.168.1.111192.168.1.118-j DROPiptables-t filter-I INPUT-s 192.168.1.0 ACCEPTiptables-t filter-I INPUT!-s 192.168.1.0 max 24-j ACCEPT

-d is used to match the destination address of the message. Multiple destination addresses can be specified at the same time, with each IP separated by a comma or as a network segment.

# example is as follows: iptables-t filter-I OUTPUT-d 192.168.1.111192.168.1.118-j DROPiptables-t filter-I INPUT-d 192.168.1.0 ACCEPTiptables-t filter-I INPUT!-d 192.168.1.0 ACCEPT 24-j ACCEPT

-p is used to match the protocol types of messages, such as tcp, udp, udplite, icmp, esp, ah, sctp, etc. (icmpv6 and mh are also supported in centos7).

# example is as follows: iptables-t filter-I INPUT-p tcp-s 192.168.1.146-j ACCEPTiptables-t filter-I INPUT!-p udp-s 192.168.1.146-j ACCEPT

-I is used to match the interface from which the message flows into the machine. Since the matching condition is only used to match the network card from which the message flows, this option cannot be used in the OUTPUT chain and the POSTROUTING chain.

# example is as follows: iptables-t filter-I INPUT-p icmp-I eth5-j DROPiptables-t filter-I INPUT-p icmp!-I eth5-j DROP

-o is used to match which network card interface the message will flow out of the local machine, and the matching condition is only used to match the network card from which the message flows out, so this option cannot be used in the INPUT chain and the PREROUTING chain.

# example is as follows: iptables-t filter-I OUTPUT-p icmp-o eth5-j DROPiptables-t filter-I OUTPUT-p icmp!-o eth5-j DROP extension matching condition tcp expansion module

Common extension matching conditions are as follows:

-sport: the source port used to match tcp protocol messages. You can use colons to specify a continuous port range.

-dport: the destination port used to match tcp protocol messages. You can use colons to specify a contiguous port range.

-tcp-flags: the flag bit used to match the tcp header of the message.

-syn: the request message used to match the new connection of tcp, which is equivalent to using-tcp-flags SYN,RST,ACK,FIN SYN.

Note that-p tcp does not conflict with-m tcp,-p is used to match the message protocol,-m is used to specify the name of the extension module, which happens to be also called tcp.

# example: iptables-t filter-I OUTPUT-d 192.168.1.146-p tcp-m tcp-- sport 22-j REJECTiptables-t filter-I INPUT-s 192.168.1.146-p tcp-m tcp-- dport 22:25-j REJECTiptables-t filter-I INPUT-s 192.168.1.146-p tcp-m tcp-dport: 22-j REJECTiptables-t filter-I INPUT-s 192.168.1.146-p tcp-m tcp-dport 80: -j REJECTiptables-t filter-I OUTPUT-d 192.168.1.146-p tcp- m tcp!-- sport 22-j ACCEPTiptables-t filter-I INPUT-p tcp- m tcp--dport 22-- tcp-flags SYN ACK,FIN,RST,URG,PSH SYN-j REJECTiptables-t filter-I OUTPUT-p tcp- m tcp--sport 22-- tcp-flags SYN,ACK,FIN,RST,URG,PSH SYN,ACK-j REJECTiptables-t filter-I INPUT-p tcp- m tcp--dport 22-- tcp-flags ALL SYN-j REJECTiptables-t filter-I OUTPUT-p tcp- m tcp--sport 22-tcp-flags ALL SYN,ACK-j REJECTiptables-t filter-I INPUT-p tcp- m tcp--dport 22-syn-j REJECTudp expansion module

Common extended matching criteria:

-sport: matches the source address of the udp message.

-dport: matches the destination address of the udp message.

# example iptables-t filter-I INPUT-p udp-m udp-- dport 137j ACCEPTiptables-t filter-I INPUT-p udp-m udp-- dport 137rig 157-j ACCEPTicmp expansion module

Common extended matching criteria:

-icmp-type: matches the specific type of icmp message.

# example iptables-t filter-I INPUT-p icmp- m icmp--icmp-type 8ap0-j REJECTiptables-t filter-I INPUT-p icmp--icmp-type 8-j REJECTiptables-t filter-I OUTPUT-p icmp- m icmp--icmp-type 0ram 0-j REJECTiptables-t filter-I OUTPUT-p icmp--icmp-type 0-j REJECTiptables-t filter-I INPUT-p icmp--icmp-type echo-request-j REJECTmultiport expansion module

Common extension matching conditions are as follows:

-p tcp-m multiport-sports is used to match the source port of a message. Multiple discrete port numbers can be specified, separated by "commas".

-p udp-m multiport-dports is used to match the destination port of the message. Multiple discrete port numbers can be specified, separated by "commas".

# example is as follows: iptables-t filter-I OUTPUT-d 192.168.1.146-p udp-m multiport-- sports 137138-j REJECTiptables-t filter-I INPUT-s 192.168.1.146-p tcp-m multiport-dports 22pl 80-j REJECTiptables-t filter-I INPUT-s 192.168.1.146-p tcp-m multiport!-dports 22Magi 80-j REJECTiptables-t filter-I INPUT-s 192.168.1.146-p tcp-m multiport-dports 80:88- J REJECTiptables-t filter-I INPUT-s 192.168.1.146-p tcp-m multiport-- dports 22nd 80Rd 88-j REJECTiprange module

The extension matching criteria included are as follows:

-src-range: specifies a contiguous source address range.

-dst-range: specifies a contiguous range of destination addresses.

# example iptables-t filter-I INPUT-m iprange-- src-range 192.168.1.127-192.168.1.146-j DROPiptables-t filter-I OUTPUT-m iprange-- dst-range 192.168.1.127-192.168.1.146-j DROPiptables-t filter-I INPUT-m iprange!-- src-range 192.168.1.127-192.168.1.146-j DROPstring module

Common extension matching conditions are as follows:

-algo: specify the corresponding matching algorithm. Available algorithms are bm and kmp. This option is required.

-string: specifies the string to match

What we want to achieve is that if the message contains the "OOXX" character, we refuse to allow the message to enter the machine:

# example iptables-t filter-I INPUT-m string-- algo bm-- string "OOXX"-j REJECT

Time module

Common extension matching conditions are as follows:

-timestart: used to specify the start time of the time range, which cannot be reversed.

-timestop: used to specify the end time of the time range, which cannot be reversed.

-weekdays: used to specify the "day of the week", which can be reversed.

-monthdays: used to specify the "number", which can be reversed.

-datestart: used to specify the start date of the date range, which cannot be reversed.

-datestop: used to specify the end time of the date range, which cannot be reversed.

# example iptables-t filter-I OUTPUT-p tcp-- dport 80-m time-- timestart 09:00:00-timestop 19:00:00-j REJECTiptables-t filter-I OUTPUT-p tcp-- dport 443-m time-- timestart 09:00:00-timestop 19:00:00-j REJECTiptables-t filter-I OUTPUT-p tcp-- dport 80-m time-weekdays 6Jud7-j REJECTiptables-t filter-I OUTPUT-p tcp-dport 80-m time-monthdays 2222 23- J REJECTiptables-t filter-I OUTPUT-p tcp-- dport 80-m time!-- monthdays 22 REJECTiptables 23-j REJECTiptables-t filter-I OUTPUT-p tcp-- dport 80-m time-- timestart 09:00:00-- timestop 18:00:00-- weekdays 6 weekdays 7-j REJECTiptables-t filter-I OUTPUT-p tcp-- dport 80-m time-weekdays 5-monthdays 22 232525 27728-t REJECTiptables-t filter-I OUTPUT-p tcp-- dport 80-m time-datestart 2017-12- 24-- datestop 2017-12-27-j REJECTconnlimit module

Common extension matching conditions are as follows:

-connlimit-above: when this option is used alone, it limits the number of links per IP.

-connlimit-mask: this option cannot be used alone. When using the-connlimit-above option, with this option, you can limit the number of connections to "a certain number of IP in a certain type of IP segment". If you don't understand, you can refer to the detailed explanation above.

# example iptables-I INPUT-p tcp-- dport 22-m connlimit--connlimit-above 2-j REJECTiptables-I INPUT-p tcp-- dport 22-m connlimit--connlimit-above 20-- connlimit-mask 24-j REJECTiptables-I INPUT-p tcp-- dport 22-m connlimit--connlimit-above 10-- connlimit-mask 27-j REJECTlimit module

The connlimit module limits the number of connections, while the limit module limits the packet arrival rate. In plain English, if I want to limit the number of packets that flow in per unit time, I can use the limit module. We can limit it in seconds, or in minutes, hours, and days. Common extension matching conditions are as follows:

-limit-burst: analogous to the token bucket algorithm, this option specifies the maximum number of tokens in the token bucket.

-limit: analogous to the token bucket algorithm, this option is used to specify the frequency at which new tokens are generated in the token bucket. Available time units are second, minute, hour, day.

The example indicates that when an external host is restricted from performing ping operations on this machine, the machine will release at most one ping packet every 6 seconds.

# example, note that the following two rules need to be used together. Up to 3 tokens can be stored in the # token bucket, generating 10 tokens per minute (that is, one token in 6 seconds). Iptables-t filter-I INPUT-p icmp-m limit--limit-burst 3-- limit 10/minute-j ACCEPT# discards the icmp packet iptables-t filter-An INPUT-p icmp-j REJECTstate expansion module by default

When we visit the web page of a website through http's url, the client initiates a request to port 80 of the server, and the server responds to our request through port 80. So, as the client, we should release port 80 as a client, so that the server responds to our message and can enter the client host, so we release port 80 on the client side. When we connect to a server remotely through the ssh tool, the client initiates a request to port 22 of the server, and the server responds to our request through port 22, so we should release all ports 22 so that the response request of the remote host can pass through the firewall, but, as a client, if we do not initiate a request to port 80 actively There is no active request to port 22, so when other hosts send data to us through port 80 or port 22, can we receive it? It should be possible, because we have released ports 80 and 22 in order to receive response messages from http and ssh, so whether they are "responding" to our messages or "actively sending" messages to us, they should all be able to pass through these two ports, so think about it carefully, is this not too safe? At this point, the state extension module comes in handy.

For the connection of the state module, the messages in the connection can be divided into five states, which are:

NEW: the status of the first packet in a connection is NEW. We can understand that the status of the first packet in a new connection is NEW.

ESTABLISHED: we can think of the state of the package behind the NEW status package as ESTABLISHED, indicating that the connection has been established.

RELATED: literally understand the translation of RELATED into relations, but this is still not easy to understand. Let's give an example. For example, the FTP service, the FTP server will set up two processes, a command process and a data process. The command process is responsible for the command transfer between the server and the client (we can think of this transfer process as a so-called "connection" in state, temporarily called "command connection"). The data process is responsible for the data transfer between the server and the client (we temporarily call this process "data connection"). However, the specific data transmitted is controlled by the command, so the message in the "data connection" has a "relationship" with the "command connection". In that case, the messages in the data connection may be the RELATED status, because they are related to the messages in the Command connection. (note: if you want to trace the connection of ftp, you need to load the corresponding kernel module nf_conntrack_ftp separately. If you want to load automatically, you can configure / etc/sysconfig/iptables-config file)

INVALID: if a packet cannot be identified, or if the packet does not have any status, then the status of the packet is INVALID, and we can actively block messages with the status of INVALID.

UNTRACKED: when the status of the message is untracked, it indicates that the message is not being tracked. When the status of the message is Untracked, it usually means that the relevant connection cannot be found.

The problem in the example just now can be solved by using the state expansion module. We only need to release the message with the status of ESTABLISHED, because if the status of the message is ESTABLISHED, then the message must be a response to the message sent before. This means that only the message responding to us can pass through the firewall, and if it is a new message sent by someone else, it cannot pass through the firewall:

Iptables-t filter-I INPUT-m state-- state ESTABLISHED-j ACCEPTmangle table

The main function of the mangle table is to modify some flag bits of the packet according to the rules so that other rules or programs can use this flag to filter or route the packet. The mangle table has the following three main operations:

TOS: the service type domain used to set or change the packet. This is often used to set policies such as how packets on the network are routed. Note that this operation is not perfect and sometimes does not get what you want. It doesn't work on Internet yet, and many routers don't notice this domain value. In other words, do not set up packets destined for Internet unless you plan to rely on TOS for routing, such as iproute2.

TTL: to change the lifetime domain of packets, we can make all packets have only one special TTL. There is a good reason for it to exist, that is, we can deceive some ISP. Why deceive them? Because they don't want us to share a connection. Those ISP will look up whether a single computer uses a different TTL and use it as a flag to determine whether the connection is shared.

MARK is used to set special tags for packages. Iproute 2 recognizes these tags and determines different routes based on different tags (or no tags). With these tags, we can do bandwidth restrictions and request-based classification.

For example, the client of the intranet connects to the Internet through the Linux host, while the Linux host connects to the Internet with two lines, and their gateways are shown in the figure. Policy routing is required for the intranet. All packets accessing port 80 through the TCP protocol are outbound from the ChinaNet line, while all packets accessing port 53 of the UDP protocol are outbound from the Cernet line.

This is a problem of policy routing. In order to achieve the goal, before routing the packet, it is necessary to flag the packet according to the protocol and destination port of the packet, and then specify the corresponding rules. Policy routing according to the flag of the packet. In order to flag a specific packet, you need to use the mangle table. There are five chains in the mangle table. Since you need to flag before routing, you should use the PREROUTING chain. Here are the specific commands:

Iptables-t mangle-A PREROUTING-I eth0-p tcp-- dport 80-j MARK-- set-mark 1 politics IptabLes-t mangle-A PREROUTING-I eth0-p udp-- dprot 53-j MARK-- set-mark 2

After the packet passes through the PREROUTING chain, it will enter the routing module. In order to route it strategically, execute the following two commands and add the corresponding rules:

Ip rule add from all fwmark 1 table 10ip rule add from all fwmark 2 table 20

The above two commands indicate that all packets with flag 1 are routed using routing table 10, while packets with flag 2 are routed using routing table 20. Routing tables 10 and 20 use gateways on ChinaNet and Cernet lines as default gateways, respectively. The specific setup commands are as follows:

Ip route add default via 10.10.1.1 dev eth2 table 10ip route add default via 10.10.2.1 dev eth3 table 20

The above two commands specify 10.10.1.1 and 10.10.2.1 as default gateways on routing tables 10 and 20, on ChinaNet and Cernet lines, respectively. Therefore, packets using routing table 10 will go out over the ChinaNet line, while packets using routing table 20 will go out over the Cernet line.

Custom chain

When there are too many rules in the default chain, it is not convenient for us to manage. Imagine if there are 200 rules stored in the INPUT chain, some for httpd services, some for sshd services, some for private IP, and some for public network IP. If we suddenly want to change the relevant rules for httpd services, do we have to look at these 200 rules from the beginning and find out which rules are for httpd? This is obviously unreasonable.

Therefore, in iptables, you can customize the chain, through the custom chain can solve the above problems. Suppose we customize a chain called IN_WEB, and we can write all the inbound rules for port 80 to this custom chain. when we want to modify the inbound rules for web services in the future, just modify the rules in the IN_WEB chain directly, even if there are more rules in the default chain, we will not be afraid, because we know All inbound rules for port 80 are stored in the IN_WEB chain.

Create custom chain # create IN_WEB custom chain in filter table iptables-t filter-N IN_WEB reference custom chain # reference custom chain in INPUT chain reference custom chain iptables-t filter-I INPUT-p tcp-- dport 80-j IN_WEB rename custom chain # rename IN_WEB custom chain to WEBiptables-E IN_WEB WEB remove custom chain

Deleting a custom chain requires two conditions:

1. The custom chain is not referenced.

2. There are no rules in the custom chain.

# step 1: clear the rule iptables-t filter-F WEB# in the custom chain step 2: delete the custom chain iptables-t filter-X WEBLOG action

The LOG action records the relevant information of the message in the / var/log/message file by default. Of course, we can also record the relevant information in the specified file to prevent the relevant information of iptables from being confused with other log information. Modify the / etc/rsyslog.conf file (or / etc/syslog.conf) and add the following configuration to the rsyslog configuration file:

Kern.warning / var/log/iptables.log

After completing the above configuration, restart the rsyslog service (or syslogd):

Service rsyslog restart

The LOG action also has its own options. The common options are as follows:

The-log-level option specifies the log level at which logs are logged, and the available level is emerg,alert,crit,error,warning,notice,info,debug.

The-log-prefix option can add information such as "tags" to the recorded information in order to distinguish the recorded message information and facilitate filtering during analysis. The corresponding value of-log-prefix cannot exceed 29 characters.

For example, if I want to log all the messages that actively connect to port 22 and name them "want-in-from-port-22", I can use the following command:

Iptables-I INPUT-p tcp-- dport 22-m state-- state NEW-j LOG-- log-prefix "want-in-from-port-22"

After completing the above configuration, I tried to connect to the host in the previous example using the ssh tool on the client machine with IP address 192.168.1.98, and then looked at the corresponding log file (the log file has been set to / var/log/iptables.log):

As shown in the figure above, the information about the message of the ssh connection operation has been recorded in the iptables.log log file, and the log contains a "tag": want-in-from-port-22. If there are many log records, we can filter through this "tag", which makes it convenient for us to view the log. At the same time, we can also know the source IP and target IP of the message from the above record. Information such as source port and destination port, from the above log, we can see that the IP of 192.168.1.98 wants to connect to port 22 of 192.168.1.139 (the IP of the current host) at 14:11, the message is entered by the eth5 network card, the MAC address of the eth5 network card is 00:0c:29:b7:f4:d1, and the MAC address of the client network card is f4:8e:38:82:b1:29.

This is the end of the introduction and use of Iptables. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report