iptables, four tables and five chains, use cases and exercises

Keywords: Linux iptables

;

Catalog

One: What is a firewall

1. What is a firewall

2. Firewall Classification

  3. The principle of firewall

4. What filter network does the firewall pass through?    

5. What is a table

6. What is a chain

7. Scenarios for using chains

8. Relationship between tables and chains

9. iptables syntax format

10. How to achieve network filtering between tables and chains

11. What protocols support filtering

12. Actions to support filtering

14. Modules for Iptables

1. Use cases and exercises

2,Use Case 2

One: What is a firewall

1. What is a firewall

Software that prevents malicious intrusion into the server.

2. Firewall Classification

Logically speaking.Firewalls can be broadly divided into host firewalls and network firewalls.
    Host Firewall: Protects against a single host.
    Network firewall: often at the entrance or edge of the network, to protect the network entrance and serve the local area network behind the firewall.
    The network firewall and the host firewall do not conflict, which can be understood as network firewall outside (collective), host firewall inside (personal).


Physically, firewalls can be divided into hardware firewalls and software firewalls.
    Hardware firewall: part of the firewall function is implemented at the hardware level, while the other part is based on software implementation, which has high performance and cost.
    Software Firewall: A firewall that uses software processing logic to run on a common hardware platform with low performance and low cost.

  3. The principle of firewall

Operate the netfilter system security framework through iptables rules to achieve network security filtering.

Detailed description:
iptables It's not really a firewall. We can think of it as a client proxy that users can use iptables This proxy implements the user's security settings into the corresponding Security Framework, which is the real firewall. The name of this Framework is netfilter
netfilter Is the real security framework for firewalls ( framework),netfilter Located in kernel space.
iptables It's actually a command line tool, in user space, that we use to manipulate the real framework.
netfilter/iptables(Abbreviated as iptables)Form Linux Packet filtering firewalls under the platform, with most Linux Like the software, this packet filter firewall is free and can replace expensive commercial firewall solutions to complete packet filtering, packet redirection, and network address translation. NAT)And other functions.


Netfilter yes Linux A data package processing module within the core layer of the operating system that has the following capabilities:
Network Address Translation(Network Address Translate)
Packet Content Modification
 And firewall capabilities for packet filtering

So, although we use service iptables start start-up iptables"Services", but in fact, iptables There is no daemon, so it is not really a service, but a function provided by the kernel.

4. What filter network does the firewall pass through?    

Firewall filters the network through four tables and five chains.

Iptables is a package filtering firewall system integrated into the Linux kernel.With iptables, you can add and delete specific filtering rules. By default, iptables maintains four tables and five chains in which all firewall policy rules are written.

5. What is a table

    Tables are firewall security filtering rules with some specific functionality.

