Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Firewall and basic usage of netfilter basic iptables

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

Iptables

Firewall:

Host firewall

Network firewall

Working at the edge of the host or network, the incoming and outgoing messages are checked according to pre-defined rules, and those components that can be matched by the rules are processed accordingly.

Network Firewall:

Professional hardware firewall:

Checkpoint,netscreen

Host:

Iptables: program

Iptables: rule authoring tool

Netfilter: a network filter, a framework in the kernel that works on the TCP/IP network protocol stack

IDS:IntrusionDetecting System

NIDS

HIDS

IPS:Intrusion Protec System

HoneyPot: honeypot

Kali, (backtrack)

OpenBSD:

Ipfw

Ipchains

Iptables/netfilter

Kernel,framework

Hooksfunction:

Prerouting: before the local back routing function occurs

Input: get inside the machine

Output: issued by this machine

Forward: forwarded locally

Postrouting: after the routing function occurs, before leaving the machine

When routing occurs:

After the message enters this machine:

Determine the destination address

Before the message leaves the machine:

Determine which interface to send

The location through which the message flows:

To this internal: prerouting, input

Issued by this machine: output, postrouting

Forwarded by this machine: prerouting, forward, postrouing

The function of the rule:

Filtering: firewall

Address translation: NAT Server

NetworkAddress Translation

Mangle: modify some information in the header of the message

Raw: turn off connection tracking enabled on the nat table

Filter:input,forward, output

Nat:prerouting,output, postrouting

Mangle:prerouting,input, forward, output, postrouting

Raw:prerouting,output

Iptables: n rules can be placed on each hook function; multiple rules corresponding to each hook are called a CHAIN

Each function has multiple chains, so it is called a table.

Chain: the order of rules on the chain is the order of inspection, so there are certain rules.

(1) for similar rules, the ones with small matching range are put on top.

(2) for different kinds of rules, matching messages are more likely to be put on top.

(3) the default policy should be set.

Iptables/netfilter

Netfilter:framework in kernel

Tcp/ip protocol stack

Iptables has four watches and five chains.

Filter:input, forward, output

Considerations when adding rules:

(1) function to be implemented: determine which table to add to

(2) message flow and path: determine which chain to add to

Priority of the function:

From high to low:

Raw-- > mangle-- > nat-- > filter

Components of the rules:

The matching condition of the message, and how to deal with it after matching

Matching conditions: basic matching conditions, extended matching conditions

How to deal with: built-in processing mechanism, custom processing mechanism (custom chain)

Note: the message cannot go through the custom chain, only the reference on the built-in chain can take effect (that is, as the custom target)

Iptables: a rule management tool

Automatically implement syntax checking of rules

Rules and chains have counters:

Pkts: the number of messages matched by a rule or chain

Bytes: the sum of all message sizes matched by a rule or chain

Chain: there should be a default policy

The iptables command generates rules and sends them to netfilter

The rules are sent directly to the kernel through the kernel interface, so they take effect immediately. But it won't last forever.

If you expect it to be permanent, you need to save it to a configuration file, which is also loaded when powered on and manually loaded by the user

Iptables [- t TABLE] SUBCOMMAND CHAIN CRETERIA-j TARGET

-tTABLE:

The default is filter, and four filter, nat, mangle and raw are available.

SUBCOMMAND:

Chain:

-F:flush to clear all rules on the specified chain of the specified table; when omitting the chain name, clear all chains in the table

Example:

[root@localhost~] # iptables-F INPUT

[root@localhost~] # iptables-F OUTPUT

-N:new, create a new user-defined chain; the custom chain can only be used as a jump object on the default chain, that is, the custom chain takes effect by reference in the default chain

Example:

-X:drop to delete user-defined empty chains; non-empty custom chains and built-in chains cannot be deleted

-Z:zero, set the counter of the rule to 0

-P:policy, sets the default processing mechanism of the chain; when all cannot be matched or the matching cannot make an effective processing mechanism, the default policy will take effect.

