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

Knowing iptables from scratch

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

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

Write at the front

In the Linux operation and maintenance work, when it comes to Linux security, the first thing we think of is iptables. As a linux beginner, in the process of learning linux, some experiments are always unsuccessful. At this point, we always check to see if the firewall is off and selinux is off. After an in-depth study of iptbales, these previously known operations, but do not know why, will be very open in the heart. If you want to learn something in depth, always ask what is it.

Learning objectives in this section

Firewall classification

How Netfilter Firewall works

Iptables four tables and five chains

Key points of iptables rule setting

How to use iptables tools (proficient in use, including host firewall configuration, network firewall configuration, and nat configuration)

What is a firewall?

Firewall is an isolation tool. Work at the edge of the host or network, match the messages entering and leaving the host or local network according to the pre-defined rules, and deal with the messages that can be matched by the rules (allow, reject, discard, etc.). It can be divided into host firewall and network firewall according to the scope of its management. According to its working mechanism, it can be divided into packet filtering firewall (netfilter) and proxy server (Proxy). Some people also classify tcp_warrpers as a kind of firewall. This is a way to control packets according to the name of the service program software.

How firewalls work

Packet filtering firewall Netfilter is a functional module framework supported by the linux kernel. Iptables is a software tool for configuration management Netfilter. So Netfilter works with kernel space. A Netfilter is a series of hook in the kernel that registers callback functions (callback) for kernel modules at different locations in the network protocol stack. The packets are processed as they pass through different locations in the network protocol stack.

Five hooks NF_IP_PRE_ROUTING,NF_IP_LOCAL_IN,NF_IP_FORWARD,NF_IP_POST_ROUTING,NF_IP_LOCAL_OUT in Netfilter. The flow chart of the network packet is shown in the following figure

1. After entering the network card, the network packet enters the TCP/IP protocol stack in the kernel space and is de-encapsulated layer by layer.

2 when a packet just enters the network layer passes through the NF_IP_PRE_FORWARD, a route selection needs to be made after the store. When the destination address is the local address, the data enters the NF_IP_LOCAL_IN, and the non-local destination address enters the NF_IP_FORWARD, so the destination address translation usually takes place at this point.

3 NF_IP_LOCAL_IN: packets that are routed and sent locally pass through this point, so filtering INPUT packets occurs at this point.

4 NF_IP_FORWARD: packets to be forwarded after routing pass through this point, so network firewalls are usually configured at this point.

5 NF_IP_LOCAL_OUT: packets generated by local user space application processes pass through this checkpoint, so OUTPUT packet filtering occurs at this point.

6 NF_IP_POST_ROUTING: packets that have just passed through NF_IP_FORWARD and NF_IP_LOCAL_OUT checkpoints are routed through which interface to send to the network, and routed packets pass through NF_IP_POST_ROUTING checkpoints, so source address translation usually takes place at this point.

Four tables and five chains of iptables

Iptables is a tool for managing netfilter working in user space. By default, the tool has five chains (chain), and REROUTING,INPUT,FORWARD,OUTPUT,POSTROUTING is triggered by five hook functions of netfilter. Iptables has four tables to realize the different functions of Netfilter.

Filter table: the most widely used table in iptables for packet filtering, which determines whether the packet continues to advance to its destination address.

Nat table: as can be seen from the name of this table, this table is used for network address translation, which is another function of the firewall, the modification of the source address or destination address.

Mangle table: the mangle table is used to modify the header information of the ip message.

Raw table: the function of raw table is to provide a mechanism for firewalls to disable connection state tracking. Using this table on servers with large traffic can effectively avoid the performance problems caused by connection tracking. For example, game servers usually disable firewall connection tracking mechanism through this table or by recompiling the kernel.

In addition, it is mentioned in the iptable help document that there is a security table that is used to always add selinux to packets. This table is rarely used and will not be detailed here.