"Four tables"means iptables Function, default iptables Rule table has 
filter Table (Filter Rule Table) Firewall
nat Table (Address Translation Rules Table) network address translation Network address translation function;Kernel module: iptable_nat
mangle(The functions of modifying the table of data mark bit rules, disassembling message, making modifications, and re-encapsulating; iptable_mangle
raw(Tracking Datasheet Rule Table: Close nat Join tracking mechanisms enabled on tables; iptable_raw

filter Table: Controls whether packets are allowed in, out, and forwarded. Links that can be controlled are INPUT,FORWARD and OUTPUT. 
nat Table: Address translation in control packets. Links that can be controlled are PREROUTING,INPUT,OUTPUT and POSTROUTING. 
mangle: Modify the original data in the data package. Links that can be controlled are PREROUTING,INPUT,OUTPUT,FORWARD and POSTROUTING. 
raw: control nat The enablement of the connection tracking mechanism in the table. Links that can be controlled are PREROUTING,OUTPUT. 


6. What is a chain

    Chains place filtering rules for tables in specific places to execute.

"Five Chains refers to the control network in the kernel NetFilter Five rule chains defined.Each rule table contains multiple data chains:
INPUT(Inbound data filtering),
OUTPUT(Outbound data filtering),
FORWARD(Forward data filtering),
PREROUTING(Pre-route filtering),
POSTROUTING(Post-Route Filtering)

Firewall rules need to be written to these specific data chains.

 The filtering framework for the Linux firewall is as follows:

 If the external host sends the data package to the firewall itself, the data will go through the PREROUTING chain and the INPUT chain.If the firewall sends packets to the external host natively, the data will go through the OUTPUT and POSTROUTING chains.If the firewall is responsible for forwarding data as a route, the data will go through the PREROUTING, FORWARD, and POSTROUTING chains.
 

7. Scenarios for using chains

Inflow: PREROUTING   --->   INPUT
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	
	Flow out: POSTROUTING  <---   OUTPUT
	<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
	
	Flow through: PREROUTING  --->  FORWARD  --->  POSTROUTING
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

 Chain through which messages flow

reach B Messages for a process on the network: PREROUTING –> INPUT

from B A process in the network sends a message: OUTPUT –> POSTROUTING

from B Network forwarded messages: PREROUTING –> FORWARD –> POSTROUTING

 

8. Relationship between tables and chains

	filter :  INPUT   -->  FORWARD  -->  OUTPUT
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	
	nat : PREROUTING  --> INPUT  -->  OUTPUT  -->  POSTROUTING
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	
	mangle : PREROUTING --> INPUT  --> FORWARD  --> OUTPUT  --> POSTROUTING
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	
	raw : PREROUTING  -->   OUTPUT
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

9. iptables syntax format


The basic syntax format of the iptables command is as follows:

[root@liangxu ~]# iptables [-t table] COMMAND [chain] CRETIRIA -j ACTION

The meaning of each parameter is:

-t: Specify the firewall rule tables filter, nat, mangle, or raw that need to be maintained.The filter table is used by default when -t is not used.
COMMAND: Subcommand that defines the management of rules.
chain: Indicates the list of chains.
CRETIRIA: Match parameters.
ACTION: Triggers an action.
 

10. How to achieve network filtering between tables and chains

    Format: iptables -t Table Name Option Chain Name Criteria  action

    -t:                    Tables for specified operations
    -A, --append        Append a rule to the chain
    -D, --delete        Delete Rules in Chain
    -I, --insert        Insert a rule to the top
    -R, --replace        modify
    -L, --list            List current rules
    -S, --list-rules    List all rules
    -F, --flush            empty
    -Z, --zero            Empty counter(  Number of packages, package size)
    -X, --delete-chain    Delete a custom chain
    -P, --policy        Specify the default policy for the chain  
    
    -n                    Non-Inverse Solution
    -v                    Query in more detail
    --line--number         iptables Rule number
    -p                    Specify Agreement
    -j                    Specify Action
    

Parameters:
	-s source address
	-d Destination Address
	
	--sport	Port of source address
	--dport Port of destination address
	--to-ports Forwarded Port

	iptables Matching rules match from top to bottom



    [root@web01 ~]# iptables -F
    [root@web01 ~]# iptables -L
    [root@master ~]# iptables -L -v -n -t nat --line-number

11. What protocols support filtering

    TCP/UDP 
    ICMP    ping Agreement
    ALL        All Agreements

12. Actions to support filtering

Common:

ACCEPT        Release the data package and, after this processing, skip directly to the next rule chain instead of comparing other rules.
REJECT         Block the packet and send it to notify the other party.
DROP         The discarded package is not processed, and after this processing action, the filter will no longer be directly interrupted compared to other rules.
REDIRECT    Redirect the package to another port, and after this processing action, it will continue to compare with the other rules.


iptables Commands trigger actions and their respective functions

Trigger Action	Functions
ACCEPT		Allow packets to pass through
DROP		Drop the packet and don't give any response information. Clients will feel like their request is in the sea and will respond within a timeout.
REJECT		Information that denies a packet passage and, if necessary, gives a response to the data sender, and the client receives the rejection as soon as the request is made.
DNAT		Target Address Translation
SNAT		Source address translation to solve the problem of intranet users accessing the Internet with the same public network address.
MASQUERADE	Address spoofing, yes SNAT A special form suitable for dynamic, temporarily changing ip Up.
REDIRECT	Redirect, map ports locally
LOG			Record Packet Information syslog Said in/var/log/messages Log information is recorded in the file, and then the data package is passed to the next rule, which means that the next rule matches without doing anything else with the data package except logging.

14. Modules for Iptables

multiport Modular
	
		Multiple ports can be specified.
		
		--dports 


iprange Modular
	
	Match multiple IP Or network segment
	
	--src-range from[-to]:	Source address range
    --dst-range from[-to]:	Target Address Range

string Modular
	Include those strings in the matched data package
        --string pattern	# Specify a string to match
        --algo {bm|kmp}		# Matching query algorithm


time Modular
	Match message based on time(Time used is UTC). 
		--timestart hh:mm[:ss]		#  start time
       	--timestop hh:mm[:ss]		# End time
		--monthdays day[,day...]	# Specify a day of the month
		--weekdays day[,day...]		# Specify Week or Sunday 

icmp Modular
	--icmp-type {type[/code]|typename}
		echo-request  (8) request 
		echo-reply    (0) Respond


connlimit Modular
       --connlimit-upto n		#  Match if the number of existing connections is less than or equal to n
       --connlimit-above n		#  Match if the number of existing connections is greater than n


limit Modular

	# Limit the message rate.Seconds, minutes, hours, days.
       --limit rate[/second|/minute|/hour|/day] # Number of Messages
       --limit-burst number  # Number of messages (default: 5)

1. Use cases and exercises

Exercise 1: Please explain that access is prohibited B How to implement the network

	Table: filter
	Chain: INPUT
iptables -t filter  -I INPUT  -s 10.10.10.10  -p ALL -j DROP

Exercise 2: Implement no access to this machine
	iptables -t filter  -I INPUT  -p ALL -j DROP
	
	
Exercise 3: Prohibit ping Native Machine
	[root@web01 ~]# iptables -t filter -I INPUT -p icmp -j REJECT


Exercise 3: Access to 192 is only allowed.168.230.7 Port 22
	iptables -t filter -I INPUT -p tcp --dport 22 -j ACCEPT 
	iptables -t filter -A INPUT -p tcp -j DROP
	
Exercise 4: Only 192 allowed.168.230.61 Visit 192.168.230.7 Port 80 of
	iptables -t filter -I INPUT -p tcp -s 192.168.230.61 --dport 80 -j ACCEPT
	iptables -t filter -A INPUT -p tcp --dport 80 -j DROP

Exercise 5: Require access to 192.168.230.7 Forward port 8080 to port 80 and allow only 192.168.230.61 Visit 192.168.230.7 Port 8080 of
	
	iptables -t nat -I PREROUTING -p tcp -s 192.168.230.61 --dport 8080 -j REDIRECT --to-port 80
	iptables -t filter -I INPUT -p tcp --dport 8080 -s 192.168.230.61 -j ACCEPT 
	iptables -t filter -I INPUT -p tcp --dport 22 -j ACCEPT 

	[root@web01 ~]# iptables -t filter -R INPUT 2 -p tcp --dport 8080 -s 192.168.230.61 -j ACCEPT 


Iptables Modules, corresponding to links

1, multiport Modular
	
		Multiple ports can be specified.		
		--dports 
	
Exercise 6: Only 80, 443, 8080 ports are allowed, using one iptables rule

	iptables -t filter -I INPUT -p tcp -m multiport --dports 80,443,8080,22 -j ACCEPT
	iptabels -t filter -A INPUT -p tcp -j DROP

Exercise 7: Only 192 allowed.168.230.61 Visit 192.168.230.7 Ports 80 and 443 of
	iptables -t filter -I INPUT -p tcp -s 192.168.230.61 -m multiport --dports 80,443-j ACCEPT
	iptabels -t filter -A INPUT -p tcp -j DROP

2, iprange Modular
	
	Match multiple IP Or network segment
	
	--src-range from[-to]:	Source address range
    --dst-range from[-to]:	Target Address Range
	
Exercise 8: Prohibit 192.168.230.0/24 Machine access for network segments

	iptables -t filter -I INPUT -p tcp -m iprange --src-range 192.168.230.1-192.168.230.254 -j DROP

Exercise 9: Only 192 allowed.168.230.0/24 Machine Access 192 for Segments.168.230.7 Port 80 of
	
	iptables -t filter -I INPUT -p tcp -m iprange --src-range 192.168.230.1-192.168.230.254 --dport 80 -j ACCEPT
	iptables -t filter -A INPUT -p tcp -j DROP

4,string Modular
	Include those strings in the matched data package
        --string pattern	# Specify a string to match
        --algo {bm|kmp}		# Matching query algorithm

Exercise 10: When data contains hello Character, all access is not allowed

	[root@web01 hello]# yum install httpd -y
	[root@web01 hello]# systemctl start httpd
	[root@web01 ~]# echo "hello world" > /var/www/html/1.html
	[root@web01 ~]# echo "Hello World" >/var/www/html/2.html

	[root@web01 hello]# iptables -t filter -I OUTPUT -p tcp -m string --string "hello" --algo kmp -j DROP
	
Exercise 11: When data contains China Character, all allowed access, other not allowed.
	 iptables -t filter -I OUTPUT -p tcp -m string --string "China" --algo kmp -j ACCEPT
 	 iptables -t filter -A OUTPUT -p tcp   -j DROP

5,time Modular
	Match message based on time(Time used is UTC). 
		--timestart hh:mm[:ss]		#  start time
       	--timestop hh:mm[:ss]		# End time
		--monthdays day[,day...]	# Specify a day of the month
		--weekdays day[,day...]		# Specify Week or Sunday 
Exercise 12: Require 8:30-10 a.m.:30 No access between
	[root@web01 ~]# iptables -t filter -I INPUT -p tcp --dport 80 -m time --timestart 6:30  --timestop 9:30 -j DROP

Exercise 13: Require 7 a.m.:30 - 9:30 And 14:30 - 17:30 Can't access between, other periods can.
	[root@web01 ~]# iptables -t filter -I INPUT -p tcp --dport 80 -m time --timestart 23:30 --timestop 1:30  -j DROP
	[root@web01 ~]# iptables -t filter -I INPUT -p tcp --dport 80 -m time --timestart 6:30 --timestop 9:30  -j DROP

6,icmp Modular
	--icmp-type {type[/code]|typename}
		echo-request  (8) request 
		echo-reply    (0) Respond

Exercise 14: Asking others not to ping This machine, but this machine can ping Others
	[root@web01 ~]# iptables -t filter -I INPUT -p icmp -m icmp --icmp-type echo-request -j DROP

Exercise 15: Native machine is required to ping Baidu, only 192.168.230.61 Yes? ping Native Machine
	iptables -t filter -I INPUT -p icmp -m icmp --icmp-type echo-request -j DROP
	iptabels -t filter -I INPUT -p icmp -s 192.168.230.61 -j ACCEPT
	iptables -t filter -A INPUT -p icmp -j DROP

7,connlimit Modular
       --connlimit-upto n		#  Match if the number of existing connections is less than or equal to n
       --connlimit-above n		#  Match if the number of existing connections is greater than n

Exercise 16: Only two machines are allowed to link to this machine at the same time
    yum install telnet* -y
    systemctl start telnet.socket
    
    iptables -t filter -I INPUT -p tcp -m connlimit --connlimit-upto 2 -j ACCEPT
    iptables -t filter -A INPUT -p tcp -j DROP

Exercise 17: Only one machine is allowed to link to this machine at the same time
	yum install telnet* -y
    systemctl start telnet.socket
    
    iptables -t filter -I INPUT -p tcp -m connlimit --connlimit-upto 1 -j ACCEPT
    iptables -t filter -A INPUT -p tcp -j DROP
   
8,limit Modular

	# Limit the message rate.Seconds, minutes, hours, days.
       --limit rate[/second|/minute|/hour|/day] # Number of Messages
       --limit-burst number  # Number of messages (default: 5)

	# 1. Speed Limit: Limit the bandwidth of the transmission to around 500k (500 * 1000 = 500000 / 1500 = 333 packets)
	[root@web01 ~]# iptables -t filter -I INPUT 1 -p tcp -m limit --limit 9000/s -j ACCEPT
	[root@web01 ~]# iptables -t filter -A INPUT -p tcp -j DROP
	
	# 2. Allow 10 datagrams to pass quickly, exceeding 1/m
	[root@web01 ~]# iptables -t filter -I INPUT -p icmp -m limit --limit-burst 10  --limit 1/m -j ACCEPT
	[root@web01 ~]# iptables -t filter -A INPUT -p tcp -j DROP
	
	# 3. Restrict receiving 10 icmp datagrams per minute,
    [root@web01 ~]# iptables -t filter -I INPUT -p icmp -m limit --limit 10/m -j ACCEPT
    [root@web01 ~]# iptables -t filter -A INPUT -p icmp -j DROP

# case
    Open local to all addresses tcp(80,22,8080-9090)Port Access
    Allow native based access to all addresses ICMP Packet Access to Protocol
    Access is prohibited on other ports that are not allowed
    
        iptables -t filter -I INPUT -p tcp -m multiport  --dport 80,22,8080:9090  -j ACCEPT
        iptables -t filter -I INPUT -p icmp -j ACCEPT
        iptables -t filter -A INPUT -j DROP

Use Case 2

Viewing and Clearing Rules
 Use iptables Commands can view, add, modify, and delete specific rules

1) View Rules
 Viewing rules requires the following commands:

[root@liangxu ~]# iptables -nvL

The meaning of each parameter is:

-L Represents all rules for viewing the current table, which is the default filter Table, if you want to view nat Table, you can add -t nat Parameters.
-n Wrong Representation IP The address is checked back, and this parameter will display faster.
-v Represents the output details, including the number of packets, the total number of bytes, and the corresponding network interface through the rule.

[Example 1) View the rules.First need to use su Command to switch the current user to root User.Then enter the following command on the terminal page:

[root@liangxu ~]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination        
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     icmp --  anywhere             anywhere           
ACCEPT     all  --  anywhere             anywhere           
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ssh
REJECT     all  --  anywhere             anywhere            reject-with icmp-host-prohibited
 Copy Code
2) Add Rule