Available policies for filter table: ACCEPT,DROP, REJECT

Example: indicates that the table INPUT chain of filter defaults to DROP

Iptables-t filter-P INPUT DROP

-E:rename, renaming the custom chain

Note: the chain in the reference cannot be deleted and renamed

Rules:

-A:append, append a rule to the end of the chain

-I:insert, inserting a rule at the specified location

-D:delete to delete the specified rule

-R:replace, replacing the specified rule

View:

-L:list, listing all rules on the specified chain

-n: numeric, which displays the address and port number in numeric format, that is, it does not converse

-v: verbose, detail format, displays the details of rules, including rule counters, etc.

-vv:

-vvv:

-- line-numbers: displays the rule number

You can display the number of the rule

Iptables-L-n-- line-numbers

-x: exactly, which displays the exact value of the counter

Pktsbytes target prot opt in out source destination

Pkts: the number of packets matched by this rule

Bytes: the sum of the size of the package matched by this rule

Target: processing targets (targets can be user-defined chains)

Prot: protocol {tcp,udp, icmp}

Opt: optional

In: packets flow into the interface

Out: packet outflow interface

Source: source addr

Destination: destination addr

CRETERIA: matching condition

Check the IP header, check the TCP, UDP or ICMP header

Based on the extension mechanism, additional checks can also be performed, such as connection tracking

Note: multiple conditions can be specified at the same time, and the default multiple conditions should be satisfied at the same time.

Matching criteria:

Universal matching:

[!]-s,-- src,-- source IP | Network: check the source IP address in the message

-d,-- dst,-- destination: check the destination IP address in the message

-p,-- protocol: check the protocol in the message, that is, the protocol identified by protocols in the header of ip; one of tcp, udp, or icmp

-I,-- in-interface: the inflow interface of datagrams; usually used only for rules on PREROUTING, INPUT, and FORWARD chains

-o,-- out-interface: check the outgoing interface of the message; it is usually only used for rules on FORWARD, OUTPUT, and POSTROUTING chains

Example: replace the first rule and check for the header of tcp protocol

Iptables-t filter-R INPUT 1-s 172.16.250.145-d 172.16.249.139-ptcp-j ACCEPT

Add an icmp protocol

Iptables-t filter-R INPUT 1-s 172.16.250.145-d 172.16.249.139-picmp-j ACCEPT

Example: change the default policy of INPUT to DROP

Iptables-t filter-P INPUTDROP

For example, replace the original second rule with the icmp protocol entered through the eth0 port.

[root@localhost] # iptables-R INPUT 2-s 172.16.250.145-d172.16.249.139-p icmp-I eth0-j ACCEPT

[root@localhost] # iptables-L-n-v-- line-numbers

Chain INPUT (policy DROP 7 packets, 796bytes)

Num pkts bytes target prot opt in out source destination

1 1546 113K ACCEPT tcp-172.16.250.145 172.16.249.139

200 ACCEPT icmp-- eth0 * 172.16.250.145 172.16.249.139

Extended matching: using iptables modules to implement extensibility checking mechanism

Implicit extension: if the protocol is indicated by using the-p option on the universal match, then using the-m option to indicate that the extension to its protocol becomes optional

Tcp:

-- dportPORT [- PORT]

-- sport

-- tcp-flagsLIST1 LIST2

LIST1: flag bits to check

LIST2: occurs in LIST1 and must be marked with 1 bit, while the rest must be 0

For example:-- tcp-flags syn,ack,fin,rst syn

-- syn: used to match the first three-way handshake in a tcp session

For example, the target port 80 is prohibited

Iptables-I INPUT 1-s 172.16.250.145-d172.16.249.139-p tcp-m tcp-- dport 80-j DROP (- m tcp may not be written)

Udp:

-- sport

-- dport

Icmp:

-- icmp-types

8:echo request

0:echo reply

Exercise:

1. Release the ssh and http services on the local machine. Both input and output policies are required to be DROP by default.

2. Open native responses to ping and ping requests

