Linux Firewall iptables Basic explanation

Source: Internet
Author: User
Tags ack types of extensions

Original from: https://www.linuxidc.com/Linux/2017-01/140073.htm (quote from)

A: Preface

Firewall, in fact, is used to realize the Linux access control functions, it is divided into hardware or software firewall two. Regardless of the network in which the firewall works, it must be at the edge of the network. And our task is to define how the firewall works, this is the firewall policy, rules, in order to allow it to access the network of IP, data detection.

At present, there are more common on the market has 3, 4 layer of firewall, called the network layer of firewalls, there are 7 layers of firewalls, in fact, is the proxy layer gateway.

For the TCP/IP seven-tier model, we know that the third layer is the network layer, and the three layer firewall will detect the source address and the destination address on this layer. But for a seven-tier firewall, whatever your source or destination port, the source address or destination address, will check everything you have. So, for the design principle, the seven layer firewall is more secure, but this brings less efficiency. So the usual firewall scheme on the market is the combination of the two. And because we all need to access from the firewall control of this port, so the efficiency of the firewall becomes the user can access the data how much of the most important control, the configuration of the bad even may become the bottleneck of traffic.

II: The history and working principle of iptables

The development of 1.iptables:

Iptables, formerly known as Ipfirewall (Kernel 1.x ERA), is an easy access control tool that the author has migrated from FreeBSD to work in the kernel and to detect packets. But the ipfirewall work is extremely limited (it requires that all rules be put into the kernel so that rules can be run and put into the kernel, which is generally extremely difficult). When the kernel developed into the 2.x series, the software was renamed IPChains, it can define multiple rules, string them together, and now, it is called iptables, you can make a list of rules to achieve absolute detailed access control functions.

They're all working in the user space, the tool that defines the rule is not itself a firewall. They define rules that allow netfilter in the kernel space to be read and implemented to allow firewalls to work. Where the kernel must be placed, it must be the place where the TCP/IP protocol stack is located. Where the TCP/IP stack must pass, the place where the rules can be read is called NetFilter. (Network filter)

The authors have selected 5 locations in the kernel space,

1. In kernel space: from one network interface to another network interface

2. Packets from the kernel into the user space

3. Packets that flow out of the user space

4. Enter/leave the external network interface of the machine

5. Enter/leave the Local intranet interface

Working mechanism of 2.iptables

From the above development we know that the author chose 5 positions, to take control of the place, but you have not found that, in fact, the first three locations have basically been able to completely block the path, but why has been in and out of the mouth to set the level after the internal card? Because the packet has not been made routing decision, still do not know where the data to go, so there is no way to achieve data filtering in import and export. So to set up a forwarding level in the kernel space, enter the level of user space, from the user space out of the level. So, since they're useless, why do we have to place them? Because we are doing NAT and Dnat, the destination address translation must be converted before the route. So we have to set up the level at the interface of the external network and then intranet.

These five positions are also known as five hooks (hook functions), also called Five rule chains.

1.PREROUTING (before routing)

2.INPUT (Packet inflow): Responsible for filtering packets entering the host

3.FORWARD (Forward pipe card): Responsible for forwarding packets flowing through the host

4.OUTPUT (Packet egress): Responsible for processing packets sent from the host

5.POSTROUTING (after routing)

This is the NetFilter rules of the five rule chain, any one packet, as long as through this machine, will pass through one of these five chains.

3. Policies for Firewalls

Firewall policy is generally divided into two kinds, called "Pass" strategy, a "blocking" strategy, a strategy, the default door is closed, you must define who can enter. Blocking strategy is that the door is open, but you must have identity authentication, otherwise you cannot enter. So we want to define, let come in, let go out, so pass, is to all pass, and plugging, then is to choose. When we define a strategy, we define several functions, including the ability to define a policy that is allowed or disallowed in a packet, the function of filter filtering, and the NAT option to define the function of address translation. In order for these functions to work alternately, we have developed the definition of "table" to define and differentiate the different working functions and processing methods.

