CentOS Study Notes-firewall iptables, centosiptables

Source: Internet
Author: User
Tags ftp connection ssh port

CentOS Study Notes-firewall iptables, centosiptables
Linux Firewall: iptables

Iptables is a packet filtering software, and more than 2.6 of the Linux kernel is this software. This Section selects the Linux private dish of laruence-Chapter 9 server setup, firewall and NAT Server

Packet entry process: Importance of Rule Order!

Assume that your Linux host provides WWW Service, you must enable the pass packet rule for port 80. However, you find that the IP source always attempts to intrude into your system maliciously, therefore, if you want to reject requests from the IP address and discard all non-WWW packets, how do you set the firewall inspection sequence for these three rules?

This sort order can meet your needs. However, if your order is wrong, it becomes:

At this time, the "can use your WWW Service" Oh! As long as he sends WWW request packets to your host, you can use your WWW function, because the first rule defined in sequence will let him pass, rather than considering the second rule! So that we can understand the meaning of the Rule Order! Now let's think about it. If Rule 1 is changed to "discard all packets", Rule 2 sets "WWW service packet passing". Could you tell me, can my client use my WWW Service? Haha! The answer is "No ~』 Have you figured it out?

[Root @ www ~] # Iptables [-t tables] [-L] [-nv] Options and parameters:-t: Followed by a table, such as nat or filter. If this item is omitted, use the default filter-L: to list the current table rules-n: do not check the IP address and HOSTNAME, the display speed will be much faster! -V: lists more information, including the total number of packets using this rule, related network interfaces, and other examples: lists the rules for the three chains of filter table [root @ www ~] # Iptables-L-nChain INPUT (policy ACCEPT) <= for the INPUT chain, and the Default policy is acceptable target prot opt source destination <= ACCEPT all -- state RELATED, ESTABLISHED <= 1st rules ACCEPT icmp -- <= 2nd rules ACCEPT all -- <= 3rd rules ACCEPT tcp -- state NEW tcp dpt: 22 <== the following REJECT all -- reject-with icmp-host-prohibitedChain FORWARD (policy ACCEPT) <= for the FORWARD chain, and the preset policy is acceptable to target prot opt source destinationREJECT all -- reject-with icmp-host-prohibitedChain OUTPUT (policy ACCEPT) <= for the OUTPUT chain, and the Default policy is acceptable target prot opt source destination. Example: list the rules for three nat table chains [root @ www ~] # Iptables-t nat-L-nChain PREROUTING (policy ACCEPT) target prot opt source destinationChain POSTROUTING (policy ACCEPT) target prot opt source destinationChain OUTPUT (policy ACCEPT) target prot opt source destination

In the preceding table, each Chain is the one mentioned above ~ The policy in the brackets in the Chain line is the preset policy. What does the target and prot represent?

  • Target: indicates the action. ACCEPT is the allow action, and REJECT is the deny action. In addition, there are items that are dropped!
  • Prot: indicates the used packet protocol, which consists of tcp, udp, and icmp packet formats;
  • Opt: Additional Options
  • Source: Which "source IP address" is restricted by this rule?
  • Destination: Which "destination IP address" is restricted by this rule?