The four tables of Iptables have different processing priorities, raw-- > mangle-- > nat-- > filter, and the priority decreases from left to right. Due to the different positions of hooks in the protocol stack and the priority order of the tables, the processing order of packets in the firewall is particularly easy to be confused. Here is a processing sequence diagram of Xu Feng's predecessor (because the figure is not clearly displayed, you can download it from the attachment):

Iptables rule

If you want to configure a more secure firewall policy, you need to understand the composition of its rules and the main points to think about when setting them.

The composition of the rules: the matching condition of the message and the processing action after matching

Matching conditions: specify matching conditions, basic matching conditions and extended matching conditions according to the characteristics of the protocol message

Processing actions: some processing actions provided by the built-in processing mechanism provided by iptables itself

Custom processing mechanism: you can customize the chain to process matching messages.

Note: the message does not go through the custom chain and can only take effect after it is referenced by rules on the built-in chain, that is, the custom chain is a collection of processing actions of the rules.

Key points to consider when setting up iptables rules:

1. Judge which function to add to that table according to which function you want to implement

2. Judge which chain to add according to the path through which the message flows.

Inflow: PREROUTING--- > INPUT

Outflow: OUTPUT--- > POSTROUTING

Forwarding: PREROUTING---- > FORWARD--- > POSTROUTING

The order of the rules on the chain, that is, the order of inspection, arranging the order of inspection can effectively improve the performance, so there are certain rules implied.

1. Similar rules (access to the same application), those with small matching range are put on top.

2. Different kinds of rules (access to different applications) are matched to those with high frequency of messages:

3. Merge multiple rules that can be described by a single rule into one

4. Set the default policy

Key points to note when configuring a firewall for a remote connection host:

1, do not change the default policy of the chain to reject. It is possible to fail the configuration or to reach the server remotely after all policies have been cleared. Try to use rule entries to configure the default policy

2. In order to prevent yourself from being rejected by misconfiguring the policy, you can set the scheduled task scheduled clearing policy when configuring the policy. When you are sure, close the scheduled task.

Sharpen a knife without mistakenly chopping firewood, and when the above things already have a framework in mind, it will be easy to learn iptables rule management tools.

How to use iptables tool

Man documentation is the best way to learn tools. I will not elaborate here. I will paste out my study notes for readers' reference. If there are any mistakes, please correct them.

Iptables command:

Iptables [- t table] {- A |-C |-D} chain rule-specification

Ip6tables [- t table] {- A |-C |-D} chain rule-specification

Iptables [- t table]-I chain [rulenum] rule-specification

Iptables [- t table]-R chain rulenum rule-specification

Iptables [- t table]-D chain rulenum

Iptables [- t table]-S [chain [rulenum]]

Iptables [- t table] {- F |-L |-Z} [chain [rulenum]] [options...]

Iptables [- t table]-N chain

Iptables [- t table]-X [chain]

Iptables [- t table]-P chain target

Iptables [- t table]-E old-chain-name new-chain-name

Iptables [- t table] SUBCOMMAND CHAIN CRETERIA-j TARGET

-t table:

Filter, nat,mangle,raw defaults to filter

Chain management:

-F: flush, clear the rule chain: omit chain means to clear all chains on the specified table

-N:new to create a new custom rule chain:

-X:drop, delete the user-defined empty rule chain:

-Z:zero, zero, zero rule counter

-P:policy, which sets the default policy for the specified chain. For chains in the filter table, the default policy usually has ACCEPT,DROP,REJECT

-E:rEname, renames a custom chain, references a custom chain whose count is not 0, and cannot be renamed or deleted

Rule management:

-A:append, appending the new rule to the tail of the specified chain

-I:insert, insert the new rule into the specified position of the specified chain (you need to specify the sequence number, default is the first one):

-D:delete to delete the specified rule on the specified chain:

There are two ways to specify:

1. Specify matching conditions

2. Specify the rule number

-R:replace, replacing the specified rule on the specified chain.

View:

-L:list, listing all rules on the specified chain.

-n:numberic to display the address and port number in numeric format

-v:verbose to display details

