day55 network security

Keywords: Linux Operation & Maintenance cloud computing Cyber Security

Firewall

Firewall function

In the computer field, firewall is a device used to protect information security. It will allow or restrict data transmission according to user-defined rules.

  • A device used to protect intranet security
  • Protection according to rules
  • User defined rules
  • Allow or deny access to external users

Firewall classification

  • Logically, firewalls can be roughly divided into host firewalls and network firewalls \ host firewalls: protection for a single host \ network firewalls: protection for the network, at the edge of the network, behind the firewall is the local LAN \ network firewall outside the host (service collective), and within the host firewall (service individual)
  • Physically, the firewall can be divided into hardware firewall and software firewall. Hardware firewall: realize the firewall function at the hardware level, and the other part is based on software, which has high performance and high hardware cost
    Software firewall: a firewall whose application software processing logic runs on a general hardware platform. Its performance is lower than that of hardware firewall and its cost is lower. It has been brought with Linux system and can be used directly

Firewall Performance

  • throughput
  • Concurrent connection
  • make new connection
  • time delay
  • shake

Hardware firewall

Hardware firewall definition

Hardware firewall refers to the hardware device that embeds the software with configuration packet passing rules into the hardware device to provide security protection for the network. More common at the edge of the network.

Function of hardware firewall

{width="6.929994531933509in" height="4.428943569553806in"}

Hardware firewall brand

  • Juniper

cisco Cisco ASA

  • Huawei

Software firewall

Software firewall is to use software with configuration packet passing rules alone to realize packet filtering. Most common in single host systems or personal computers.
{width="6.273468941382327in" height="5.022942913385827in"}

Extension: Web application firewall (WAF)

Web application firewall is a security protection device (software) for web protection (web page protection). It is mainly used to intercept all HTTP data or sessions that only meet some rules. It is more common in cloud platforms.
{width="6.210942694663167in" height="2.4593657042869643in"}

Comparison between hardware firewall and software firewall

Hardware firewall has independent hardware equipment, with high operation efficiency and slightly higher price, which can provide security protection for computer network. The software firewall must be deployed on the host system. Compared with the hardware firewall, the operation efficiency is low, which will affect the performance of the host system to a certain extent. It is generally used in single machine system or personal computer, not directly used in computer network.

iptables

What are iptables?

  • iptables is not a firewall, but a firewall user agent
  • Used to add the user's security settings to the security framework
  • "Security framework" is a firewall
  • The name of "security framework" is net "lter. Net" lter is located in the kernel space and is a packet processing module within the core layer of Linux operating system
  • iptables is a command-line tool for operating net "lter" in kernel space in user space

netfilter/iptables function

net "lter/iptables" can be referred to as iptables for short. It is an open source packet filtering firewall under Linux platform. It comes with the kernel and can replace the enterprise hardware firewall with high cost. It can realize the following functions:

  • Packet filtering, i.e. firewall

  • Packet redirection, i.e. forwarding

  • Network address translation, i.e. NAT

    Note:
    Generally, iptables is not the "service" of firewall, but the service is provided by kernel.

iptables concept

iptables work basis ----- rules

ptables work basis - Rules iptables act according to rules, and rules are the conditions defined by the operation and maintenance personnel; The rule is generally defined as "if the packet header meets such conditions, the packet will be processed in this way".

The rules are stored in the packet filtering table in the kernel space. These rules specify the source address, destination address, transmission protocol (TCP, UDP, ICMP) and service type (HTTP, FTP) respectively.

When the packets match the rules, iptables processes the packets according to the methods defined by the rules, such as accept, reject, drop, etc

The main work of configuring firewall is to add, modify and delete iptables rules

The concept of chain in iptables

For example:
When the client accesses the web service of the server, the client sends the access request message to the network card, and the tcp/ip protocol stack belongs to the kernel. Therefore, the request message of the client will be transmitted to the web service in user space through the TCP protocol of the kernel, and the target address of the client message is the socket (ip:port) monitored by the web server, When the web server responds to the client's request, the target address of the response message responded by the web service is the client's address. As we said, net "lter is the real firewall and part of the kernel. Therefore, if we want net" lter to work, we need to set "gateways" in the kernel, so all incoming and outgoing data messages should pass through these gateways and be checked, Those that meet the release conditions are allowed to release, and those that meet the blocking conditions are blocked. Therefore, input and output gateways appear. However, in iptables, we call gateways "chains".

{width="6.929994531933509in" height="4.585259186351706in"}

In the above example, if the server address contained in the message sent by the client to the local machine is not the local machine, but other servers, the local machine should be able to forward, and this forwarding is the IP supported by the local kernel_ Forward function. At this time, our host is similar to the router function, so we will see that in iptables, there are only the input and output mentioned above, and there should be "before routing", "forwarding" and "after routing",

Their corresponding English names are "preceding", "FORWARD" and "POSTROUTING", which is the 5 chain we are talking about.

{width="6.929994531933509in" height="3.5744181977252842in"}

It can be seen from the above figure that when we start the firewall function locally, the data message needs to pass through the above gateway. According to the situation of each message, the "chain" of each registration may be different. If the message target address is local, it will often send the input chain to the local user space. If the message target is not local, forward chain and postrouting chain will be forwarded directly in kernel space.

Sometimes we often hear people call input "rule chain". What's going on? We know that the function of firewall is to match the rules of data packets passing through and then perform the corresponding "actions". Therefore, when data packets pass through these checkpoints, they must match the gateway rules. However, there may be more than one gateway rule, and there may be many. When we put many rules on one gateway, all data packets often have to be matched, Then a rule chain to match is formed, so we also call "chain" as "rule chain".