In the OUTPUT result, because the-t option is not added to the first example, the INPUT, OUTPUT, and FORWARD chain rules in the filter table are used by default. For a single machine, INPUT and FORWARD are important firewall chains, so you can find that the policy of the last rule is REJECT (REJECT! Although the INPUT and FORWARD policies allow (ACCEPT), all packets have been rejected in the last rule!

However, the observation of this command is only a formatted query. It is difficult to parse each rule in detail. For example, based on the output results, the five rules of INPUT are displayed as follows:

The most interesting thing is 3rd rules. How can we accept all the packets in the club? If all of them are accepted, the subsequent rules will not be useful at all! In fact, that rule only tests the network (lo) interface for each host! If no interface is listed, we can easily make a mistake ~ So we recommend using the iptables-save command to observe firewall rules recently! Because iptables-save lists the complete firewall rules, but there is no normalized output.

[Root @ www ~] # Iptables-save [-t table] Options and parameters:-t: Can be output only for certain tables, for example, for nat or filter purposes only [root @ www ~] # Iptables-save # Generated by iptables-save v1.4.7 on Fri Jul 22 15:51:52 2011 * filter <= The table starts with an asterisk. Here, the filter is used: input accept [0: 0] <= The chain starts with a colon. The three built-in chains: forward accept [0: 0] <= the policies for the three built-in chains are all ACCEPT! : Output accept [680: 100461]-a input-m state -- state RELATED, ESTABLISHED-j ACCEPT <= rules for INPUT-a input-p icmp-j ACCEPT-A INPUT-I lo-j ACCEPT <= This is very important! Open for internal interface of Local Machine! -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 <= for the FORWARD rule COMMIT # Completed on Fri Jul 22 15:51:52 2011
From the output above, among the rules with a bottom line and the content containing lo, "-I lo" refers to the packets from Lolo's adapter! This is much clearer! Because there is a link to the interface! Unlike the previous iptables-L-n! You can understand this! However, since this rule is not what we want, how can we modify it? It is recommended that you delete the rules before creating the required rules! So how to clear rules? This is right:
[Root @ www ~] # Iptables [-t tables] [-FXZ] Options and parameters:-F: Clear all predefined rules;-X: kill the "Custom" chain (tables) of all users.-Z: returns the count and traffic statistics of all chains to zero. Example: Clear the local firewall (filter) all rules of [root @ www ~] # Iptables-F [root @ www ~] # Iptables-X [root @ www ~] # Iptables-Z

These three commands will clear all the rules of the local firewall, but will not change the preset policy, so if you do not issue these three lines of commands on the local machine, it is very likely that you will be out of the door by yourself (if the INPUT is set to DROP )! Be careful!

In general, when we redefine the firewall, we will first clear the rules for it. As we mentioned earlier, the "Rule Order" of the firewall has special significance. So, of course, it is easier to clear the rules first and set them one by one. Let's talk about defining preset policies!

Define preset policies)

After the rules are cleared, the next step is to set the rule policy! Do you still remember what policies mean? "When your package is not in the rules you set, the pass of the package is subject to the Policy setting." In the local preset Policy, if you have confidence in internal users, the INPUT chain in the filter can be defined more strictly, while the FORWARD and OUTPUT can be set more loosely! Generally, the INPUT policy is defined as DROP, and the other two are defined as ACCEPT. As for the nat table, ignore it for the moment.

[Root @ www ~] # Iptables [-t nat]-P [INPUT, OUTPUT, FORWARD] [ACCEPT, DROP] Options and parameters:-P: define Policy ). Note: P is in uppercase! ACCEPT: This packet can accept drop: the packet is directly discarded, so that the client does not know why it is discarded. Example: Set the INPUT of the Local Machine to DROP, and the other to ACCEPT [root @ www ~]. # Iptables-p input drop [root @ www ~] # Iptables-p output accept [root @ www ~] # Iptables-p forward accept [root @ www ~] # Iptables-save # Generated by iptables-save v1.4.7 on Fri Jul 22 15:56:34 2011 * filter: input drop [0: 0]: forward accept [0: 0]: output accept [0: 0] COMMIT # Completed on Fri Jul 22 15:56:34 2011 # Since the INPUT is set to DROP and there are no rules yet, the above OUTPUT result shows: # All packets cannot enter your host! No firewall settings are available! (Network connection is bidirectional)
Can I see the output result? INPUT has been modified! The default policy settings for the three links of other nat tables are the same. For example, "iptables-t nat-p prerouting accept" sets the acceptable meaning of the nat table PREROUTING chain! After the preset policy is set, let's talk about the packet basic comparison settings of various rules.

Basic packet comparison: IP, domain, and interface device

