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

How to use iptables

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces you how to use iptables, the content is very detailed, interested friends can refer to, hope to be helpful to you.

I. introduction to iptables

When a host is connected to a network, it will inevitably be subject to the possibility of coming to the network. In order to solve this problem, the firewall (Firewall) technology was born, through which the vast majority of unknown network requests can be blocked so as to protect their hosts.

Firewalls can be divided into hardware firewalls and software firewalls. Software firewalls monitor and block all kinds of messages and information passing through the host through software processing logic, while hardware firewalls can be blocked directly based on hardware. some functions of the hardware firewall also need to be implemented based on software.

Iptables is a software-based firewall, which is mainly composed of two parts. Netfilter in kernel space provides the whole firewall framework, while iptables is located in user space, which mainly provides an interface for users to manage the netfilter located in the kernel according to their needs.

Netfilter mainly uses five hookfunction (hook functions) to monitor and modify messages at the kernel level, which are called prerouting,input,forward,output,postrouting. The iptables in user space uses five chains to correspond to the five hookfunction. Four different functions (tables) are set up to facilitate the management of iptables.

Filter: filtering, firewall

Nat:networkaddress translation; is used to modify the source or destination address, or even the port, of a message

Mangle: disassemble the message, make changes, and repackage it

Raw: turn off the connection tracking mechanism enabled on the nat table

Priority order (from high to low):

Raw-- > mangle-- > nat-- > filte

The relationship between function and hook is as follows:

Function hook:

Raw:PREROUTING,OUTPUT

Mangle:PREROUTING,INPUT,FORWARD,OUTPUT,POSTROUTING

Nat:PREROUTING,INPUT,OUTPUT,POSTRUTING

Filter:INPUT,FORWARD,OUTPUT

II. Iptables settings

Get help:

CentOS7:man iptables-extensions

CentOS6:man iptables

Use format

Iptables [- t table] COMMAND chain [- m matchname [per-match-options]] [- j targetname [per-target-options]]

-t table: defaults to filter;. Other available ones are raw, mangle, nat.

COMMAND:

Chain operation:

-P:policy, policy, define default policy; generally, there are two choices, ACCEPT and DROP

-N:new, create a custom rule chain. It will only take effect if it is called by the rules on the built-in chain.

-X:drop to delete a custom empty chain with a reference count of 0

-F:flush to clear the specified chain

-E: rename custom reference count and chain with 0

Management rules:

-A:append, append, append a rule to the end of the specified chain

-I:insert, insert, insert a rule at the specified position (indicates the head of the chain when the position is omitted)

-D:delelte, delete, delete the specified rule

-R:replace, replace, replace the specified rule with a new rule; you cannot modify only parts of the rule, but replace the whole rule completely

View:

-L:list, listing the rules on the chain in the table

-n:numeric, displayed in numeric format

-v:verbose to display detailed format information

-vv,-vvv

-x:exactly, exact result of the counter

-- line-numbers: displays the rule number in the chain

Counter:

Rules, and default policies have dedicated counters

The record is matched by the current rule:

(1) number of messages

(2) Total number of bytes

Reset the rule counter:

-Z:zero, set 0

Chain:

(1) built-in chain; PREROUTING,INPUT,FORWARD,OUTPUT,POSTROUTING

(2) Custom chain

Matching criteria:

When there are multiple matching rules in a rule, the logical relationship is "and"

1) basic matching conditions:

[!]-s,-- source address [/ mask] [,...]: check whether the source IP address in the message matches the address or range specified here

[!]-d,-- destination address [/ mask] [,...]: check whether the destination IP address in the message matches the address or range specified here

E.g. Prohibit 172.16.10.17 from connecting to 172.16.10.7 hosts

~] # iptables-An INPUT-s 172.16.10.17-d 172.16.10.7-j DROP

[!]-p,-- protocol protocol:

Protocol: {tcp | udp | icmp}

[!]-I,-- in-interface name: data message inflow interface; INPUT, FORWARD,PREROUTING

[!]-o,-- out-interface name: data message outflow API: FORWARD,OUTPUT, POSTROUTING

E.g. Deny all requests through the eno16777736 network card

~] # iptables-An INPUT-I eno16777736-j REJECT

2) extended matching conditions

Implicit extension: do not use the-m option to indicate matchname to match with the dedicated options of this match