We now use more than 3 different features:

1.filter definition allows or does not allow

2.nat defines the address translation

3.mangle function: Modify message original data

We modify the message original data is to modify the TTL. It is possible to disassemble the metadata of the packet and mark/modify the contents. and the firewall tag, in fact, is to rely on mangle to achieve.

Small extensions:

For filter generally can only be done on 3 chains: INPUT, FORWARD, OUTPUT

In general, Nat can only be done on 3 chains: Prerouting, OUTPUT, postrouting

And Mangle is a 5 chain can do: prerouting,input,forward,output,postrouting

Iptables/netfilter (the software) is working in user space, which allows the rules to take effect, is not a service in itself, and the rules are effective immediately. And our iptables is now being made into a service that can be started and stopped. Starts, the rule takes effect directly and stops, then the rule is revoked.

Iptables also supports its own definition chain. But the chain that you define must be associated with a particular chain. In a level setting, specify that when there is data to be dedicated to a particular chain to deal with, when the chain is finished, then return. Then continue checking in a particular chain.

Note: The order of the rules is very critical, the stricter the rules, the more forward you should put, and check the rules by the way they are checked from the top down.

Three The wording of the rule:

Iptables defines rules in a more complex way:

Format: iptables [-t table] COMMAND chain Cretiria-j ACTION

-T Table:3 a filter NAT mangle

COMMAND: Define how rules are managed

Chain: Specifies which chain your next rule is to operate on, which can be omitted when defining a policy

Cretiria: Specifying Matching Criteria

-j ACTION: Specify how to Handle

For example: 172.16.0.0/24 is not allowed to access.

Iptables-t filter-a input-s 172.16.0.0/16-p UDP--dport 53-j DROP

Of course, if you want to refuse more thoroughly:

Iptables-t filter-r INPUT 1-s 172.16.0.0/16-p UDP--dport 53-j REJECT

Iptables-l-n-v
#查看定义规则的详细信息

Four: detailed command:

1. Chain management commands (which are immediately effective)

-P: Set Default policy (set default door is closed or open)

The default policy generally has only two

Iptables-p INPUT (drop| ACCEPT) is off by default/open by default

Like what:

Iptables-p INPUT Drop This will deny the default rule. And there is no action defined, so all the rules about the outside connection, including the Xshell connection, are rejected by the remote connection.

-f:flash, emptying the rule chain (note the administrative permissions for each chain)

Iptables-t nat-f prerouting

Iptables-t Nat-f clears all the chains of the NAT table

-n:new enables users to create a new chain

The Iptables-n inbound_tcp_web indicates that it is attached to the TCP table for checking the web.

-X: Used to delete a user-defined empty chain

The use method is the same as-N, but the chain must be emptied before it is deleted.

-E: Used to rename chain is primarily used to rename a user-defined chain

-E oldname newname

-Z: Empty The chain, and the default rule in the chain counter (there are two counters, the number of packets to match, how many bytes)

Iptables-z: Empty

2. Rule Management Commands

-A: Append, add a rule at the end of the current chain

-I num: Insert to insert the current rule into the first few.

-I 3: Insert as third article

-R num:replays Replace/modify the rules

Format: Iptables-r 3 ......

-D Num: Delete, explicitly specify delete rule

3. View the admin command "-l"

Additional subcommands

-N: Displays the IP in a digital manner, which displays the IP directly and, if not, resolves the IP back to the hostname.

-V: Show more information

-vv

-VVV: The more the more detailed

-X: Displays the exact value on the counter, does not do the unit conversion

--line-numbers: Displays the line number of the rule

-T NAT: Displays information for all levels

Five: Detailed matching Criteria

1. Generic match: Match of source address destination address

-S: Specifies that the host name cannot be specified as the source address, and must be an IP

