Firewall:
Firewalls in the IT domain: a complete set of security isolation tools;
Software firewall:
Application software processing logic to run the common hardware implementation of the firewall;
The most common firewall in Linux is: NetFilter network filter, is a kernel component;
Iptables/netfilter Packet filtering Firewall
Hardware firewall:
The firewall function can be implemented at the hardware level, while the other part is still based on the software implementation;
Cisco:pix (Low-level), ASA (Advanced point): ISO (internetworking openrating System)
Deeply convinced of their firewalls: NGAF
The so-called firewall: refers to the work on the edge of the host or network, for the data message through the firewall based on pre-defined matching rules (recognition conditions) for detection, for the message can be matched by the rule to take some pre-defined processing mechanism to be processed, A set of components that have a default access control processing mechanism for messages that are not matched by a rule;
Host firewall: Its security service scope is limited to the current one host;
Network firewall: Its security service scope is the current LAN;
The implementation of firewalls in Linux systems:
Iptables/netfilter
That can implement the host firewall, but also can implement the network firewall;
netfilter:位于Linux系统内核中的防火墙的框架,Framework,防火墙功能实现的主体;iptabless:专门为netfilter编写数据报文的匹配规则的用户空间中的应用程序工具;
The logical structure of the NetFilter:
There are 5 large hook structures inside:
hook function
Hook_input ()
Hook_output ()
Hook_forward ()
Hook_prerouting ()
Hook_postrouting ()
chain: 5条规则链 INPUT OUTOUT FORWARD PREROUTING POSTROUTINGtable: filter:过滤器,包过滤防火墙功能; 包含:INPUT、OUTPUT、FORWARD三条链; nat:用于修改报文的源地址和/或目的地址,而且还可以修改端口号; 地址转换 地址伪装 包含:PREROUTING、POSTROUTING、OUTPUT、INPUT(1.4版本中新增加) mangle:拆解报文并对报文格式进行修改,然后再重新封装报文; 流量控制 数据标签 包含:FORWARD、REROUTING、POSTROUTING、OUTPUT、INPUT五条链; raw:关闭nat表上启动的连接追踪机制; 包含:PREROUTING、OUTPUT两条链;
The order of precedence (high to low) for the rules on the same rule chain in each table:
Raw---mangle------Filter
The flow of data messages:
Inbound data--the destination IP address is a valid IP address of the firewall host data message:
Prerouting--(Routing table)---INPUT
Outbound data--The source IP address is a valid IP address of the firewall host data packet;
Prerouting--(Routing table)--OUTPUT--postrouuting
Forward data--source, destination IP address is not a valid IP address of the firewall host, and requires a data message forwarded by the firewall:
Prerouting--(Routing table)--FORWARD and postrouting
Iptables/netfilter:
Iptables: Rule authoring Tool, non-interactive command-line tool, can only write one rule at a time and send to NetFilter to execute;
The rule matching order of NetFilter is: Prime Minister match
First match: Each rule is matched from top to bottom, and the other matching rules are no longer retrieved as long as there are rules that match the data packet;
CentOS 6-: Write rules using the iptables command;
CentOS 7: Write rules using the Firewall-cmd command; iptables commands are still available;
It is recommended to use the Iptables tool:
Stop the FIREWALLD service and cancel its autorun:
Systemctl Disable Firewalld.service
# systemctl stop firewalld.service
iptables command:
Rule Authoring Tools:
Rules:
Also known as matching rules or recognition conditions, according to the requirements defined to match the incoming, outgoing or through the local message matching conditions, and after the match to specify the specific processing mechanism;
In simple terms, the rule = match condition + processing action
匹配条件: 基本匹配条件: 简单的IP、TCP、UDP等协议的报文首部中特定属性的匹配条件; 扩展匹配条件: 需要借助于扩展的功能模块来进行匹配的机制; 隐式扩展: 不明确的指出使用哪个具体的模块,但实际上确实在使用扩展模块来完成条件匹配; 显示扩展: 必须要明确指出此次使用那个模块来完成条件匹配; 处理动作: 基本动作: 即包过滤的动作: ACCEPT,DROP,REJECT 扩展动作: 需要借助于扩展模块才能执行的处理动作;
To add the right rules, we need to consider the following questions in advance:
1. The flow path of the data message to determine the correct link to add the rule to the correct target;
2. Determine the functions implemented by this rule to select the correct table to fill in;
3. Determine the content of the specific matching criteria for use in the data of interest;
4. Determine the default matching condition and execution action of the chain;
iptables command:
Iptables/ip6tables-administration tool for Ipv4/ipv6 packet fil‐tering and NAT
Format:
iptables [-t table] {-a|-c|-d} chain rule-specification
ip6tables [-t table] {-a|-c|-d} chain rule-specification
iptables [-t table]-I chain [rulenum] Rule-specification
iptables [-T table]-R chain Rulenum rule-specification
iptables [-t table]-D chain Rulenum
iptables [-t table]-s [chain [Rulenum]]
iptables [-t table] {-f|-l|-z} [chain [Rulenum]] [options ...]
iptables [-t table]-n Chain
iptables [-T table]-X [chain]
iptables [-t table]-p chain Target
iptables [-t table]-e old-chain-name new-chain-name
Rule-specification = [matches ...] [Target]
Match =-M matchname [per-match-options]
target =-j targetname [per-target-options]
Common formats written by the iptables rule:
iptables [-t table] COMMAND CHAIN [-M matchname] [per-match-options]-j targetname [per-target-options]
Description
-T table: Specifies the ability to choose which table to execute, including: Raw,mangle,nat and filter, if omitted, the default table--filter table is used;
-M MatchName: it is usually necessary to write when the matching condition of the display extension is configured, if omitted, to configure a basic match or an implicit extended match condition;
-j targetname: Specifies the processing action of packets with all matching criteria
COMMAND:
Operation of the chain:
-p,--policy chain Target
The default policy for specifying a chain: There are usually two action choices, namely: Accept and drop;
-N,--new-chain chain
Create a new custom rule chain; The new chain must be called by the rules on the built-in chain to take effect;
-X,--delete-chain [chain]
Delete the custom chain that was called 0 by the built-in chain;
-E,--rename-chain old-chain new-chain
Renaming a custom chain with a number of 0 built-in chain calls;
-F,--flush [chain]
Clears the rule on the specified chain (or all chains in the table);
Action command for
rule:-A,--append chain rule-specification appends a rule at the end of the specified chain;-D,--delete chain rule-specification-d,--del ETE chain Rulenum Deletes a rule from the specified chain, either specifying a specific rule or specifying the number of rules on the chain;-I,--insert chain [Rulenum] rule-specification inserts a rule on the specified chain, by default Insert a new rule into the first rule on the chain, or you can specify the rule designator to make the inserted rule the Rulenum rule on the specified chain;-R,--replace chain Rulenum rule-specification Replace the rulenum rule on the instruction chain with the rule in the command line; instead of modifying a specific condition in the rule, the entire rule is completely replaced;-L, the--list [chain] list displays all rules on the specified chain (not all) on the designated table; Other common options are available:-V ,--verbose: Information in more detailed formats, and-VV;-N,--numeric: Digitally display all the information in the rule, including information such as hostname and port number,-X,--exact: Accurate display of the results of the counter, and each rule has two Counter: 1. The number of messages matched by the rules; 2. The total number of bytes of the message matched by the rule;--line-numbers: Displays the number of individual rules on the specified chain other commands:-Z,--zero [chain [Rulenum]] will specify the chain The rule counter is set to 0;
Common targets:
LOG: The flow of matched data packets is logged, and does not affect the transmission of the data packet itself;
Mark: The setting of the firewall tag for matching data packets;
Masquerade: Source Address spoofing, a special source IP address translation;
REDIRECT: Destination IP address and port redirection;
REJECT: Organize data message transmission and return message to the source of data message;
SNAT: source IP address translation;
DNAT: Destination IP address translation;
ACCEPT: To release the matching data packets;
DROP: Organization of matched data packets;
RETURN: Jumps between the regular chains;
Matching Criteria:
By default, there is a logical "and" relationship between the different conditions in the same command;
!: For matching results, there are "except ... The meaning of "outside";
Basic matching Criteria:
[!] -S,--source address[/mask][,...]
Check the matching range of the source IP address in the data packet, can be a single IP address, or it can be a subnet, a master network, such as IP address settings: 0.0.0.0/0 represents the entire IP address stack all the IP address, if the condition is omitted, it means that all the source IP address will be matched;
[!] -D,--destination address[/mask][,...]
Check the matching range of the destination IP address in the data packet, either a single IP address or a subnet, a master network, a network, and other IP address settings: 0.0.0.0/0 represents all IP addresses in the entire IP address stack, and if omitted, means that all source IP addresses will be matched;
[!] -I.,--in-interface name
Check that the interface of the data packet into the stack can match this condition;
[!] -O,--out-interface name
Check if the interface of the data message stack is able to match this condition;
Extended Match condition: implicitly extended match condition: [!]-P, [-M matchname]--protocol protocol Check packet header of a specified protocol whether there is a qualifying attribute or field; Protocols specified include: TCP, UDP, Udplite, Icmp,icmpv6,esp, Ah, SCTP, MH, All TCP Protocol (TCP module): [!]--source-port,--Spor T port[:p ORT] [!]--destination-port,--dport port[:p ort] to specify the matching criteria for the source or destination port, you can specify only one port or a contiguous set of ports at a time, and you cannot specify a discrete port; [!] --tcp-flags Mask Comp Specifies the matching criteria for each flag bit in the TCP protocol header; Common flag bits: Urg,syn,rst,psh,ack,fin,all,none mask: Sets the flag to be detected A list of bits, separated by the use of "," between the flags, comp: Must be placed "1" in the list of flags, the remaining in the mask table of the flag bit must be set "0"; [!]--syn equivalent:--tcp-flags syn,rst,ack , Fin,syn UDP protocol (UDP module): [!]--source-port,--Sport port[:p ORT] [!]--destination-port,--dport port[:p ort] Used to specify the matching criteria for the source or destination port, only one port or a contiguous set of ports can be specified at a time, but not a discrete port; ICMP protocol (ICMP module): [!]--icmp-type [Type[/code]|typename] The common Icmp-type:echo-request, code is 8; echo-replay, code is 0;
Considerations when defining a rule:
1. The order in which rules are matched is matched from top to bottom,
1) with the same class of rules, the minimum matching range should be written on top;
2) non-homogeneous rules, the higher the matching frequency should be written on;
3) It is recommended to try not to modify the chain's default policy to block all data, and if you want to set a rule that blocks all data, set the rules for organizing all data in the last bar of the chain;
Host firewall basic Matching Criteria configuration example: 1. Allow the specified host to access the local SSH service: ~]# iptables-t filter-a input-s 172.16.0.1-p tcp--dport 22-j ACCEPT 2. Default block all other hosts to the native all data communication: Method One: ~]# iptables-p INPUT DROP (not recommended, if using the Iptables-f command the consequences are terrible) method two: ~]# iptables-a I Nput-j REJECT (recommended) 3. Configure all hosts in the 172.16.0.0/16 network segment to access the local httpd service: ~]# iptables-i input-s 172.16.0.0/16-p TCP--d Port 80-j ACCEPT 4. Allow native ping to external host, but do not allow external host ping through native: ~]# iptables-i INPUT 2-d 172.16.72.2-p ICMP--icmp-type EC Ho-reply-j ACCEPT 5. To avoid the implant run of the XXX program, you can set the firewall rules on the OUTPUT chain: ~]# iptables-a output-d 172.16.0.1-p TCP--sport 22- J ACCEPT ~]# iptables-a output-j REJECT ~]# iptables-i output-d 172.16.0.0/16-p tcp--sport 80-j accep T ~]# iptables-i OUTPUT 2-p ICMP--icmp-type echo-request-j Accept network firewall basic matching Criteria Configuration example: ~]# iptables-a FORWARD- J REJECT ~]# iptables-i forward-s 192.168.100.100-d 172.16.69.2-p tcp--dport 3306-j ACCEPT ~]# iptables-i for WARD 2-s 172.16.69.2-d 192.168.100.100-p TCP--sport 3306-j accept ~]# iptables-i FORWARD 3-p icmp-j Accept Note: All networks set through the FORWARD chain The matching rules of the firewall must appear in pairs, that is, the round-trip process of data must be released at the same time, in order to ensure the normal operation of the routing function; explicit extended match condition: 1.multiport extension: One-time write to multiple discrete ports or multiple sets of contiguous ports, maximum of 15 sets of ports, each port range occupies two ports; protocols that can be supported: TCP, UDP, Udplite, DCCP, SCTP. Related options: [!]--source-ports,--Sports Port[,port|,port:port] ... [!] --destination-ports,--dports Port[,port|,port:port] ... [!] --ports Port[,port|,port:port] ...--dports 22,80,3306-j ACCEPT Example: ~]# iptables-i forward-s 192.168.100.100-d 172.16.69.2-p tcp-m multiport--dports 22,8 0,3306-j ACCEPT ~]# iptables-i forward-d 192.168.100.100-s 172.16.69.2-p tcp-m multip ORT--sports 22,80,3306-j ACCEPT 2.iprange extension: As a matching condition with any number of consecutive IP address accesses; related options: [ !] --src-range from[-to] [!]--dst-range From[-to]-m iprange--src-ran GE 192.168.100.1-192.168.100.100 Example: ~]# iptables-i forward-m IPRange--src-range 192.168.100.1-192.168.100.100-d 172.16.69.2-p tcp-m multiport--dports 22,80,3306-j ACCEPT ~]# iptables-i forward-m iprange--dst-range 192.168.100.1-192.168.100.100-s 172.16.69.2-p TCP -M multiport--sports 22,80,3306-j ACCEPT 3.string Extension: String matching detection of the application layer data in the data packet; Related options:--algo {BM|KMP}--string "STR ING "Example: ~]# iptables-i forward-s 172.16.69.2-m string--algo BM--string "Dafa"-J REJECT 4.time extension: Match detection based on the time of the packet arriving at the firewall and the specified time range; related options :--datestart Yyyy[-mm[-dd[thh[:mm[:ss]]--datestop yyyy[ -MM[-DD[THH[:MM[:SS]] [] defines the only absolute time range;--timestart hh:m M[:SS]--timestop Hh:mm[:ss] Defines a periodic time range; [!] --monthdays Day[,day ...] Define each day of the month; 1-31 [!]--weekdays Day[,day ...] Define the day of the week; Value: Mon, Tue, Wed, Thu, Fri, Sat, Sun, or values from 1 to 7, or Mo, Tu, et C. Example: ~]# iptables-i forward-m time--timestart 08:00:00--ti Mestop 17:59:59! --weekdays 6,7-o eno16777736-j REJECT 5.state Extended Connection Status detection, based on connection tracing mechanism; Conntrack related options: [!] --state state iptables definition of connection Status: INVALID, established, NEW, related or UN Tracked; INVALID: Unrecognized connection state, invalid communication state, Syn,fin established: The state of the connection has been established; The state of being connected; a new connection state; A related: A connection condition associated with another established connection; an associative or derivative state; Untracked: An untraceable state; the location in the kernel where the connection tracking state data is saved:/proc/net/nf_conntrack The maximum number of connections that can be traced:/proc/sys/net/nf_conntrack_max Note: The maximum number of connections recorded here, it is recommended to adjust the size to be large enough if necessary; In order to be able to use memory resources as efficiently as possible, the state of the cached connection tracking cannot be saved indefinitely, so the corresponding timeout time is set;/proc/sys/net/netfilter/nf_conntra Ck*timeout* using connection tracking to set the FTP server's access control: ~]# iptables-a input-m State--state EstabliShed,related-j ACCEPT ~]# iptables-a input-d 172.16.69.2-p tcp-m multiport--dports 21,22,80,3 306-m State--state new-j ACCEPT ~]# iptables-a input-j DROP Note: Load Nf_c required Onntrack_ftp kernel module, ~]# modprobe nv_conntrack_ftp setup nf_conntrack_ftp module Auto-mount: Set/etc/sysconfig/iptables-config iptables_modules= "NF _conntrack_ftp "Use connection tracking to set general rules on the OUTPUT chain: ~]# iptables-a output-m State--state Established-j ACCEPT ~]# iptables-a output-j DROP 6.mac Extension Implement MAC address matching detection; for prerouting, FORWARD or input chain; related options [!]--mac-source Address matches the source MAC address, which must be in the form: XX:XX:XX:XX:XX:XX 7.connlimit extension: Make concurrent connections based on each client IP addressThe matching detection of the number; related options:--connlimit-upto n When the client is current and When the number of connections is less than or equal to N, this condition can be matched; This condition is usually used in conjunction with the Accept action;--connlimit-above N when the client This condition can be matched when the current number of concurrent connections is greater than N; This condition is usually used in conjunction with the drop or reject action; 8.limit expansion: Match detection based on the rate of data packets sent and received by the server; Related options:--limit Rate[/second|/minute|/hour|/day] The rate at which the server is able to receive the maximum unit time, and the--limit-burst number of the data packets that can be received at the initial Large quantity; Example: ~]# iptables-i INPUT 1-p ICMP--icmp-type 8-m limit--limit 15/minute--limit-burst 8-j Accept custom rule chain: Create a custom rule chain: ~]# iptables-n udp_match Add a rule to a custom rule chain: ~]# IPTABL Es-a udp_match-d 172.16.72.2,192.168.100.1-p udp-m multiport--dports 53,67,69,137,138-j ACCEPT ~]# iptables- A udp_match-j RETURN The last rule of the custom rule chain can be returned to the main chain for subsequent rule matching; change the name of the custom rule chain: Premise: The reference count for the custom rule chain to be renamed must be 0; ~]# iptables-e udp_match UDP Delete Custom rule chain: Prerequisite: The reference count of the custom rule chain to be renamed must be 0 and no rule on the chain; ~]# iptables-x UDP references a custom rule chain on the main chain: ~]# iptables When does the-I input-p udp-j UDP work? There are a number of similar rules, but not the rules for matching most data, you can set such rules in a custom chain, which can reduce the time of rule matching and improve the matching efficiency;
Nat Table:
Function:
1.nat,network address translation, network addresses translation,
1) snat:source-address NAT
Typically used to allow a host with a private IPV4 address in the LAN to access the external network or the Internet; The
generally completes the network address translation of the source address after routing is selected, so for iptables, such rules should be configured on the postrouting chain;
A. Static address translation: Single-to-one address translation; b. Address spoofing: Multiple-to-an address translation; 2) dnat:destination-address NAT is typically used to make an external network or internet The host in the LAN can access the network service on the server using the private IPV4 address in the local area network, usually need to complete the network address translation of the destination address before routing the choice, therefore, in iptables, such rules should be configured on the prerouting chain; 2.NAPT:NETW Ork addresses and port translation, network address port translation, network address translation + port mapping snat:this target is only valid in the NAT table, in the Postrouting and INPUT chains, and user-defined chains which is only called from those chains. --to-source [ipaddr[-ipaddr]][:p Ort[-port]] Note: In Rhel or CentOS distribution Linux, the ipaddr specified by Snat must be an IP address configured and in effect on the current host; Example: ~]# iptables-t nat-a postrouting-s 192.168.100.0/24-j SNAT--to-source 172.16.72.72 ~]# iptables -T nat-a postrouting-s 192.168.100.0/24-j Masquerade//Source Address camouflage technology, no need to specify a specific internal global address, automatically determine the local available IP address as the internal global address, to source Dnat:this Target is a valid in the NAT table, in the prerouting and OUTPUT chains, and user-defined chains WH Ich is called from those chains. --to-destination [ipaddr[-ipaddr]][:p Ort[-port]] Example: ~]# iptables-t nat-a prerouting-d 192.168.100.1-p TCP--DP ORT 80-j DNAT--to-destination 172.16.69.2:8000 functions the same as: 1. Firewall rules that set NAT translation on the router: ~]# iptables-t NAT -R prerouting 1-d 192.168.100.1-j DNAT--to-destination 172.16.69.2 2. Do port redirection on the destination server: You need to use the redirect target ~]# iptables-t nat-a prerouting-p tcp--dport 80-j REDIRECT--to-ports 8000 REDIRECT This Target is a valid in the NAT table, in the prerouting and OUTPUT chains, and user-defined chains which Ed from those chains. --to-ports port[-port]log target Turn on kernel logging of matching packets. It is only the function of opening the kernel to log the matching data packets, and not doing any other operations on the data, and if the data packets are matched by the rules of the target log, the following rules will be matched in the normal matching order;--log-level level Level of logging, which can be (system-specific) numeric or a mnemonic. Possible values is (in decreasing order of priority): Emerg, Alert, Crit, error, warning, notice, info or Debug. --log-prefix prefix prefix log messages with the specified prefix; Up to letters long, and useful for distinguishing messages in the logs. Example: ~]# iptables-t filter-a forward-p tcp--dport 80-j LOG--log-level info--log-prefix "iptab-log-" Note: By default, the log is recorded in the default log file defined by the Rsyslog service, saving and overloading the/var/log/messages;iptables rule: CentOS 7: Recommendation: To be compatible with CentOS 6 and previous versions, consider IP The rule definitions of tables are saved in the/etc/sysconfig/iptables file; The rules are saved: ~]# (umask 077; iptables-save >/etc/sysconfig/iptab Les) Rule recovery: ~]# Iptables-restore </etc/sysconfig/iptables CentOS 6-: Rule Save: ~]# I Ptables-save >/etc/sysconfig/iptables ~]# service iptables Save rule recovery: ~]# Iptables-restor E </etc/sysconfig/iptables ~]# service iptables restart
Iptables/netfilter Supplemental Material 1:
Use Iptables's recent module to defend against dosxxx: 22, create a list that holds all client IPs that have access to the specified service
SSH: Remote connection iptables-i input-p TCP--dport 22-m connlimit--connlimit-above 3-j DROP iptables-i input-p TCP --dport 22-m State--state new-m recent--set--name SSH iptables-i input-p TCP--dport 22-m State--state NEW- M recent--update--seconds--hitcount 3--name ssh-j LOG--log-prefix "SSH Attach:" Iptables-i input-p TCP-- Dport 22-m State--state new-m recent--update--seconds 3--hitcount--name DROP 1. Using the Ssh-j module to set the concurrency of a single IP is 3; users who use NAT to surf the internet can increase the value according to the actual situation; 2. Use the recent and state modules to restrict a single IP to only 2 new connections to the native computer within 300s. Access can be resumed after five minutes of restriction. Here is a description of the last two sentences: 1. The second sentence is a new connection that records access to the TCP 22 port, the record name is the source IP of the SSH--set record packet, and if the IP already exists, an entry that already exists will be updated 2. The third sentence refers to the ip,300s within the SSH record to initiate more than 3 connections The connection to this IP is denied. --update is a list of updates that are updated each time a connection is established;--seconds must use both--hitcount and--rcheck or--update to use the same 3.iptables record with--rcheck or--update:/pro C/net/xt_recent/ssh can also use the following sentence to log: iptables-a input-p tcp--dport 22-m State--state new-m recent--update--na Me SSH--second--hitcount 3-j LOG --log-prefix "SSH Attack"
Iptables/netfilter Supplementary Material 2:
Install and set up layer7 third-party extensions to achieve application-level access control;
由于layer7扩展功能于2009年之后停止更新,所以仅能支持linux-2.6版的内核补丁;于是将于CentOS 6中安装并设置其功能;CentOS 6: http://ftp.redhat.com/redhat/linux/enterprise/6Server/en/os/SRPMS/ layer7:第三方扩展; iptables实现七层访问过滤: 模块:layer7 识别应用层协议 iptables/netfilter iptables -m state, netfilter state 对内核中的netfilter,打补丁layer7,重新编译内核 对iptables打补丁,补上layer7模块,重新iptables
Iptables/netfilter related content