{width="6.679889545056868in" height="5.616943350831146in"}

  • INPUT: Processing inbound packets
  • OUTPUT: Processing outbound packets
  • forward: process and forward data packets (mainly forward data packets to other local network cards). When data packets pass through the local machine, the network card receives data packets to the buffer. The kernel reads the ip header of the message and finds that the message is not sent to the local machine (the destination ip is not the local machine), the kernel directly sends it to the forward chain for matching. After matching, if the forward rules are met, Then it is sent to the next hop or destination host via postrouting.
  • Routing: process packets before routing, and modify the destination IP address of packets arriving at the firewall to judge the target host
  • POSTROUTING: process the packet after routing, modify the source IP address of the packet to leave the firewall, and determine which interface to send to the next hop
Table concept in iptables

A string of rules is set on each "rule chain". In this way, we can combine different "rule chains" into a set classification that can complete a specific function. This set classification is called table. Iptables has five tables in total. To learn iptables, we need to understand the role of each table.

  • Filter: filter function to determine whether to release the packet. It belongs to a real firewall. Kernel module: iptables_ filter
  • Nat: network address translation function to modify the source, target IP address or port in the packet; Kernel module: iptable_nat
  • Mangle: re encapsulate the data packet and set the tag for the data packet; Kernel module: iptable_mangle
  • Raw: determine whether to track the packet; Kernel module: iptables_raw
  • security: whether to define mandatory access control rules; Added after
Relationship between watch chains in iptables