There are two parameters for adding a rule: -A and -I. among -A Is added to the end of the rule;-I It can be inserted at the specified location, which is inserted at the top of the rule by default if there is no specified location.

[Example 2) View the current rule.First need to use su Command to switch the current user to root The user then enters the command on the terminal page as follows:

[root@liangxu ~]# iptables -nL --line-number
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination        
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
2    ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0          
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0          
4    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:22
5    REJECT     all  --  0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited

[Example 3) Add a rule to the end.First need to use su Command to switch the current user to root The user then enters the following command on the terminal page:

[root@liangxu ~]# iptables -A INPUT -s 192.168.1.5 -j DROP
[root@liangxu ~]# iptables -nL --line-number
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination        
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
2    ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0          
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0          
4    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:22
5    REJECT     all  --  0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited
6    DROP       all  --  192.168.1.5          0.0.0.0/0    

3) Modify Rules

Required when modifying rules-R Parameters. 
[Example 4) Add the DROP Modify to ACCEPT. First need to use su Command to switch the current user to root The user then enters the following command on the terminal page:

[root@liangxu ~]# iptables -R INPUT 6 -s 194.168.1.5 -j ACCEPT
[root@liangxu ~]# iptables -nL --line-number
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination        
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
2    ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0          
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0          
4    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:22
5    REJECT     all  --  0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited
6    ACCEPT     all  --  194.168.1.5          0.0.0.0/0   

Comparisons show that the target Modified to ACCEPT. 

4) Delete Rule

There are two ways to delete a rule, but both must use -D Parameters. 
[Example 5) Delete the rule added in line 6.First need to use su Command to switch the current user to root The user then enters the following command on the terminal page:

[root@liangxu ~]# iptables -D INPUT 6 -s 194.168.1.5 -j ACCEPT

or

[root@liangxu ~]# iptables -D INPUT 6

Note that sometimes rules that need to be deleted are longer and a large list of code needs to be written to make them easier to write incorrectly, so you can use them first -line-number Find the line number of the rule and delete the rule by line number.

Posted by biz0r on Sat, 04 Sep 2021 19:35:01 -0700