Start to configure the firewall rule packets! Since it is the Internet, we will talk about the most basic IP address, domain name and port, that is, the third layer of OSI, and the limitations of devices (network cards. You must remember the syntax of this section and the next section, because this is the most basic syntax for comparison!

[Root @ www ~] # Iptables [-AI chain name] [-io network interface] [-p protocol] \> [-s source IP/domain] [-d target IP/domain]-j [ACCEPT | DROP | REJECT | LOG] Options and parameters: -AI chain name: "insert" or "accumulate"-A: adds A rule to the end of the original rule. For example, if you already have four rules, use-A to add the Fifth rule! -I: Insert a rule. If the sequence of the rule is not specified, insert is the first rule by default. For example, if there are four rules, use-I to change the rule to the first one, and the original four rules to the second one ~ Chain 5: There are INPUT, OUTPUT, FORWARD, etc. The chain name is related to-io, please refer to below. -I/O network interface: Set the packet inbound and outbound interface specification-I: the network interface that the packet enters, such as eth0 and lo. -O: the network interface sent out by the packet. It must be used with the OUTPUT chain.-p protocol: this rule is applicable to the following packet formats: tcp, udp, icmp, and all. -S source IP/domain: Set the source project of the packet for this rule. You can specify a pure IP address or a domain, for example, IP: domain:,192.168 .0.0/ If the rule is "not allowed", add it! -S! indicates that no packet source of is allowed;-d target IP Address/domain: Same as-s, but here it refers to the target IP address or domain. -J: The following actions: ACCEPT, DROP, REJECT, and LOG)
The basic parameters of iptables are as shown above. Only information about IP addresses, domains, and devices is described. For TCP, the port number and status (such as SYN flag) of UDP packets are described) it will not be discussed in the next section. Well, let's take a look at the most basic rules, such as opening the lo local interface and an IP source!
Example: Set lo to a trusted device, that is, the packets entering and exiting lo are accepted [root @ www ~] # Iptables-a input-I lo-j ACCEPT

Taking a closer look at the rules not listed above, such as-s and-d, this means that no matter where the packet comes from or where it goes, it will be accepted as long as it comes from the lo interface! This concept is very important, that is, "No specified project, it means that the project is completely accepted! For example, in this case, when there are no parameters for-s,-d... and so on, it means that no matter what value is accepted.

This is the so-called trust device! Assume that your host has two Ethernet cards, one of which is an internal domain. Assume that the NIC code is eth1. If the internal domain is trustworthy, then the incoming and outgoing packets of the NIC will be accepted, and you can use "iptables-a input-I eth1-j ACCEPT" to set the device as A trusted device. However, pay special attention before issuing this command, because it means that this Nic has no defense!