-p tcp: implied-m tcp

[!]-- source-port,--sport port [: port]: matches the source port of the transport layer in the message

E.g. Disable all requests to access port 23 of tcp

~] # iptables-An INPUT-p tcp-- dport 23-j DROP

[!]-- destination-port,--dport port [: port]: matches the destination port of the transport layer in the message

[!]-tcp-flags mask comp

Identification bit: SYN,ACK,FIN,RST,URG,PSH

Mask: a comma-separated list of flag bits to check

Comp: flag bits that must be 1, and the remaining flag bits that appear in the mask list must be 0

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

[!]-syn:

Equivalent to-- tcp-flags SYN,ACK,FIN,RST SYN

-p udp: implied-m udp:

[!]-- source-port,--sport port [: port]: matches the source port of the transport layer in the message

[!]-- destination-port,--dport port [: port]: matches the destination port of the transport layer in the message

-p icmp: implied-m icmp:

[!]-- icmp-type {type [/ code] | typename}

8:echo-request is used for request

0:echo-reply is used to answer

E.g. All hosts except 172.16.10.17 are prohibited from performing ping operations on this machine.

~] # iptables-An INPUT!-s 172.16.10.17-d 172.16.10.7-p icmp--icmp-type 8-jDROP

~] # iptables-An OUTPUT!-d 172.16.10.17-s 172.16.10.7-p icmp--icmp-type 0-j DROP

Explicit extension: you must use the-m option to indicate matchname, and some match may have dedicated options

Multiport extension

Define multi-port matching conditions in a discrete or continuous manner

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

[!]-- destination-ports,--dports port [, port |, port:port]...: specify multiple destination ports

E.g. All requests are prohibited from accessing port 21, 22, 22, 23 and 80 of tcp.

~] # iptables-An INPUT-p tcp-m multiport-- dports 21 tcp 23 80-j DROP

[!]-- portsport [, port |, port:port]...: specify multiple ports

Iprange extension

Indicate continuous multi-address matching conditions with a continuous range of ip addresses

[!]-- src-range from [- to]: source IP address

[!]-- dst-range from [- to]: destination IP address

String extension

Do string matching detection on the application layer data in the message

[!]-- string pattern: to detect a string pattern

[!]-- hex-string pattern: string pattern to be detected, hexadecimal encoding

-- algo {bm | kmp}

Time extension

The matching degree is detected according to the arrival time of the message and the specified time range.

-- datestartYYYY [- MM [- DD [Thh [: mm [: ss]: start date time

-- datestopYYYY [- MM [- DD [Thh [: mm [: ss]: end date time

-- timestarthh:mm [: ss] start time

-- timestop hh:mm [: ss] end time

[!]-- monthdays day [, day...] Start date

[!]-- weekdays day [, day...] End date

E.g. Open port 23 on Tuesday, Thursday and Saturday during working hours

~] # iptables-I INPUT-d 172.16.10.7-p tcp-- dport 23-m time-- timestart 09:00:00--timestop 18:00:00-- weekdays Tue,Thu,Sat-j ACCEPT

Connlimit extension

Match the number of concurrent connections per client IP

-- connlimit-upton: if the number of connections is less than or equal to n, it should be allowed

-- connlimit-aboven: if the number of connections is greater than n, it should be rejected.

~] # iptables-An INPUT-d 172.16.100.67-p tcp-- dport 23-m connlimit--connlimit-upto2-j ACCEPT

Limit extension

Matching based on the rate of sending and receiving messages

-- average speed [/ second | / minute | / hour | / day]

-- limit-burstnumber: peak rate

State extension

State STATE

State detection; connection tracking mechanism (conntrack)

INVALID: unrecognized statu

ESTABLISHED: established connection

NEW: new connection

RELATED: associated connection

UNTRACKED: untracked connections

State tracking requires nf_conntrack kernel modules to be mounted

Tracked connection: / proc/net/nf_conntrack file

The maximum number of connections that can be tracked is defined as: / proc/sys/net/nf_conntrack_max

This value can be defined by yourself, and it is recommended to adjust it to large enough if necessary.

Duration of connection tracking for different protocols: / proc/sys/net/netfilter/

E.g. How to open up a modeled ftp service:

Load the module that tracks the ftp protocol

~] # modprobe nf_conntrack_ftp

Release command connection

~] # iptables-An INPUT-d 172.16.100.67-p tcp-m state-- state ESTABLISHED-jACCEPT

~] # iptables-An INPUT-d 172.16.100.67-p tcp-- dport 21-m state-- state NEW-jACCEPT

Release data connection

~] iptables-An INPUT-d 172.16.100.67-p tcp-m state-- state RELATED-j ACCEPT

There are several issues to be aware of when defining on the FORWARD chain:

(1) request and response are all through the FORWARD chain, so pay attention to the directionality of the rules.

(2) if the conntrack mechanism can be enabled, it is recommended to release messages with the status of ESTABLISHED in both directions directly.

E.g. Only external hosts can access httpd services and ftpd services of 192.168.10.27 hosts only

1) ~] # iptables-A FORWARD 1-d 192.168.10.27-p tcp-m multiport-- dports 21 state--state NEW 80-m state--state NEW-j ACCEPT