-vv,-vvv

-- line-numbers: displays the rule number

-x:exectly, which displays the exact value of the counter count result.

Matching criteria:

Basic match:

[!]-s,-- src,--source IP | Netaddr: check whether the source ip address in the message matches the address range specified here

[!]-Netaddr: check whether the destination ip address in the message matches the address range specified here.

-p,-- protocal {tcp | udp | icmp}: check the protocol in the message, that is, the protocol identified by protocol in the header of ip. Tcp.17 indicates udp.

-imam Murin Mutual IFACE: the interface for the inflow of data packets. Can only be used for PREROUTING,INPUT,FORWARD chains

-ofuromine: the outflow interface of datagrams. Can only be used on FORWARD,OUTPUT,POSTROUTING chains

Extended matching:-m macth_name-- spec_options

Eq:-m tcp-- dport 22 indicates that the target port for tcp extension is 22

Implicit extension: extends the protocol specified by-p protocal, omitting the-m option:

-p tcp

-- dport PORT [- PORT]: destination port, which can be a single port or consecutive multiple ports

-- sport PORT [- PORT]

-- tcp-flags list1 list2: check all the flag bits specified by list1, where all tags indicated by list2 must be 1, and the rest must be 0. No check is made if there is no flag specified in list1.

SYN,ACK,FIN,RST,PSH,URG

Eq:--tcp-flags SYN,ACK,FIN,RST SYN

=-- syn: check the first handshake of a three-way handshake

-p udp

-- dport

-- sport

-p icmp

-- icmp-type

Its type can be represented by a number:

0 echo-reply

8 echo-request

Show extensions:

Goal:

-j target:jump to the specified target

ACCEPT: receive

DROP: discard

REJECT; refuses

RETURN: returns the call chain

REDIRECT: Port redirection

LOG: logging

MARK: do firewall marking

DNAT: destination address translation

SNAT: source address translation

MASQUERADE: address masquerade

...

Custom chain: matches are checked by rules on the custom chain.

Display extensions: the extension module indicated to be used must be displayed (rpm-ql iptables | grep "\ .so")

Centos6 man iptables

Centos7 man iptbales-extensions

1. Multiport extension

Define multi-port matches in a discrete manner: match up to 15 ports

[!]-- source-ports,--sports port [, port |, port:port] Indicate multiple source ports

[!]-- destination-ports,--dports port [, port |, port:port] Indicate multiple discrete target ports

[!]-- ports port [, port |, port:port]

Example: # iptables-An INPUT-p tcp-m multiport-- dports 22pr 80-j ACCEPT

# iptables-An OUTPUT-p tcp-m multiport-- sports 22 80-j ACCEPT

2. Iprange extension

Indicates a contiguous (but generally not extended to the entire network) range of ip addresses

[!]-- src-range from [- to] match indicates a contiguous range of source IP addresses

[!]-- dst-range from [- to] indicates a contiguous range of destination IP addresses

# iptables-An INPUT-m iprange-- src-range 172.18.11.0-172.18.11.100-j DROP

# iptables-An INPUT-p tcp-m multiport-- dports 22 80-m iprange-- src-range 172.18.11.0-172.18.11.100-j DROP

3. String extension

Check the string that appears in the message:

-- algo {bm | kmp}:

[!]-string pattern

[!]-- hex-string pattern hexadecimal

Iptables-I OUTPUT-m string-algo bm-string "movle"-j DROP

4. Time extension

Match the time of arrival of the message with the specified time range

-- datestart

-- datestop

-- timestart

-- timestop

-- monthdays

-- weekdays

# iptables-I INPUT-d 172.18.11.7-p tcp-- dport 80-m time-- timestart 8:00-- timestop 10:00-j DROP

# Note that centos7 uses UTC time

5. Connlimit extension

Match the number of concurrent connections per client ip (or address block):

-- the number of connlimit-above n connections is greater than n

-the number of connlimit-upto n connections is less than or equal to n