IP | Ip/mask | 0.0.0.0/0.0.0.0

And the address can be reversed, plus a "!" Indicates that except which IP

-D: Indicates matching destination address

-P: For matching protocol (there are usually 3 protocols here, TCP/UDP/ICMP)

-I eth0: Incoming data from this NIC

Inflow is generally used on input and prerouting

-O eth0: Data streamed out of this NIC

Outflow is generally on output and postrouting

2. Extended Match

2.1 Implied extensions: Extensions to Protocols

The extension of the-P TCP:TCP protocol. There are generally three types of extensions

--dport xx-xx: Specify the destination port, you cannot specify multiple noncontiguous ports, you can specify only a single port, such as

--dport 21 or--dport 21-23 (this means 21,22,23)

--sport: Specifying the source port

--TCP-FIAGS:TCP's Flag (Syn,ack,fin,psh,rst,urg)

For it, two parameters are usually followed:

1. Check the flag bit

2. Must be 1 of the flag bit

--tcpflags Syn,ack,fin,rst syn =--syn

Indicates that the 4 bits are checked, that the SYN in the 4 bits must be 1, and the other must be 0. So this is the first time the package is used to detect three handshakes. For this package that specifically matches the first packet of SYN 1, there is also a shorthand method called--syn

Extension of-P UDP:UDP protocol

--dport

--sport

Extension of the-P ICMP:ICMP data message

--icmp-type:

Echo-request (Request echo), generally denoted by 8来

So--icmp-type 8 matches the request Echo packet

Echo-reply (response packets) are generally expressed in

2.2 Explicit expansion (-m)

Expansion of various modules

-M Multiport: indicates enabling multiport expansion

Then we can enable it, like--dports 21,23,80.

VI: Detailed-J ACTION

Common action:

Drop: Silently Discard

We often use drop to hide our identities and hide our lists

REJECT: Express Refusal

Accept: Acceptance

Custom_chain: Turning to a custom chain

DNAT

SNAT

Masquerade: Source Address Spoofing

REDIRECT: Redirect: Used primarily for port redirection

Mark: Hit the firewall tag

return: Back

Returns the original rule chain after the custom chain has finished executing.

Exercises 1:

As long as it is from the 172.16.0.0/16 network segment allows access to my native 172.16.100.1 sshd service

Analysis: The first must be defined in the Allow table. Because there is no need to do NAT address translation and so on, and then view our sshd service, on port 22nd, the processing mechanism is accepted, for this table, there needs to be one back two rules, if we allow or deny, for access to native services, we'd better be defined on the input chain, And the output is defined as well. (The initial end of the session is defined first), so the rule is:

Defined in: Iptables-t filter-a input-s 172.16.0.0/16-d 172.16.100.1-p tcp--dport 22-j ACCEPT

Defined: iptables-t filter-a output-s 172.16.100.1-d 172.16.0.0/16-p tcp--dport 22-j ACCEPT

Change the default policy to drop:

Iptables-p INPUT DROP

Iptables-p OUTPUT DROP

Iptables-p FORWARD DROP

Seven: State detection:

is an explicit extension that detects the connection between sessions, and with detection we can extend the functionality between sessions.

What is stateful inspection? For the entire TCP protocol, it is a connected protocol, three handshake, the first handshake, we call the new connection, and from the second handshake, the ACK is 1, which is normal data transmission, and TCP's second third handshake, called the established connection (established), There is a state, more bizarre, such as: Syn=1 ack=1 rst=1, for this we do not recognize, we call invalid unrecognized. There is a fourth, FTP this ancient features, each port is independent, ports 21st and 20th are a go back, they are related, this relationship we call related.

So we have a total of four kinds of states:

NEW

Established

Related

INVALID

So we can increase the state detection for the exercises we just did. For example, only allow the state to enter the new and established, go out only allow established state out, this can be more common rebound Trojan has a good control mechanism.