2) ~] # iptables-A FORWARD 3-d 192.168.10.27-m state-- state ESTABLISHED,RELATED-j ACCEPT

3) ~] # iptables-A FORWARD-s 172.16.0.0 iptables-A FORWARD 16-d 192.168.10.27-j DROP

4) ~] # modprobenf_conntrack_ftp

Custom chain:

Iptables-N chain_name adds a custom chain

Iptables-X chian_name delete custom chain (rules need to be emptied before deletion)

Iptables-E old_name new_name rename custom chain

-j chain_name references the specified custom chain

Usually, at the end of the custom chain, you need to add a RETURN that has returned to the previous main chain.

Processing action

ACCEPT: receive

DROP: discard

REJECT: reject

REDIRECT: retargeting port, which can only be used on nat tables and PREROUTING,OUTPUT chains, and must be referenced if you want to use it elsewhere

-- to-portsport [- port]: which target port to map to

E.g. Map port 80 of the httpd service to port 8088

~] # iptables-t nat-A PREROUTING-d 192.168.10.27-p tcp-- dport 80-j REDIRECT--to-port 8088

SNAT: modify the source address, which can only be used on the nat table and above the POSTROUTING,INPUT chain. If you want to use it elsewhere, you must refer to it. If the IP address is a dynamic reference, use MASQUERADE.

-- to-source [ipaddr [- ipaddr]] [: port [- port]]

~] # iptables-t nat-A POSTROUTING-s 192.168.0.0Universe 16-j SNAT-- to-source172.16.10.17

After setting the above rules, when the hosts in the 192.168.0.0 network segment pass through this route, the IP address will be translated to 172.16.10.17, thus the access to various services of the internal network and external network can be realized.

DNAT: modify the source address, which can only be used on the nat table and on the PREROUTING,OUTPUT chain. If you want to use it elsewhere, you must refer to it.

-- to-destination [ipaddr [- ipaddr]] [: port [- port]]

~] # iptables-t nat-A PREROUTING-d 172.16.10.17-p tcp-- dport 80-j DNAT--to-destination 192.168.10.27 PREROUTING 8088

When an external host accesses port 80 of the tcp protocol of the 172.16.10.17 host, it automatically goes to port 8088 of the 192.168.10.27 host in the internal network.

LOG: log function, log is saved in / var/log/messages

-log-prefix: add a prefix to the log

-- log-ip-options: record the information of the IP header in the log

E.g. Access to 172.16.10.7 host tcp protocol port 80 is logged

~] # iptables-An INPUT-d 172.16.10.7-p tcp-- dport 80-j LOG-- log-prefix "STRING"-log-ip-options

three。 Summary

Questions to consider when adding rules:

(1) the flow path of the message to determine the chain to which the rule is added

(2) determine the functions to be implemented and determine which table to add rules to.

(3) the matching condition to be specified to match the target message

Pay attention to optimization after adding rules:

(1) all inbound and outbound connections with a status of ESTABLISHED can be safely released

(2) for the rules that serve the same kind of function, the matching conditions should be strictly placed in front and loosely placed behind.

(3) for rules that serve different types of functions, matching messages are more likely to be expanded in front and less in the back.

(4) set the default policy

(a) the last rule is set, adding a default rule to reject or accept at the end of each table

Iptables-An INPUT-d 172.16.10.17-j DROP

(B) default policy settings

On how to use iptables to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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