For the relationship between table chains in iptables, we use the table as the operation entry when applying the firewall. As long as we add rules to the rule chain in the corresponding table, we can realize a certain function. Then we should know which table includes which rule chains, and then operate on the rule chain.

  • What chains can be used in the "fi lter" table to define rules: INPUT,FORWARD,OUTPUT

  • Which chains can be used in nat table to define rules: preouting, output, postrouting, input

  • Which chains can be used to define rules in the mangle table:

  • PREROUTING,INPUT,FORWARD,OUTPUT,POSTROUTING

  • What chains can be used in the raw table to define rules: preouting, output

    [external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-x8fdoc2m-1633783934030)( http://r0l2wcel3.hn-bkt.clouddn.com//blog/image178.png )]{width=“6.919573490813648in” height=“3.845365266841645in”}

Table priority in iptables

Raw mangle NAT - filter (from high to low)

Data packets flow through iptables process

{width="6.929994531933509in" height="3.418102580927384in"}

iptables rule matching and action

Rule: try to match each packet flowing through here according to the specified matching criteria. If the matching is successful, it will be processed by the processing action specified in the rule. Rules are composed of matching conditions and actions. What are the rules?

For example: two students, one with white hair and one with black hair, enter the classroom at the same time, and the condition for entering the classroom is that only black hair can enter, white hair refuses to enter, black hair and white hair are matching conditions, and entering and refusing to enter is action.

iptables rule matching criteria classification

Basic matching conditions:

Source address, destination address, source port, destination port, etc

Basic matching use options and functions

-p Specify the rule agreement, tcp udp icmp all
-s Specify the source address of the packet, ip hostname
-d Specify destination address
-i Input interface
-o Output interface                                              
 ! Reverse

The basic matching feature is that there is no need to load the extension module and the matching rules take effect

Extended matching criteria:

Extended matching is divided into explicit matching and implicit matching.

The feature of extension matching is that the extension module needs to be loaded before the matching rule can take effect.
Characteristics of implicit matching: when using the - p option to specify the protocol, it is no longer necessary to use the - m option to specify the extension module and no need to load the extension module manually; Display matching features: the - m option must be used to indicate the extension mechanism of the extension module to be called and the need to load the extension module manually.

Implicit matching options and functions

-p tcp
	--sport Match the source port of the message; Multiple ports can be given, but only continuous port ranges can be given
	--dport Matching message target port; Multiple ports can be given, but only continuous port ranges can be given
	--tcp-flags mask comp Matching in message tcp Flag bit of the protocol

-p udp
	--sport Match the source port of the message; Multiple ports can be given, but only continuous port ranges can be given
	--dport Matching message target port; Multiple ports can be given, but only continuous port ranges can be given

--icmp-type
 0/0:  echo reply Allow other hosts ping\
 8/0: echo request allow ping Other hosts

Explicit matching use options and functions

  • Multiport multiport
iptables -I INPUT -d [192.168.2.10](http://192.168.2.10) -p tcp -m multiport --dports 22,80 -j ACCEPT # opens the local tcp 22 and tcp80 ports in the INPUT chain

iptables -I OUTPUT -s [192.168.2.10](http://192.168.2.10) -p tcp -m multiport --sports 22,80 -j ACCEPT # opens the origin ports tcp 22, tcp80 in the OUTPUT chain
  • iprange multiple ip addresses
iptables -A INPUT -d [192.168.2.10](http://192.168.2.10) -p tcp --dport 23 -m iprange --src-range 192.168.2.11-192.168.2.21 -j ACCEPT

iptables -A OUTPUT -s [192.168.2.10](http://192.168.2.10) -p tcp --sport 23 -m iprange --dst-range 192.168.2.11-192.168.2.21 -j ACCEPT
  • Time specifies the access time range

    iptables -A INPUT -d [192.168.2.10](http://192.168.2.10) -p tcp \--dport 901 -m time \--weekdays Mon,Tus,Wed,Thu,Fri \--timestart 08:00:00 \--time-stop 18:00:00 -j ACCEPT
    
    iptables -A OUTPUT -s [192.168.2.10](http://192.168.2.10) -p tcp \--sport 901 -j ACCEPT
    
  • string
    String to detect the string pattern matching of the application layer data in the message (realized by algorithm).

    --algo {bm|kmp}: Algorithm used in character matching lookup
    --string "STRING": String to find
    --hex-string "HEX-STRING": The character to find is encoded into hexadecimal format
    
  • connlimit
    Connection limit: limit the number of concurrent connections according to each client IP.

    limit

Message rate limit

state

Tracks the status of data messages between requests and responses on the machine. There are five statuses: invalid, established, new, retired,

UNTRACKED.

Actions in iptables rules

The actions in iptables rules are often called target, which can also be divided into basic actions and extended actions.

--algo {bm|kmp}: Algorithm used in character matching lookup
--string "STRING": String to find
--hex-string "HEX-STRING": The character to find is encoded into hexadecimal format
  • connlimit
    Connection limit: limit the number of concurrent connections according to each client IP.
 --connlimit-upto n  Number of connections is less than or equal to n Time matching
 --connlimit-above n Number of connections greater than n Time matching
  • limit
    Message rate limit

-state
Tracks the status of data messages between requests and responses on the machine. There are five statuses: invalid, established, new, retired,
UNTRACKED.

--state state
NEW New connection request
ESTABLISHED Established connection
INVALID Unrecognized connection
RELATED Associated connection. The current connection is a new request, but it is attached to an existing connection
UNTRACKED Untraceable connections
1,For the entered status is ESTABLISHED Should be released;

2,The status of going out is ESTABLISHED Should be released;

3,Strictly check that the entered status is NEW Connection of;

4,All States are INVALIED Should refuse;

Actions in iptables rules
The actions in iptables rules are often called target, which can also be divided into basic actions and extended actions.

  • ACCEPT: allow packets to pass
  • DROP: directly discard the data packet without giving any response information
  • REJECT: REJECT the packet and send the response information to the client
  • SNAT: source address translation
    • Explanation 1: when a packet is sent from the network card, the source address in the packet is replaced with the specified IP. The receiver thinks that the source of the packet is the IP host to be replaced. When returning the response, it also uses the replaced IP address.
    • Explanation 2: modify the data packet source address. When the internal network data packet reaches the firewall, the firewall will replace the source IP address of the data packet with the external address (the destination IP address remains unchanged), so that the internal host of the network can communicate with the external host of the network.
      {width="5.106311242344707in" height="1.7715769903762029in"}
iptables -t nat -A POSTROUTING -s 192.168.10.0/24 -o eth1 -j SNAT --to-source 
202.12.10.100
  • MASQUERADE: camouflage, similar to SNAT, is applicable to dynamic and temporary IP addresses, such as broadband for home use. Replace the source IP with the IP on the network card sending data. It is used when the IP address is not fixed.
  • DNAT: destination address translation
    • Explanation 1: when the data packet is sent from the network card, the destination IP in the data packet is modified, which shows that you want to access A, but because the gateway makes DNAT, the destination IP address in all data packets accessing A is modified to B, and the actual final access is B.
    • Explanation 2: change the destination address of the packet. When the firewall receives the packet from the external network, it will replace the destination IP address of the packet (the source IP address remains unchanged) and re forward it to the host of the internal network.
iptables -t nat -A PREROUTING -d 202.12.10.100 -p tcp --dport 80 -j DNAT --to-
destination 192.168.10.1
  • REDIRECT: do port mapping on the local machine
  • LOG: record the LOG information in the / var/log/message file, and then pass the packet to the next rule.

The route is selected according to the destination address. Therefore, DNAT is carried out on the forwarding chain, and SNAT is carried out when the data packet is sent, so it is carried out on the POSTROUTING chain.

Develop iptables rules and policies
  • blacklist

    Traffic that has not been rejected can pass through. Under this strategy, the administrator must formulate new rules for each new attack, so it is not recommended

  • White list

    All traffic that is not allowed should be rejected. This strategy is relatively conservative. The host is gradually opened as needed. At present, the white list policy is generally adopted
    Omitted, recommended.

Thoughts on formulating iptables rules
  1. Select a table that determines the data message processing method
  2. Select a chain that determines where the data message flows through
  3. Select the appropriate condition, which determines the condition matching for the data message
  4. Select the action of processing data message and formulate corresponding firewall rules
iptables basic syntax structure
iptables [-t   Table name  ]   Management options   [  Chain name  ] [  Condition matching  ] [-j   Target action or jump  ]

If you do not specify a table name, it means the "fi lter" table by default. If you do not specify a chain name, it means all chains in the table by default. Unless you set the default policy of the rule chain, you need to specify the matching criteria.

{width="6.252626859142607in" height="4.1684175415573055in"}

iptables chain management method
   -N, --new-chain chain: Create a custom rule chain;        
   -X, --delete-chain [chain]: Delete the empty chain with user-defined reference count of 0;        
   -F, --flush [chain]: Clear the rules on the specified rule chain;        
   -E, --rename-chain old-chain new-chain: Rename the chain;        
   -Z, --zero [chain [rulenum]]: Zero setting counter;          Note: each rule has two counters          packets: The number of all messages matched by this rule;          bytes: The sum of the sizes of all messages matched by this rule;        
   -P, --policy chain target Formulate the strategy of linked list(ACCEPT|DROP|REJECT)

iptables rule management
      -A, --append chain rule-specification: Append a new rule to the tail of the specified chain;         
      -I, --insert chain [rulenum] rule-specification: Insert a new rule at the specified position of the specified chain. The default is the head;        
      -R, --replace chain rulenum rule-specification: Replace the specified rule with a new one;        
      -D, --delete chain rulenum: Delete the rule according to the rule number;        
      -D, --delete chain rule-specification: Delete the rule according to the rule itself;

iptables rule display
         -L, --list [chain]  : List rules;           
         -v, --verbose: Details;            -vv More detailed information           
         -n, --numeric: Display host address and port number in digital format;           
         -x, --exact: Display the exact value of the counter instead of the rounded data;           --line-numbers: When a rule is listed, its corresponding number on the chain is displayed           
         -S, --list-rules [chain]: Display all rules of the specified chain;

iptables application

  • Environment centos7
Iptables services installation
[root@localhost ~]# yum -y install iptables-services

Iptables command exists by default in CentOS 7 system. This command is only a simple query and operation command, and does not include configuration files. Install iptables-
After services, the configuration file will be generated directly to save the configuration. Including ipv4 and ipv6.

  • Set service on
[root@localhost ~]# systemctl start iptables.service
  • Set startup and self startup
[root@localhost ~]# systemctl enable iptables.services
  • View profile
[root@localhost ~]# rpm -ql iptables-services
  • Save rule
[root@localhost ~]# iptables-save > /etc/sysconfig/iptables
  • heavy load
[root@localhost ~]#iptables-restore < /etc/sysconfig/iptables
  • Basic configuration
iptables -F
#Delete existing rule
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP
#Configure default chain policy

Case: white list

[root@localhost ~]# iptables -t filter -F
[root@localhost ~]# iptables -P INPUT DROP
[root@localhost ~]# iptables -t filter -I INPUT -p tcp --dport=22 -j ACCEPT
[root@localhost ~]# iptables -t filter -I INPUT -p tcp --dport=80 -j ACCEPT

Case: blacklist

[root@localhost ~]# iptables -P INPUT ACCEPT
[root@localhost ~]# iptables -F
[root@localhost ~]# iptables -t filter -A INPUT -s 192.168.2.20/24 -p tcp --dport 80 -j
DROP

Case: accessing native data via lo

[root@localhost ~]# iptables -I INPUT -d 127.0.0.1 -p tcp --dport=9000 -i lo -j ACCEPT

[root@localhost ~]# iptables -I INPUT -i lo -j ACCEPT
#Allow access to this computer through the local loopback network card

Case: allow connected state to generate derivative ecology

[root@localhost ~]# iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

iptables filter table application case

Case 1:

[root@localhost ~]# yum -y install httpd vsftpd sshd
[root@localhost ~]# systemctl start httpd vsftpd sshd

[root@localhost ~]# iptables -t filter -F
[root@localhost ~]# iptables -I INPUT -p tcp --dport 80 -j ACCEPT
[root@localhost ~]# iptables -I INPUT -p tcp --dport 20:21 -j ACCEPT
[root@localhost ~]# iptables -I INPUT -p tcp --dport 22 -j ACCEPT
[root@localhost ~]# iptables -A INPUT -j REJECT

#Existing problems
 This computer cannot access this computer
 For example: ping 127.0.0.1
 resolvent
[root@localhost ~]# iptables -I INPUT -i lo 

 -j ACCEPT

This computer cannot access other hosts
 For example: ssh remote_host
 resolvent
[root@localhost ~]# iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

FTP cannot access
 Solution 1:
[root@localhost ~]# iptables -I INPUT -p tcp --dport 20:21 -j ACCEPT
[root@localhost ~]# vim /etc/vsftpd/vsftpd.conf
pasv_min_port=50000
pasv_max_port=60000
[root@localhost ~]# iptables -I INPUT -p tcp --dport 50000:60000 -j ACCEPT

Solution 2: use the connection tracking module
[root@localhost ~]# iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
[root@localhost ~]# iptables -I INPUT -p tcp --dport 20:21 -j ACCEPT
[root@localhost ~]# modprobe nf_conntrack_ftp #Temporary method, add connection tracking module

[root@localhost ~]# vim /etc/sysconfig/iptables-config
IPTABLES_MODULES="nf_conntrack_ftp" 
#Load when starting service
#For the data port connection, the first state of the three handshakes is recognized as released by NEW

Case 2: iptables standard process

[root@localhost ~]# iptables -F
[root@localhost ~]# iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
[root@localhost ~]# iptables -A INPUT -i lo -j ACCEPT
[root@localhost ~]# iptables -A INPUT -s 192.168.2.0/24 -j ACCEPT #Allow any access to the Intranet
[root@localhost ~]# iptables -A INPUT -p tcp --syn --dport 80 -j ACCEPT
[root@localhost ~]# iptables -A INPUT -p tcp --syn --dport 22 -j ACCEPT
[root@localhost ~]# iptables -A INPUT -p tcp --syn --dport 21 -j ACCEPT
[root@localhost ~]# iptables -A INPUT -j REJECT
[root@localhost ~]# modprobe nf_conntrack_ftp
[root@localhost ~]# iptables-save > /etc/sysconfig/iptables
[root@localhost ~]# vim /etc/sysconfig/iptables-config
IPTABLES_MODULES="nf_conntrack_ftp"

Case 3: extended matching

#-m icmp
[root@localhost ~]# iptables -F
[root@localhost ~]# iptables -t filter -I INPUT -p icmp -m icmp --icmp-type echo-reply

 

-j ACCEPT #Allow ping response
[root@localhost ~]# iptables -A INPUT -j REJECT

#-m iprange
[root@localhost ~]# iptables -t filter -I INPUT -m iprange --src-range 192.168.2.10-
192.168.2.100 -j REJECT

#-m multiport
[root@localhost ~]# iptables -t filter -I INPUT -p tcp -m multiport --dports 
20,21,22,25,80,110 -j ACCEPT

#-m tos filters according to the ip protocol header type of service
[root@localhost ~]# iptables -F
[root@localhost ~]# tcpdump -i eth0 -nn port 22 -vvv 
 #Grab the ssh packets accessed by the remote host and observe the TOS value
[root@localhost ~]# tcpdump -i eth0 -nn port 22 -vvv
 #Grab the file copied remotely from the local rsync or scp, and observe the TOS value
 #ssh: tos 0x0  0x10
 #scp: tos 0x0  0x8
 #rsync: tos 0x0 0x8
[root@localhost ~]# iptables -t filter -A INPUT -p tcp --dport 22 -m tos --tos 0x10 -j

 

ACCEPT
[root@localhost ~]# iptables -t filter -A INPUT -j REJECT

#-m tcp matches by TCP control bit
Flags:SYN ACK FIN RST URG PSH  ALL NONE
[root@localhost ~]# iptables -t filter -A INPUT -p tcp -m tcp --tcp-flags 
SYN,ACK,FIN,RST SYN --dport 80 -j ACCEPT
[root@localhost ~]# iptables -t filter -A INPUT -p tcp --syn --dport 80 -j ACCEPT
#--TCP flags SYN, ACK, fin, RST SYN check the four flag bits. Only the SYN flag bits match, that is, only the first of the three handshakes is allowed
 Handshake, equivalent to--syn

#-m comment comments on the rules
[root@localhost ~]# iptables -A INPUT -s 192.168.2.250 -m comment --comment "cloud 
host" -j REJECT

#-m mark uses the marking method of the mangle table and is used in conjunction with the mangle table
[root@localhost ~]# iptables -t filter -A INPUT -m mark 2 -j REJECT

Case 4: extension action

#-j LOG to log
[root@localhost ~]# grep 'kern.*' /etc/rsyslog.conf
kern.* /var/log/kernel.log
[root@localhost ~]# systemctl restart rsyslog 
[root@localhost ~]# iptables -j LOG -h
[root@localhost ~]# iptables -t filter -A INPUT -p tcp --syn --dport 22 -j LOG --log-
prefix " localhost_ssh "
[root@localhost ~]# iptables -t filter -A INPUT -p tcp --syn --dport 22 -j ACCEPT
[root@localhost ~]# iptables -t filter -A INPUT -j REJECT

#-j REJECT
 When accessing an unopened TCP Port, should return a RST Marked packets
 When accessing an unopened UDP Port, result return port xxx unreachable
 When accessing an open TCP Port, but by firewall REJECT,Result return port xxx unreachable
[root@localhost ~]# iptables -j REJECT -h
[root@localhost ~]# iptables -t filter -A INPUT -p tcp --dport 22 -j REJECT --reject-
with tcp-reset //Returns a custom message type

#-j MARK, which can be applied in LVS scheduler
[root@localhost ~]# iptables -t mangle -L
[root@localhost ~]# iptables -j MARK -h
[root@localhost ~]# iptables -t mangle -A PREROUTING -s 192.168.2.110 -j MARK --set-
mark 1
[root@localhost ~]# iptables -t mangle -A PREROUTING -s 192.168.2.25 -j MARK --set-
mark 2
[root@localhost ~]# iptables -t filter -A INPUT -m mark --mark 1 -j ACCEPT / / match according to the mark
 match
[root@localhost ~]# iptables -t filter -A INPUT -m mark --mark 2 -j REJECT
iptables nat table application case
  • nat table function

    Diversion

  • nat table action location

    The virtual machine or virtual machine in KVM or OpenStack communicates with the outside
    The container managed by Docker communicates with the outside

  • nat table the chain corresponding to the rule action

    SNAT source address translation shall be applied to export POSTROUTING
    MASQUERADE source address translation is applied to export POSTROUTING
    DNAT destination address translation shall be applied to import provisioning
    REDIRECT port redirection is applied to import provisioning

  • Enable routing forwarding function

[root@localhost ~]# sysctl -a | grep ip_forward
net.ipv4.ip_forward = 1
[root@localhost ~]# cat /proc/sys/net/ipv4/ip_forward
1
#The above is on

#The following is closed
[root@localhost ~]# echo 0 > /proc/sys/net/ipv4/ip_forwar

d

[root@localhost ~]# cat /proc/sys/net/ipv4/ip_forward
0
  • SNAT,MASQUERAED source address translation case
Case 1: realize the Internet access function of intranet host

Network connection topology
{width="6.929994531933509in" height="4.574838145231846in"}

  • Implementation topology
    {width="6.929994531933509in" height="3.0533661417322833in"}
  • Configuration command
    • client host configuration
[root@localhost ~]# cat /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens33
UUID=486d5c6d-17ed-4a3f-baab-92d56d042796
DEVICE=ens33
ONBOOT=yes
IPADDR= 192 .168.1.2
PREFIX= 24
GATEWAY= 192 .168.1.1 #The gateway is the firewall host ens33 interface ip
  • firewall host configuration
[root@localhost ~]# cat /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens33
UUID=4ac0aefc-628f-4461-ab59-636aae59965f
DEVICE=ens33
ONBOOT=yes
IPADDR= 192 .168.1.1
PREFIX= 24
[root@localhost ~]# cat /etc/sysconfig/network-scripts/ifcfg-ens37
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=no

IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens37
DEVICE=ens37
ONBOOT=yes
IPADDR= 192 .168.3.1
PREFIX= 24

#Enable routing forwarding function
[root@localhost ~]# cat /etc/sysctl.conf
# sysctl settings are defined through files in
# /usr/lib/sysctl.d/, /run/sysctl.d/, and /etc/sysctl.d/.
#
# Vendors settings live in /usr/lib/sysctl.d/.
# To override a whole file, create a new file with the same in
# /etc/sysctl.d/ and put new settings there. To override
# only specific settings, add a file with a lexically later
# name in /etc/sysctl.d/ and put new settings there.
#
# For more information, see sysctl.conf(5) and sysctl.d(5).
net.ipv4.ip_forward = 1

[root@localhost ~]# sysctl -p
net.ipv4.ip_forward = 1

[root@localhost ~]# iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o ens37 -j
SNAT --to-source 192.168.3.1
 or
[root@localhost ~]# iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o ens37 -j
MASQUERADE

[root@localhost ~]# cat /etc/sysconfig/iptables
# sample configuration for iptables service
# you can edit this manually or use system-config-firewall
# please do not ask us to add additional ports/services to this default
configuration
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]

-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
#-A FORWARD -j REJECT --reject-with icmp-host-prohibited
# To comment
COMMIT

[root@localhost ~]# iptables-restore < /etc/sysconfig/iptables
[root@localhost ~]# iptables -t filter -nL
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT all  --  0 .0.0.0/0 0 .0.0.0/0 state
RELATED,ESTABLISHED
ACCEPT icmp --  0 .0.0.0/0 0 .0.0.0/0
ACCEPT all  --  0 .0.0.0/0 0 .0.0.0/0
ACCEPT tcp  --  0 .0.0.0/0 0 .0.0.0/0 state NEW tcp dpt:22
REJECT all  --  0 .0.0.0/0 0 .0.0.0/0 reject-with icmp-
host-prohibited
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
[root@localhost ~]# iptables -t nat -nL
Chain PREROUTING (policy ACCEPT)
target prot opt source destination
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
Chain POSTROUTING (policy ACCEPT)
target prot opt source destination
RETURN all  --  192 .168.122.0/24 224 .0.0.0/24
RETURN all  --  192 .168.122.0/24 255 .255.255.255
MASQUERADE tcp  --  192 .168.122.0/24 !192.168.122.0/24 masq ports: 1024 -
65535
MASQUERADE udp  --  192 .168.122.0/24 !192.168.122.0/24 masq ports: 1024 -
65535
MASQUERADE all  --  192 .168.122.0/24 !192.168.122.0/24
MASQUERADE all  --  192 .168.1.0/24 0 .0.0.0/0  #Effect after configuration
  • web server configuration

    Before configuring other IP addresses, please install the httpd service to verify the results

[root@localhost ~]# cat /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens33
UUID=bb300759-8c34-4e8a-b708-089b105425c3
DEVICE=ens33
ONBOOT=yes
IPADDR= 192 .168.3.2
PREFIX= 24
GATEWAY= 192 .168.3.1 #The gateway is the IP address of the firewall host ens37 interface
client host result validation
[root@localhost ~]# curl [http://192.168.3.2](http://192.168.3.2)

Install wireshark packet capture verification on firewall host or web server
[root@localhost ~]# yum -y install wireshark*

(media/image506.png){width="6.929994531933509in" height="3.428523622047244in"}

Case 2: achieve KVM virtual machine access to external host

Route: kvm_instance(192.168.122.0/24) - > 192.168.122.1 virbr0 (KVM virtual machine gateway) ens33 192.168.2.10) - > 192.168.2.20 (external host)

#Method 1
[root@localhost ~]# iptables -t nat -F

[root@localhost ~]# iptables -t nat -A POSTROUTING -s 192.168.122.0/24 -j SNAT --to
192.168.2.10

[root@localhost ~]# iptables -t nat -A POSTROUTING -s 192.168.122.0/24! -d
192.168.122.0/24 -j SNAT --to 192.168.2.10

#Method 2
[root@localhost ~]# iptables -t nat -F
[root@localhost ~]# iptables -t nat -A POSTROUTING -s 192.168.122.0/24 -j MASQUERADE
[root@localhost ~]# iptables -t nat -A POSTROUTING -s 192.168.122.0/24! -d
192.168.122.0/24 -j MASQUERADE

  • DNAT target address translation (port mapping) case

Case 1: realize the publishing server in the LAN

  • Network connection topology
    {width="6.929994531933509in" height="4.564417104111986in"}
  • Experimental topology
    {width="6.929995625546806in" height="3.855786307961505in"}
  • Configuration command
    • web server configuration
[root@localhost ~]# cat /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens33
UUID=486d5c6d-17ed-4a3f-baab-92d56d042796
DEVICE=ens33
ONBOOT=yes
IPADDR= 192 .168.1.2
PREFIX= 24
GATEWAY= 192 .168.1.1

[root@localhost ~]# yum -y install httpd wireshark*
[root@localhost ~]# cat /var/www/html/index.html
dnat test
[root@localhost ~]# systemctl start httpd

  • firewall host configuration
[root@localhost ~]# cat /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens33
UUID=4ac0aefc-628f-4461-ab59-636aae59965f
DEVICE=ens33
ONBOOT=yes
IPADDR= 192 .168.1.1
PREFIX= 24

[root@localhost ~]# cat /etc/sysconfig/network-scripts/ifcfg-ens37
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens37
DEVICE=ens37
ONBOOT=yes
IPADDR= 192 .168.3.1
PREFIX= 24
[root@localhost ~]# cat /etc/sysctl.conf
net.ipv4.ip_forward = 1
[root@localhost ~]# iptables -t nat -A PREROUTING -d 192.168.3.1 -p tcp --dport 80
-j DNAT --to-destination 192.168.1.2
[root@localhost ~]# iptables -t nat -nL
Chain PREROUTING (policy ACCEPT)
target prot opt source destination
DNAT tcp  --  0 .0.0.0/0 192 .168.3.1 tcp dpt:80
to:192.168.1.2
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
Chain POSTROUTING (policy ACCEPT)
target prot opt source destination
RETURN all  --  192 .168.122.0/24 224 .0.0.0/24
RETURN all  --  192 .168.122.0/24 255 .255.255.255
MASQUERADE tcp  --  192 .168.122.0/24 !192.168.122.0/24 masq ports: 1024 -
65535
MASQUERADE udp  --  192 .168.122.0/24 !192.168.122.0/24 masq ports: 1024 -
65535
MASQUERADE all  --  192 .168.122.0/24 !192.168.122.0/24
MASQUERADE all  --  192 .168.1.0/24 0 .0.0.0/0
  • client host configuration
[root@localhost ~]# cat /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens33
UUID=bb300759-8c34-4e8a-b708-089b105425c3
DEVICE=ens33
ONBOOT=yes
IPADDR= 192 .168.3.2
PREFIX= 24
GATEWAY= 192 .168.3.1

  • client host result validation
[root@localhost ~]# curl http://192.168.3.1
dnat test

{width="6.929994531933509in" height="3.6161023622047246in"}
{width="6.929994531933509in" height="2.5948392388451444in"}

Case 2: before enabling external hosts to access KVM virtual machines (intranet hosts) routing

Suggestion: intranet hosts can access external hosts (e.g. based on SNAT mode)

Route: kvm_instance (192.168.122.0 / 24) < - 192.168.122.1 virbr0 ens33 192.168.2.10 < - 192.168.2.20 external host

[root@localhost ~]# iptables -F
[root@localhost ~]# iptables -t nat -A PREROUTING -d 192.168.2.10 -p tcp --dport 80 -j
DNAT --to 192.168.122.43:80
[root@localhost ~]# iptables -t nat -A PREROUTING -d 192.168.2.10 -p tcp --dport 2222 -
j DNAT --to 192.168.122.43:22
[root@localhost ~]# iptables -t nat -A PREROUTING -d 192.168.2.10 -p tcp --dport 8080 -
j DNAT --to 192.168.122.43:8080
Thinking: if there are two intranet servers that need to provide 80/tcp services, how to map them?
[root@localhost ~]# iptables -t nat -A PREROUTING -d 192.168.2.10 -p tcp --dport 80 -j
DNAT --to 192.168.122.43:80
[root@localhost ~]# iptables -t nat -A PREROUTING -d 192.168.2.11 -p tcp --dport 80 -j
DNAT --to 192.168.122.53:80

firewalld

What is firewall?

Firewall is a dynamic firewall. It is a user space management tool for netfilter kernel module in CentOS7 system.

Firewall only replaces the iptables service part, and its bottom layer still uses iptables as the firewall rule management entry.
{width="6.929994531933509in" height="5.377258311461067in"}

Summary:
  • Dynamic firewall
  • Tools for managing netfilter user space
  • iptables command called

The concept and function of zone in firewall

A zone is a set of firewall policies prepared by firewalld in advance, that is, a policy template, which can be switched according to different application scenarios.

For example, you have a laptop that you use every day in the company's office, coffee shop and home. Let's rank the security of the place from high to low: home, company's office and coffee shop.
We want to specify the following firewall policy rules for this laptop: allow access to all services at home; only allow access to file sharing services in the company office; and only allow Internet browsing in the coffee shop. In the past, we needed to set firewall policy rules manually frequently, but now we only need to preset the area collection, which can be switched automatically at any time Thus, the application efficiency of firewall policy is greatly improved.

zone classification in firewall

The main difference between different regions of firewall is that each region treats packets differently by default

Firewall has 9 zone s by default:
  • block (reject)
  • dmz (demilitarization)
  • drop (discard)
  • external
  • home
  • internal
  • public firewall default area
  • trusted
  • work

Firewall files

Firewall files fall into two categories:

/usr/lib/firewalld/services:firewalld service has more than 70 services defined in this directory by default and can be used directly.

/usr/lib/firewalld/zones: zone configuration file

/etc/firewalld/zones: the default zone configuration file, which specifies the written rules

firewalld file function: humanized management rules; grouping through service organization ports is more efficient. If a service uses several network ports, the service configuration file is equivalent to providing batch operation shortcuts for rule management to these ports.

Firewall syntax

Command syntax:

If the – zone option is not specified, it is the current default zone, and the – permanent option is whether to write changes to the zone configuration file

Firewall status

1 firewall-cmd [--zone=zone] action [--permanent]
[root@localhost ~]# firewall-cmd --state
running
#View status
[root@localhost ~]# firewall-cmd --reload
success
#Reload the firewall, disconnect the user, clear the temporary configuration, and load the permanent configuration in the configuration file
[root@localhost ~]# firewall-cmd --complete-reload
success
#Reload the firewall without interrupting the user's connection (used in case of serious firewall failure)
[root@localhost ~]# firewall-cmd --panic-on
#Emergency mode, force all network connections to close

Action in firewall

View actions in action

[root@localhost ~]# firewall-cmd xxx
--get-icmptypes ##View all ICMP types supported
--get-zones ##View all areas
--get-default-zone ##View the current default area
--get-active-zones ##View areas currently in use
--get-services ##View the services supported in the current region
--list-services ##View the list of services open in the current region
--list-services --zone=home  ##View the list of services open in the specified domain
--list-all ##View all configurations in the default area, similar to iptables -L -n
--list-all-zones ##View all configurations for all areas

Change area operation

[root@localhost ~]# firewall-cmd xxx
--set-default-zone=work ##Change the default area

New rule

New -- add

[root@localhost ~]# firewall-cmd xxx
--add-interface=eth0 ##Add the network interface to the default zone
--add-port= 12222 /tcp --permanent ##Add ports to the zone open list
--add-port= 5000 -10000/tcp --permanent ##Add the port range to the open list;
--add-service=ftp --permanent ##Add the service to the regional open list (note that the name of the service needs to be consistent with the list of services supported in this region
 (consistent names in)
--add-source= 192 .168.1.1 ##Add traffic from the source address to the specified area
--add-masquerade ##Enable SNAT (source address translation)

Delete rule
Delete -- remove

[root@localhost ~]# firewall-cmd xxx
--remove-service=http ##In the home area, delete the http service from the open list
--remove-interface=eth0 ##Delete the network interface in the default area
--remove-source= 192 .168.1.1 ##Delete the traffic from the source address to the specified area
rules of change

change

[root@localhost ~]# firewall-cmd xxx
--change-interface=eth1 ##Change the specified interface to other areas

Query rules

Query query

[root@localhost ~]# firewall-cmd xxx
--query-masquerade ##Query the status of SNAT
--query-interface=eth0 ##Determine whether the network card interface exists in this area
Port forwarding

Port forwarding can forward traffic to the specified port of the specified address when the specified address accesses the specified port. If the forwarding purpose does not specify ip, it defaults to the local machine. If the ip is specified but no port is specified, the source port is used by default.

Note: the following parts may need 2 hosts to complete. Suggestion: it is best to draw the picture first.
#SNAT via firewalld
[root@localhost ~]# firewall-cmd --add-masquerade --permanent
[root@localhost ~]# firewall-cmd --reload
 # Forward traffic from port 80 to 8080

#firewall-cmd --add-forward-port=port=80:proto=tcp:toport=8080
 # Forward traffic from port 80 to


firewall-cmd --add-forward-port=port= 80 :proto=tcp:toaddr= 192 .168.2.20

#delete
[root@localhost ~]# firewall-cmd --remove-forward-
port=port=80:proto=tcp:toaddr=192.168.2.20 --permanent
# Forward the traffic of port 80 to port 8080 of 192.168.2.20


firewall-cmd --add-forward-port=port= 80 :proto=tcp:toaddr= 192 .168.2.20:toport= 8080


If port forwarding cannot be used after configuration, you can check the following two problems:

  • For example, when forwarding port 80 to port 8080, first check whether the local port 80 and the target port 8080 are open for listening
  • Secondly, check whether the camouflage IP is allowed. If not, turn on the camouflage IP
Rich rule

When the basic firewalld syntax rules cannot meet the configuration requirements, rich rules can be used to complete more complex functions.

Rich rule help
 [root@localhost ~]# man 5 firewalld.richlanguage
Rich rule options
--add-rich-rule='rule'  ##New rich rule
--remove-rich-rule='rule' ##Delete rich rule
--query-rich-rule='rule'  ##View a single rich rule
--list-rich-rules ##View rich rule list
Rich rule case
  • Deny access to a host
[root@localhost ~]# firewall-cmd --permanent --zone=public --add-rich-rule='rule
family=ipv4 source address=192.168.2.20/32 reject'
[root@localhost ~]# firewall-cmd --reload
Discard all icmp packets
[root@localhost ~]# firewall-cmd --permanent --add-rich-rule='rule protocol value=icmp
drop'
success
[root@localhost ~]# firewall-cmd --reload
success
#delete
[root@localhost ~]# firewall-cmd --permanent --remove-rich-rule='rule protocol
value=icmp drop'
  • Allow a network segment to pass through a port
[root@localhost ~]# firewall-cmd --permanent --zone=public --add-rich-rule='rule
family=ipv4 source address=192.168.2.0/24 port port=7900-7905 protocol=tcp accept'
success
  • Turn on SNAT
[root@localhost ~]# firewall-cmd --permanent --add-rich-rule='rule family=ipv4 source
address=192.168.1.0/24 masquerade'
  • Port forwarding
[root@localhost ~]# firewall-cmd --add-masquerade --permanent
[root@localhost ~]# firewall-cmd --permanent --add-rich-rule='rule family=ipv4 source
address=192.168.2.10/24 forward-port port=80 protocol=tcp to-port=8090 to-
addr=192.168.2.20'
[root@localhost ~]# firewall-cmd --reload

Posted by offsprg01 on Sat, 09 Oct 2021 05:11:45 -0700