Explicit extension: the extension mechanism used must be specified

-m module name

Each module introduces a new matching mechanism

Want to know which modules are available:

Rpm-ql iptables

Lowercase letters ending with .so

Multiport extension:

Define multi-port matches in discrete terms; specify up to 15 ports

Dedicated options:

-- source-ports,--sports PORT [, PORT,...]

-- destination-ports,--dports PORT [, PORT,...]

-- portsPORT [, PORT,...]

Example:

Iptables-I INPUT 1-d 172.16.100.11-p tcp-m multiport-- dports 22 80443-j ACCEPT

Iptables-I OUTPUT 1-s 172.16.100.11-p tcp-m multiport-- sports 22 80443-j ACCEPT

Iprange extension:

Specifies a contiguous range of ip addresses; used when matching non-entire network addresses

Dedicated options:

[!]-- src-range IP [- IP]

[!]-- dst-range IP [- IP]

Example:

Iptables-An INPUT-d 172.16.100.11-p tcp-- dport 23-m iprange-- src-range172.16.100.1-172.16.100.100-j ACCEPT

Iptables-An OUTPUT-s 172.16.100.11-p tcp-- sport 23-m iprange-- dst-range172.16.100.1-172.16.100.100-j ACCEPT

String extension:

Check the string that appears in the message to match the given string

String matching checking algorithm:

Kmp,bm

Dedicated options:

-- algo {kmp | bm}

-string "STRING"

-- hex-string "HEX_STRING": HEX_STRING is a string encoded in hexadecimal format

Example:

Iptables-I OUTPUT 1-s 172.16.100.11-p tcp-- sport 80-m string-- string "sex"-- algo kmp-j REJECT

Time extension:

Access control based on time interval

Dedicated options:

-- datestartYYYY [- MM] [- DD] [hh [: mm [: ss]

-- dattestop

-- timestart

-- timestop

-- weekdaysDAY1 [, DAY2,...]

Example:

# iptables-R INPUT 1-d 172.16.100.11-p tcp-- dport 80-m time-- timestart08:30-- timestop 18:30-- weekdays Mon,Tue,Thu,Fri-j REJECT

Connlimit extension:

Limit based on the number of connections; limit the number of concurrent connections that can be initiated per IP

Dedicated options:

-- connlimit-above [n]

# iptables-I INPUT 2-d 172.16.100.11-p tcp-- dport 22-m connlimit--connlimit-above 5-j REJECT

Limit extension:

Limit based on the rate of sending packets

Dedicated option: token bucket algorithm

-- limit n [/ second | / minit | / hour | / day]

-- limit-burstn

Iptables-R INPUT 3-d 172.16.100.11-p icmp--icmp-type 8-m limit--limit 10/minute--limit-burst 5-j ACCEPT

Iptables/netfilter (3)

Explicit expansion (Cont.)

Connection template: connection tracking template, which is used to record connections and related status; implemented based on IP, regardless of whether it is TCP protocol or not; delete entries by countdown

Record the status of the connection:

NEW: the request made by the client for the first time when there is no entry in the connection tracking template for the newly established connection

After the ESTABLISHED:NEW status, the communication process that takes place before the entries in the margin tracking template are deleted is called ESTABLISHED

RELATED: associated connections, such as ftp protocol command connections and data connections, are associated connections

INVALIED: unrecognized statu

State extension: enable the connection tracking template to record the connection and match the extension of the connection status based on the connection

Before enabling connection tracking: simple packet filtering firewall

Enable connection tracking: packet filtering firewall with stateful inspection

Dedicated options:

-- stateSTATE

Adjust the maximum number of connections that the connection tracking feature can accommodate:

/ proc/sys/net/nf_conntrack_max

All connections currently tracked:

/ proc/net/nf_conntrack

Duration attribute when tracking for different protocols or connection types:

/ proc/sys/net/netfilter/

How to release a ftp service in passive mode:

(1) load module:

# modprobe nf_conntrack_ftp

(2) release request message

Release the request message with inbound request port 21

Release all inbound messages with ESTABLISHED and RELATED statuses

(3) release outbound response message

Release all outbound messages with the status of ESTABLISHED

How to save and reload rules:

Save:

(1) service iptables save

/ etc/sysconfig/iptables file

(2) iptables-save > / PATH/TO/SOMEFILE

Overload:

(1) service iptables reload

(2) iptables-restore

< /PATH/FROM/SOMEFILE NAT:Network AddressTranslation 仅从请求报文判断,地址转换: 源地址转换:SNAT 目标地址转换:DNAT 端口转换:PNAT NAT Server: 能根据需要实现所谓的SNAT、DNAT或PNAT; 并非是用户空间运行的进程完成转换功能,靠的是内核中地址转换规则; SNAT:CIP -->

SIP: CIP-- > SNAT (PIP)-- > SIP

CIP: local client address

DNAT:RemoteIP-- > PIP: RemoteIP-- > DNAT (SIP)-- > SIP

RemoteIP: remote client address

PNAT: Port translation

How private clients access the Internet:

(1) SNAT

(2) Proxy

SNAT: mainly used to enable intranet clients to access external hosts

Note: to be defined in the POSTROUTING chain; you can also use it on the OUTPUT

Definition method:

Iptables-t nat-A POSTROUTING-s intranet or host address-j SNAT-some extranet address on the to-source NAT server

Another TARGET:

MASQUERADE: address masquerade

Be able to determine which source address to switch to

Iptables-t nat-A POSTROUTING-s intranet or host address-j MASQUERADE

DNAT: mainly used to publish internal servers, so that servers in the internal network can be accessed in the external network

Note: to be defined in the PREROUTING chain

Iptables-t nat-A PREROUTING-d NAT server's public network address-p some protocol-dport port-jDNAT-to-destination intranet server address [: PORT]

FULLNAT: full address translation

When the request message arrives: modify both the source address and the destination address

Review:

State extension, nat

State extension:

Tcp finite state machine: finite state machine

Closed, listen, syn_sent, syn_rcvd,established, fin_wait_1, fin_wait_2, close_wait, last_ack, time_wait

State: regardless of tcp,udp or icmp protocols, connection tracking can be completed based on connection track template.

NEW,ESTABLISHED, RELATED, INVALID

Kernel modules: nf_conntrack, nf_conntrack_ftp

Dedicated option:-- state

Nat: network address translation; the table used is nat

SNAT: source address translation

DNAT: destination address translation

FULLNAT: both source and destination addresses are translated

Corresponding chain of nat table: PREROUTING,OUTPUT, POSTROUTING

SNAT:OUTPUT,POSTROUTING

-jSNAT-- to-source

-jMASQUERADE

DNAT:PREROUTING

PNAT:

-jDNAT-- to-destination IP [: PORT]

Iptables (4):

TARGET:

ACCEPT

DROP

REJECT

SNAT

DNAT

MASQUERADE

LOG: log

REDIRECT: Port redirection

RETURN: return to the caller

MARK: firewall tagging

Exercise: the default policy for INPUT and OUTPUT is DROP

Iptables-P INPUT DROP

Iptables-P OUTPUT DROP

1. Restrict access to the web server of the local host on Monday; the rate of new requests cannot exceed 100s per second; the web server does not allow access to pages containing admin strings; and the web server only allows response messages to leave the machine.

# iptables-An INPUT-d 172.16.18.1-p tcp-- dport 80-m time!-- weekdays Mon limit--limit10/minute-- limit-burst 5

! String-string "admin"-algo kmp-j ACCEPT

# iptables-AOUTPUT-s 172.16.18.1-p tcp-- dport 80-m time!-- weekdays Mon limit--limit 10/minute-- limit-burst 5

! String-string "admin"-algo kmp-j ACCEPT

2. During working hours, that is, from 8:30 to 18:00 from Monday to Friday, open the local ftp service to hosts in the 172.16.0.0 network; the number of data download requests should not exceed 5 per minute.

# iptables-An INPUT-s 172.16.0.0 time--timestart 16-d 172.16.18.1-ptcp-- dport 21-m time--timestart 08:30-timestop 18:30

-- weekdays Mon,Tue,Wed,Thu,Fri connlimit--connlimit-above 5-j REJECT

# iptables-An OUTPUT-s 172.16.18.1-d 172.16.0.0 time 16-p tcp-- dport 21-m time-- timestart 08:30-- timestop18:30

-- weekdays Mon,Tue,Wed,Thu,Fri connlimit--connlimit-above 5-j REJECT

3. Open the local ssh service to the host in 172.16.x.1-172.16.x.100. X is your seat number. The rate at which new requests are created must not exceed 2 per minute. Only response messages are allowed to leave the machine through their service ports.

Iptables-An INPUT-s 172.16.18.1-172.16.18.100-m connlimit--connlimit-above 5-state RELATED-j REJECT

Iptables-An OUTPUT-d 172.16.18.1-172.16.18.100-m connlimit--connlimit-above 5-state RELATED-j REJECT

4. Deny access to this machine for messages with TCP flag bits of all 1s and all zeros

Iptables-An INPUT-d172.16.18.1-p tcp--tcp-flags allnone-j REJECT

5. Allow other hosts to ping locally, but do not open other hosts ping native machines.

Iptables-An INPUT-d 172.16.18.1-p tcp-- dport 22-j REJECT

Iptables-An OUTPUT-s 172.16.18.1-p tcp-- dport 22-j ACCEPT

Exercise: judge the meaning of the following rules:

# iptables-N clean_in

# iptables-A clean_in-d 255.255.255.255-p icmp-j DROP

# iptables-A clean_in-d 172.16.255.255-p icmp-j DROP

# iptables-A clean_in-p tcp!-- syn-m state-- state NEW-j DROP

# iptables-A clean_in-p tcp--tcp-flags ALL ALL-j DROP

# iptables-A clean_in-p tcp--tcp-flags ALL NONE-j DROP

# iptables-A clean_in-d 172.16.100.7-j RETURN

# iptables-An INPUT-d 172.16.100.7-j clean_in

# iptables-An INPUT-I lo-j ACCEPT

# iptables-An OUTPUT-o lo-j ACCEPT

Run in and out from the lo port

# iptables-An INPUT-I eth0-m multiport-p tcp-- dports 531135135137139445-j DROP

# iptables-An INPUT-I eth0-m multiport-p udp-- dports 531135135137139445-j DROP

# iptables-An INPUT-I eth0-p udp-- dport1026-j DROP

# iptables-An INPUT-I eth0-m multiport-p tcp-- dports 1433 4899-j DROP

# iptables-An INPUT-p icmp-m limit--limit 10/second-j ACCEPT

Extracurricular tasks: study the use of recent extensions

Using the recent module of iptables to defend against DOS***:

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 300-- hitcount 3-- name SSH-j LOG--log-prefix "SSH Attack:"

Iptables-I INPUT-p tcp-- dport 22-m state--state NEW-m recent-- update-- seconds 300-- hitcount 3-- name SSH-j DROP

1. Use the connlimit module to set the concurrency of a single IP to 3; it will mistakenly kill users who use NAT to surf the Internet, and you can increase this value according to the actual situation.

two。 Using recent and state modules, a single IP can only establish 2 new connections with the local computer in 300s. Access can be resumed after being restricted for five minutes.

Here is an explanation for the last two sentences:

1. The second sentence records the new connection to port 22 of tcp. The record name is SSH

-- set records the source IP of the packet. If the IP already exists, the entry that already exists will be updated.

two。 The third sentence means that if a connection is initiated more than 3 times within the IP,300s in the SSH record, the connection of this IP is rejected.

-- update refers to updating the list every time a connection is established

-- seconds must be used with-- rcheck or-- update

-- hitcount must be used with-- rcheck or-- update

Record of 3.iptables: / proc/net/xt_recent/SSH

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report