For an extension of the exercises:

In the refusal to go out of the permit, come in only allow established come in, go out only allow established out. Default rules use Deny

Iptables-l-N--line-number: View the previous rule in the first few lines

Overwrite input

Iptables-r INPUT 2-s 172.16.0.0/16-d 172.16.100.1-p TCP--dport 22-m State--state new,established-j ACCEPT

Iptables-r OUTPUT 1-m State--state established-j ACCEPT

Now, if you want to release a 80 port, how can it be released?

Iptables-a input-d 172.16.100.1-p TCP--dport 80-m State--state new,established-j ACCEPT

Iptables-r INPUT 1-d 172.16.100.1-p UDP--dport 53-j ACCEPT

Exercises 2:

If we allow ourselves to ping others, but others ping their ping does not work how to achieve it?

Analysis: For ping This Protocol, comes in 8 (ping), out of 0 (response). We need 8 out of the way to get there, allow 0 to come in.

On the outgoing port: iptables-a output-p ICMP--icmp-type 8-j ACCEPT

On the incoming port: iptables-a input-p ICMP--icmp-type 0-j ACCEPT

Small extension: For 127.0.0.1 is special, we need to clearly define it

Iptables-a input-s 127.0.0.1-d 127.0.0.1-j ACCEPT

Iptables-a output-s 127.0.0.1-d 127.0.0.1-j ACCEPT

VIII: The realization of Snat and Dnat

Because we now have a very tight IP address, we have already allocated it, which leads us to address translation to conserve only a bit of the IP resources we have left. So how do you implement NAT's address translation through Iptables?

1.SNAT conversion based on the original address

The conversion based on the original address is generally used in many of our intranet users through an external network of the port when the Internet, then we will be the address of our intranet into a network of IP, we can achieve the ability to connect to other external network IP.

So we're going to define exactly how to convert in Iptables:

The defined style:

For example, we now want all the IP of the 192.168.10.0 network segment to be converted into a 172.16.100.1 this hypothetical extranet address:

Iptables-t nat-a postrouting-s 192.168.10.0/24-j SNAT--to-source 172.16.100.1

In this way, any attempt to access the network through the NIC from the local network will be converted to the IP 172.16.100.1.

So, what if the 172.16.100.1 is not fixed?

We all know when we use Unicom or telecom Internet, it will be in every time you turn on the random generation of an external network IP, meaning that the external network address is dynamic transformation. At this point we will change the address of the external network to masquerade (dynamic camouflage): It can automatically find out the address of the network, and automatically change it to the correct external network address. So, we need to set this up:

Iptables-t nat-a postrouting-s 192.168.10.0/24-j Masquerade

It is important to note that address spoofing does not apply to all places.

2.DNAT Destination Address Translation

For the destination address translation, the data flow is from the outside of the client, the inside is the server side through the destination address translation, we can let the outside of the IP through our external IP to access our servers different servers, and our services are placed on different servers in the intranet server.

How do I do destination address translation? :

Iptables-t nat-a prerouting-d 192.168.10.18-p tcp--dport 80-j DNAT--todestination 172.16.100.2

The destination address translation is to be converted before it reaches the NIC, so it should be done in the prerouting position.

IX: Control of the storage and opening of rules

Note: All of the content you define will expire when you restart, and you need to save it with a command if you want us to take effect.

1.service iptables Save Command

It will be saved in the/etc/sysconfig/iptables file.

2.iptables-save command

Iptables-save >/etc/sysconfig/iptables

3.iptables-restore command

It will automatically load/etc/sysconfig/iptabels when it is powered on

If the boot does not load or does not load, and you want to have a self-written configuration file (assuming iptables.2) to be manually effective:

Iptables-restore </etc/sysconfig/iptables.2

The rules defined in Iptables are completed manually

Ten: Iptables workflow

Linux Firewall iptables Basic explanation

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.