Example: as long as the packet from the Intranet ( is accepted [root @ www ~] # Iptables-a input-I eth1-s ACCEPT # because it is accepted by the Intranet, it can also be called "trust domain. Example: accept the IP address as long as it comes from, but discard the malicious IP address [root @ www ~]. # Iptables-a input-I eth1-s ACCEPT [root @ www ~] # Iptables-a input-I eth1-s DROP # For A single IP source, it can be regarded as A trusted host or A untrusted malicious source! [Root @ www ~] # Iptables-save # Generated by iptables-save v1.4.7 on Fri Jul 22 16:00:43 2011 * filter: input drop [0: 0]: forward accept [0: 0]: output accept [17: 1724]-a input-I lo-j ACCEPT-A INPUT-s eth1-j ACCEPT-A INPUT-s eth1-j ACCEPT-A INPUT-s 32-I eth1-j DROPCOMMIT # Completed on Fri Jul 22 16:00:43 2011
This is the simplest way to set and observe firewall rules. However, in the above case, you also found that two rules may be faulty ~ That is the rule order circled by the special fonts above. The rule has been released, so it is impossible to use the rule! This is the firewall setting! Understand Hu? What should we do? Just hit again! @_@! What if you want to record a rule? You can do this:
[root@www ~]# iptables -A INPUT -s -j LOG[root@www ~]# iptables -L -ntarget prot opt source         destinationLOG    all  --   LOG flags 0 level 4
To the leftmost of the output result, LOG appears! As long as there is a packet from the IP address, the packet information will be written to the core message, that is, the file/var/log/messages. Then the packet will continue to be compared with subsequent rules. Therefore, the LOG action is only recorded, and does not affect the comparison of other rules of the packet. Now let's take a look at the comparison of TCP, UDP, and ICMP packet rules!

Comparison of TCP and UDP rules: Set ports

When talking about TCP and UDP, the port is special. In TCP, there is also the so-called online packet status, including the most common SYN active online packet format. How can we set firewall rules for these two packet formats? You can see as follows:

[Root @ www ~] # Iptables [-AI chain] [-io network interface] [-p tcp, udp] \> [-s source IP address/domain] [-- sport port range] \> [-d target IP Address/domain] [-- dport port range]-j [ACCEPT | DROP | REJECT] Options and parameters: -- sport port range: restrict the source port number. The port number can be continuous, for example, 1024: 65535 -- dport range: restrict the target port number.
In fact, there are two more things -- sport and -- dport. The focus is on that port! Note that only tcp and udp packets have ports, so when you want to use -- dport, -- sport, you must add the-p tcp or-p udp parameter to make the request succeed! Let's perform a few small tests:
Example: all packets that want to connect to port 21 on the local machine are blocked: [root @ www ~] # Iptables-a input-I eth0-p tcp -- dport 21-j DROP example: Wangfang (upd port 137,138 tcp port 139,445) Who wants to connect to my host) allow [root @ www ~] # Iptables-a input-I eth0-p udp -- dport 137: 138-j ACCEPT [root @ www ~] # Iptables-a input-I eth0-p tcp -- dport 139-j ACCEPT [root @ www ~] # Iptables-a input-I eth0-p tcp -- dport 445-j ACCEPT
Look! You can use the port numbers of UDP and TCP to enable or disable some services! You can also handle it comprehensively! For example, if a packet from port 1024: port 65535 of is sent and the ssh port to connect to the local machine is blocked, you can do this:
[root@www ~]# iptables -A INPUT -i eth0 -p tcp -s \> --sport 1024:65534 --dport ssh -j DROP
What will happen if you forget to add-p tcp and use -- dport?
[root@www ~]# iptables -A INPUT -i eth0 --dport 21 -j DROPiptables v1.4.7: unknown option `--dport'Try `iptables -h' or 'iptables --help' for more information.

You may find it strange. How can "-- dport" Be an unknown parameter (arg? This is because-p tcp or-p udp is not added! Very important!

In addition to ports, there are also special flag in TCP! The most common is the SYN flag that actively comes online. We also support the "-- syn" Processing Method in iptables. Let's explain it in the following example:

Example: route the port from any source port to the local port and discard it [root @ www ~] # Iptables-a input-I eth0-p tcp -- sport \> -- dport -- syn-j DROP
Generally, ports enabled on the client are ports larger than 1024, while ports enabled on the server are listening ports smaller than 1023. Therefore, we can discard all the remote active connections of Port Data smaller than 1023! But it is not applicable to active FTP connection! Let's talk about this part of FTP server in Chapter 21 in the future!

Iptables plug-in module: mac and state

When you use ipchains to manage the firewall before kernel 2.2, the system administrator usually has a headache! Because ipchains does not have a so-called packet status module, we must control the inbound and outbound packets. For example, if you want to connect to port 22 of the remote host, you must set two rules:

  • Port 22 at the local end 1024: 65535 to remote port 22 must be allowed (OUTPUT chain );
  • The remote host port 22 must be opened (INPUT chain) to the host's 1024: 65535 );

This is troublesome! Because if you want to connect to port 22 of 10 hosts, assuming that OUTPUT is enabled by default (ACCEPT), you still need to fill in ten rows of rules, let the port 22 of the ten remote hosts be connected to your local host. What if all port 22 is enabled? We are also worried that some Malicious Hosts will take the initiative to bring port 22 to your machine! In the same way, if you want to allow the local host to connect to the external port 80 (WWW Service), it will be even worse ~ This is a very important concept of two-way network connection!

Fortunately, our iptables does not bother us! He can use a status module to analyze whether the packet he wants to enter is the response that I just sent ?』 If the response is just sent, you can accept it! Wow! Awesome! In this way, you don't have to worry about whether the remote host is online! How can this problem be achieved? Look at the syntax below:

[Root @ www ~] # Iptables-a input [-m state] [-- state] Options and parameters:-m: Some plug-ins of iptables, including: state: Status Module mac: hardware address of the network card (hardware address) -- state: the status of some packets, mainly including: INVALID Packets, such as the status of damaged packets ESTABLISHED: online status that has been online successfully; NEW: You want to create a NEW package status. RELATED: This is the most common option! This indicates that the package is related to the packets sent by our host: the package is successfully established or passed as long as it is an invalid package. [root @ www ~] # Iptables-a input-m state \> -- state RELATED, ESTABLISHED-j ACCEPT [root @ www ~] # Iptables-a input-m state -- state INVALID-j DROP
In this way, our iptables will take the initiative to analyze whether the packet is in the response state, if so, it will be accepted directly. Haha! In this way, you do not need to write individual firewall rules for response packets! This is amazing! Next, let's talk about another plug-in of iptables, that is, to allow and defend against NICs:
Example: open its connection to the aa: bb: cc: dd: ee: ff host in the local area network [root @ www ~] # Iptables-a input-m mac -- mac-source aa: bb: cc: dd: ee: ff \>-j ACCEPT Option and parameter: -- mac-source: the MAC of the source host!
What should you do if you have some network experts who can always try to run outside the vro by modifying the IP address? Will the whole district network be rejected? You don't need it. You can catch the MAC of that host through the ARP-related concepts mentioned earlier, and then DROP the entire host through the above mechanism. No matter what IP address he has changed, unless he knows that you are using the MAC of the network card to manage it, he will not be able to get out! Understand Hu?

ICMP packet rule comparison: Design for ping response

If it is not used as a router host, we usually remove ICMP type 8 (echo request), so that the remote host does not know whether or not we exist and does not accept the ping response. The ICMP packet format is as follows:

[Root @ www ~] # Iptables-a input [-p icmp] [-- icmp-type]-j ACCEPT options and parameters: -- icmp-type: the type of the packet that must be followed by ICMP, you can also use the Code. For example, 8 indicates the meaning of echo request. Example: Enable the ICMP type of, to enter the local machine: [root @ www ~] # Vi somefile #! /Bin/bashicmp_type = "0 3 4 11 12 14 16 18" for typeicmp in $ icmp_typedo iptables-a input-I eth0-p icmp -- icmp-type $ typeicmp-j ACCEPTdone [root @ www ~] # Sh somefile
In this way, some ICMP packet formats can be opened to the Local Machine for network detection! However, if your host is a vro of the zone network, we recommend that you Allow icmp packets! This is because the client often uses ping to test whether the router line is smooth when detecting the network! So do not turn off the icmp of the vro. This will happen!

Design of the superyangchun Client Firewall and storage of firewall rules

After analyzing the above-mentioned local iptables syntax, let's take a look at how to design your firewall if you are a Linux local role that does not provide network services on the client side? To be honest, you only need to analyze the default firewall rules of CentOS. Theoretically, you should have the following rules:

This is the most popular firewall. You can guard against all remote source packets through step 2, and allow the remote host response packets you require to access through step 4, in addition, let the local loo internal loop device be able to pass through, hey! A client-specific firewall rule is OK! You can do this on a script:

[Root @ www ~] # Vim bin/firewall. sh #! /Bin/bashPATH =/sbin:/bin:/usr/sbin:/usr/bin; export PATH #1. clear rules iptables-Fiptables-Xiptables-Z #2. set the policy iptables-p input DROPiptables-p output ACCEPTiptables-p forward accept #3 ~ 5. develop rules iptables-a input-I lo-j ACCEPTiptables-a input-I eth0-m state -- state RELATED, ESTABLISHED-j ACCEPT # iptables-a input-I eth0-s ACCEPT #6. write the firewall rule configuration file/etc/init. d/iptables save [root @ www ~] # Sh bin/firewall. shiptables: Saving firewall rules to/etc/sysconfig/iptables: [OK]
In fact, the firewall is also a service. You can view it through "chkconfig -- list iptables. Therefore, if you want to save the changes at the next boot, you need to add parameters to the "/etc/init. d/iptables save" command. As a result, laruence now writes the stored actions to this firewall. sh script, which is more simple! Now, your Linux host has been quite protected. If you want to act as a server or a vro, you have to add custom rules on your own.

To be honest, if you are familiar with Linux, directly modify/etc/sysconfig/iptables and restart the iptables service. Then, your firewall rules will continue to exist after the system is started!

After setting the rules, you must test the rules! So how to test it?

Step by step, let's see where the problem is, and then make improvements and improvements! Basically, a lot of information on the Internet can provide you with a good reference! The setting in this article is very simple, and most of them are still in the introduction phase! Hope to help you!

Related Article

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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