# iptables-I INPUT-p tcp-- dport 22-m connlimit--connlimit-above 3-j REJECT

# if the ssh connection is greater than 3, the link is rejected

6. Limit extension

Check based on the rate of sending and receiving messages:

Token bucket filter:

-- limit second [/ second | / minute | / hour | / day]

-- limit-burst number

# iptables-An INPUT-p icmp--icmp-type 8-m limit--limit-burst 5-- limit 6/minute-j ACCEPT

# iptables-An INPUT-p icmp-j REJECT

# # skip 5 packets and respond to a ping packet every 10 seconds

7. State extension

Check the connection tracking mechanism check the status of the connection:

Adjust the maximum number of connections that the connection tracking feature can accommodate:

/ proc/sys/net/nf_conntrack_max

Connections that have been tracked and recorded:

/ proc/net/nf_conntrack

Length of time tracked by different protocols or connection types

/ proc/sys/net/netfilter/

Traceable connection status:

NEW: new request: the information entry related to this connection does not exist in the connection tracking template, so it is recognized as the first request

After the ESTABLISHED:NEW state, the connection tracks the status of the communication that took place during the period before the item established for it expired in the template.

RELATED: related connections: for example, the relationship between command connections and data connections in the ftp protocol

INVALIED: unrecognized connection

-- state state1 state2...

Example:

# iptables-I INPUT-d 172.18.11.7-p tcp-- dport 22-m state-- state NEW,ESTABLISHED-j ACCEPT

# iptables-I OUTPUT-s 172.18.11.7-p tcp-- sport 22-m state-- state ESTABLISHED-j ACCEPT

# Control newly initiated http and ssh access requests

# iptables-An INPUT-d 172.16.100.10-p tcp-m multiport-- dports 22 state 80-m state-- state NEW,ESTABLISHED-j ACCEPT

# iptables-An OUTPUT-s 172.16.100.10-p tcp-m multiport-- sports 22 state 80-m state-- state ESTABLISHED-j ACCEPT

How to open FTP services in passive mode?

(1) load a dedicated module for ftp tracking

# modprobe nf_conntrack_ftp

Path / lib/modules/3.10.0-514.el7.x86_64/kernel/net/netfilternf_conntrack_ftp.ko

Module Information modinfo nf_conntrack_ftp.ko

(2) release request message:

Command connection: NEW,ESTABLISHED

Data connection: RELATED,ESTABLISHED

# iptables-An INPUT-d localIP-p tcp-dport 21-m state-- state NEW,ESTABLISHED-j ACCEPT

# iptables-An INPUT-d localIP-p tcp-m state-- state RELATED,ESTABLISHED-j ACCEPT

(3) release response message

ESTABLISHED

# iptables-An OUTPUT-d localIP-p tcp-m state-- state ESTABLISHED-j ACCEPT

How to save and reload rules:

Save the rule to the specified file:

Iptables-save > / path/to/somefile

Reload the rule from the specified file:

Iptables-restore

< /path/from/somefile centos6: service iptables save iptable-save >

/ etc/sysconfig/iptables

Service iptables restart

Iptables-restore < / etc/sysconfig/iptables

Network Firewall:

Core forwarding configuration: / proc/sys/net/ipv4/ip_forward

/ etc/sysctl.conf

Net.ipv4.ip_forward=1

Nat:

SNAT: only modify the source address of the request message

DNAT: modify only the destination address of the request message

Nat table:

PREROUTING: DNAT

OUTPUT

POSTROUTING: SNAT

Source address translation

Iptables-t nat-A POSTROUTING-s local_net!-d local_net-j SNAT-- to-source public_ip public network ip fixed

Iptables-t nat-A POSTROUTING-s local_net!-d local_net-j MASQUERADE public network ip is not fixed

Destination address translation iptables-t nat-A POSTROUTING-d public_ip-p tcp | udp-- dport PORT-j DNAT-- to-destination local_ip:port

Attachment: http://down.51cto.com/data/2368698

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

Network Security

Wechat

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

12
Report