Basic iptables commands in Linux

Source: Internet
Author: User
Tags ftp protocol

Basic iptables commands in Linux

Firewall (Firewalld) is an isolation tool that prevents unauthorized access and makes the host more secure. It mainly works on the edge of the network or host, and matches and checks the communication packets in and out of the network or host according to the predefined rules; handle packets that can be matched by rules.
Classification of firewalls:
Host firewall: the work scope is a single host

Network Firewall: the work scope is the entire network. The network firewall can also contain host firewalls.
Implementation of the firewall:
Hardware firewalls: NetScreen and CheckPoint
Software Firewall: iptables

The iptables introduced in this article is the implementation before Linux's soft fire prevention.
The main feature of iptables is four table 5 chains and different chains for each table;

5 links: prerouting, input, output, forward, and postrouting
4 tables: filter, mangle, nat, raw
Filter: Mainly used for filtering. The corresponding links are: input, output, and forward.
Mangle: The main function is to disassemble, modify, and re-encapsulate packets. The corresponding links are prerouting, input, output, forward, and postrouting.
Nat: The main function is network address translation. The corresponding links are prerouting, postrouting, and output.
Raw: Disable the Connection Tracing Mechanism enabled on the nat table within a limited time range. The corresponding links are output and prerouting.
Application priorities of different tables on the same link: raw, mangle, nat, and filter


Message flow in the Host:

There are two types of message flows:
Incoming packets: incoming packets --> prerouting --> input --> output --> postrouting --> outgoing packets
Forward packets from the local machine: incoming packets --> prerouting --> forward --> postrouting
Note: The packets are processed by the local machine, but whether the packets are forwarded is determined by the route. After the packets flow into the local machine, Route 1 determines whether the destination address of the packets is the local machine. If yes, inbound input. If not, the inbound traffic is forwrad. Route 2 determines that the packet is sent to the next Gateway (Next Hop) through that interface before the packet is sent to the next Gateway (Next Hop, make sure that the forwarding function is enabled. 1 indicates that the forwarding function is enabled, and 0 indicates that the forwarding function is disabled:

[Root @ bkjia ~] # Vim/etc/sysctl. conf
[Root @ bkjia ~] # Net. ipv4.ip _ forward = 0 # Change 0 to 1 to enable
[Root @ bkjia ~] #/Sbin/sysctl-p # take effect immediately after modification

 

Iptables rules: Checks packets based on rule matching conditions, and processes successfully matched packets accordingly.
Components: matching conditions and processing actions
Matching conditions: Basic match and extended match
Processing actions: basic processing actions, extended processing actions, and custom processing actions
Note: considerations when adding rules;
(1) What functions should be implemented; Determine the table to be added
(2) the position where the message flows. Determine the link to which the message is added.
(3) similar rules with a smaller matching range placed in front for special processing
(4) for different types of rules, the matching range should be large.
(5) Merge multiple rules described by one rule into one
(6) set the Default policy

Iptables commands:

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

Iptables [-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


Rule-specification = [matches...] [-j target]


Implement Chain Management: Manage a whole chain
-N: adds a custom chain.
-X: delete a custom chain (make sure there are no rules under the chain when deleting it)
-P: Set the default chain Policy
-E: rename a custom chain that has not been referenced (reference count is 0, that is, references is 0)

Implement rule management: Manage a rule on the chain
-A: append A rule. The default value is the end.
-I: Insert a rule. The default value is at the beginning.
-D: delete a rule.
-R: specifies the number of rules to be modified.
-F: Clear all rules.

View the rules of a table:
-L: List Rules
-N: Display address ports in digital format
-V: displays details.
-- Line-numbers: displays the rules and numbers on the chain.
-X: displays the exact counter value.


Matching condition:
Basic match: the matching mechanism provided by netfilter
[!] -S, -- source address [/mask] [,...]: original address match (! S is reverse)
[!] -D, -- destination address [/mask] [,...]: target address match
[!] -I, -- in-interface name: interface that limits incoming packets (only available for the prerouting, input, and forward links)
[!] -O, -- out-interface name: interface used to Restrict outbound packets (only available for output, forward, and postrouting chains)
[!] -P {tcp | udp | icmp}: indicates the protocol used.
[Root @ bkjia ~] # Iptables-a input-s 172.18.0.0/18-d 172.18.42.200-p tcp-j ACCEPT
[Root @ bkjia ~] # Iptables-a output-s 172.18.42.200-d 172.18.0.0/16-p tcp-j ACCEPT

Extension matching: the matching mechanism introduced by the extension module;-m matchname
Implicit Extension: you do not need to specify which Protocol the-m option can match to specifically load the response module.
Display Extension: You must specify that the response module must be specifically loaded by the-m option.


Implicit extension:

Tcp: "-m tcp" is implicitly specified, with special options:
[!] -- Source-port, -- sport port [: port]: match the source port of the tcp Header in the packet. It can be a port range.
[!] -- Destination-port, -- dport port [: port]: match the target port of the tcp Header in the packet. It can be a port range.
[!] -- Tcp-flags mask comp: Check the tcp flag specified by the message mask.
Example: -- tcp-flags syn, fin, ack, rst syn
In this case, syn must be 1.

[!] -- Syn:
-- Syn is equivalent to "-- tcp-flags syn, fin, ack, syn", the first handshake in tcp
[Root @ bkjia ~] # Iptables-a input-s 0/0-d 10.0.1.2-p tcp -- dport 80 -- tcp-flags SYN, ACK, FIN, rst syn-j ACCEPT
[Root @ bkjia ~] # Iptables-a input-d 0/0-s 10.0.1.2-p tcp -- sport 80-j ACCEPT

Udp:
[!] -- Source-port, -- sport port [: port]: match the source port of the tcp Header in the packet. It can be a port range.
[!] -- Destination-port, -- dport port [: port]: match the target port of the tcp Header in the packet. It can be a port range.

Icmp: indicates "-m icmp", with special options.
[!] -- Icmp-type {type [/code] [typename]
Type/code:
0/0: indicates a response.
0/8: indicates the request
[Root @ bkjia ~] # Iptables-a input-s 0/0-d 172.18.42.200-p icmp -- icmp-type 8-j ACCEPT
[Root @ bkjia ~] # Iptables-a output-s 172.18.42.200-d 0/0-p icmp -- icmp-type 0-j ACCEPT


Display extension:

(1) multiport Extension: define multi-port matching in Discrete mode; Specify up to 15 ports;
[!] -- Source-ports, -- sports port [, port |, port: port]...: Specifies multiple source ports;
[!] -- Destination-ports, -- dports port [, port |, port: port]...: specify multiple destination ports;
[!] -- Ports port [, port |, port: port]...: multiple ports are matched at the same time (multiple ports are specified ;)
[Root @ bkjia ~] # Iptables-a input-s 0/0-d 172.18.42.200-p tcp-m multiport -- dports 80, 22-j ACCEPT
[Root @ bkjia ~] # Iptables-a output-s 172.18.42.200-d 0/0-p tcp-m multiport -- sports 80, 22-A ACCEPT


(2) iprange Extension: specifying a consecutive IP address range as the source address or target address match
[!] -- Src-range from [-to]: source IP address;
[!] -- Dst-range from [-to]: Destination IP address;
[Root @ bkjia ~] # Iptables-a input-d 172.18.42.200-p tcp-dport 80-m iprange -- src-range 172.18.42.1-172.18.42.100-j ACCEPT
[Root @ bkjia ~] # Iptables-a output-s 172.18.42.200-p tcp-sport 80-m iprange -- dst-range 172.18.42.1-172.18.42.100-j ACCEPT


(3) string extension: Performs string pattern matching detection on the application layer data in the message;
-- Algo {bm | kmp}: string matching detection algorithm;
Bm: Boyer-Moore
Kmp: Knuth-Pratt-Morris
[!] -- String pattern: the string pattern to be checked;
[!] -- Hex-string pattern: string mode to be checked (hexadecimal format );
1 [root @ bkjia ~] # Iptables-I OUTPUT-s 172.18.42.200-d 0/0-p tcp-sport 80-m string -- algo bm -- string "bkjia"-j A DROP

Note: the stricter the requirements, the more we need to put them in front. The reason why "OUTPUT" is used is because the OUTPUT can be responded after the message is received. If "INPUT" is used directly, "DROP" is used ", the message will be rejected directly and will not flow into the local machine.

 


(4) time Extension: match the arrival time of the message with the specified time range;
-- Datestart YYYY [-MM [-DD [Thh [: mm [: ss]: Start Date and Time
-- Datestop YYYY [-MM [-DD [Thh [: mm [: ss]: End Date and Time
-- Timestart hh: mm [: ss]: Start Time
-- Timestop hh: mm [: ss]: End Time
[!] -- Monthdays day [, day...]: matches certain days from 1 to 12 months.
[!] -- Weekdays day [, day...]: matches certain days of a week.
-- Kerneltz: Use the Kernel Time Zone instead of the default UTC time zone;
1 [root @ bkjia ~] # Iptables-a input-s 0/0-d 172.18.42.200-p tcp-dport 80-m time -- timestart 08:30:00 -- timestop 18:00:00 -- weekdays, 5-j ACCEPT


(5) connlimit Extension: the number of concurrent connections per client IP address is matched, that is, the maximum number of connections that can be initiated at the same time per client
-- Connlimit-upto n: match when the number of connections is less than or equal to n;
-- Connlimit-above n: match when the number of connections is greater than n
[Root @ bkjia ~] # Iptables-a input-s 0/0-d 172.18.42.200-p tcp-dport 80-m connlimit -- connlimit-upto 20-j ACCEPT

(6) limit Extension: matching based on the rate of sending and receiving packets;
-- Limit rate [/second |/minute |/hour |/day]
-- Limit-burst number
[Root @ bkjia ~] # Iptables-a input-s 0/0-d 172.18.42.200-p tcp-dport 80-m limit -- limit 20/second -- limit-burst 5-j ACCEPT


(7) state Extension (subset of conntrack): used to check the connection status of packets based on the "Connection Tracing Mechanism" (but it has a great impact on the number of connections of the Service)
Connection template: occupies a portion of the memory space (kernel space)
[!] -- State
Conntrack mechanism: tracks the relationship between requests and responses on the local machine. The status can be as follows:
NEW: a NEW request. The Connection Tracing template does not contain information entries related to this connection. Therefore, it is recognized as the first request;
ESTABLISHED: Communication Status in the Connection Tracing template before the entry created in the Connection Tracing template expires;
RELATED: associated connections, such as the relationship between data connections and command connections in the ftp protocol;
INVALID: Unrecognized connection (usually not allowed)
UNTRACKED: Connection not tracked (no relevant records in the connection template)

[Root @ bkjia ~] # Iptables-a input-m state -- state ESTABLISHED-j ACCEPT
[Root @ bkjia ~] # Iptables-a output-s 172.18.42.200-d 0/0-p tcp-sport 80-m state -- state NEW-j ACCEPT

View the maximum number of connections that the Connection Tracing function can accommodate:
/Proc/sys/net/nf_conntrack_max
Maximum number of connections that the link tracing function can accommodate
Echo Num>/proc/sys/net/nf_conntrack_max
Sysctl-w net. nf_conntrack_max = Num
Disadvantage: if the connection template is overloaded, the web page displays a connection timeout when a new request is sent. The maximum number of connections that conntrack can connect to depends on/proc/sysnet/nf_conntrack_max; records that have been tracked are recorded in the/prco/net/nf_conntrack file. However, when the template is fully loaded, subsequent new connections may time out, the connection timeout duration will be deleted. There are two solutions:
(1) Increase the value of nf_conntrack_max.

[Root @ bkjia ~] # Vim/proc/sys/net/netfilter/nf_conntrack_max

(2) reduce the duration of the nf_conntrack_timeout file (The Connection Tracing duration varies with different protocols)
[Root @ bkjia ~] # Vim/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_time_wait
[Root @ bkjia ~] # Vim/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established
[Root @ bkjia ~] # Vim/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_fin_wait
[Root @ bkjia ~] # Vim/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_close_wait

Open the ftp service in active/passive mode:
Active:

[Root @ bkjia ~] # Iptables-a input-d 172.18.42.200-p tcp -- dport 21-m state -- state ESTABLISHED-j ACCEPT
[Root @ bkjia ~] # Iptables-a output-s 172.18.42.200-p tcp -- sport 21-m state -- state ESTABLISHED-j ACCEPT

Passive:

[Root @ bkjia ~] # Modprobe nf_conntrack_ftp # the kernel loads the nf_conntarck_ftp Module
[Root @ bkjia ~] # Iptables-a input-m state -- state established related-j ACCEPT
[Root @ bkjia ~] # Iptables-a output-s 172.18.42.200-p tcp -- sport 21-m state -- state NEW-j ACCEPT

Save the compiled rules and start them on startup
[Root @ bkjia ~] # Server iptables save
[Root @ bkjia ~] # Iptables: Saving firewall rules to/etc/sysconfig/iptables: [OK] # default storage path of the system
[Root @ bkjia ~] # Iptables-save>/path/to/rule_file # specify the save path
[Root @ bkjia ~] # Chkconfig iptables on # Set to the current rule to enable startup
[Root @ bkjia ~] # Service iptables restart # The rules are automatically reloaded from the default storage path of the system.

Action:
(1) LOG: match the LOG function in the message
-- Log-level :( emerg, alert, crit, error, warning, notice, info or debug .)
-- Log-prefix: indicates who generates the log information of the message.

[Root @ bkjia ~] Iptables-a forward-m state -- state ESTABLISHED-j ACCEPT
[Root @ bkjia ~] Iptables-a forward-s 0/0-d172.18.42.200-p tcp-m multiport -- dports 80, 21, 23,22-m state-state NEW-j LOG -- log-prefix "(bkjia's log)"


(2) REDIRECT: Port redirection (used before packets flow into the local machine: prerouting)
-- To-ports port [-port]: ing to a port
[Root @ bkjia ~] Iptables-t nat-a prerouting-d 172.18.42.200-p tcp 80-j REDIRECT -- to-ports 172.18.42.201: 8080
# This command maps port 80 to port 8080. Although port 80 is accessed, port 8080 is actually provided.

(3) SNAT (local host requests remote server): source address conversion; occurs in postrouting
Modify the source IP address in the IP Message
Use Cases: hosts in the local network can communicate with external hosts using a Unified Address to achieve address disguise.
Request: initiated by an intranet host. Modify the source IP address. If modified, it is defined by the Administrator.
Response: Modify the target IP address. nat automatically modifies the target IP address based on the tracing mechanism in the session table.

-- To-source [ipaddr [-ipaddr] [: port [-port]
[Root @ bkjia ~] Iptables-t nat-a postrouting-s 172.18.42.200-d 172.18.42.201-p tcp -- dport 80-j SNAT -- to-source 172.18.42.202
# The host requesting port 80 is the 172.18.42.202 host, but the host requesting port 80 is the 172.18.42.200 host


(4) DNAT (remote host requests local server): Destination Address Translation; occurs in prerouting
Modify the target IP address in the IP Message
Application Scenario: Wu fuqi in the local network uses a Unified Address to provide external services, but hides his real address.
Request: The target address of an Internet host is modified, which is defined by the Administrator.
Response: Modify the source address. However, nat automatically modifies the source address based on the tracing mechanism in the session table.
-- To-destination [ipaddr [-ipaddr] [: port [-port]
[Root @ bkjia ~] Iptables-t nat-a prerouting-s 172.18.42.200-d 172.18.42.201-p tcp -- dport 80-j DNAT -- to-destination 172.18.42.202
# The request is port 80 of 172.18.42.201, but the real service is port 80 of 172.18.42.202
[Root @ bkjia ~] Iptables-t nat-a prerouting-s 172.18.42.200-d 172.18.42.201-p tcp -- dport 80-j DNAT -- to-destination 172.18.42.202: 8080
# Port 8080 of 172.18.42.202

(5) MASQUERADE: source address conversion; occurs in postrouting
When the source address is a dynamically obtained address, MASQUERADE automatically determines the address to be converted.
[Root @ bkjia ~] Iptables-t nat-a postrouting-s 0/0-d 172.18.42.201-j MASQUERADE

For more iptables tutorials, see the following:

Disable the default firewall in CentOS 7.0 and enable the iptables firewall.

Iptables examples

Linux Firewall iptables

Basic use of iptables backup, recovery, and firewall scripts

Detailed description of firewall iptables usage rules in Linux

Iptables firewall settings in Linux

This article permanently updates the link address:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.