
Shell命令
# Shell命令 ? 硬件·內核·監(jiān)測 ? iptables
iptables 命令是 Linux 上常用的防火墻軟件,是 netfilter 項目的一部分??梢灾苯优渲茫部梢酝ㄟ^許多前端和圖形界面配置。
通過 iptables 搭建的防火墻規(guī)則可以實現:
防攻擊
數據包轉發(fā)
等等..
iptables 中的4表5鏈
4張表:
-
filter:一般的過濾功能 -
nat:用于nat功能(端口映射,地址映射等) -
mangle:用于對特定數據包的修改 -
raw:有限級最高,設置raw時一般是為了不再讓iptables做數據包的鏈接跟蹤處理,提高性能
注:表的處理優(yōu)先級:raw > mangle > nat > filter
5條鏈:
-
PREROUTING:數據包進入路由表之前 -
INPUT:通過路由表后目的地為本機 -
FORWARDING:通過路由表后,目的地不為本機 -
OUTPUT:由本機產生,向外轉發(fā) -
POSTROUTIONG:發(fā)送到網卡接口之前。如下圖數據包的流向:

-w594
iptables 規(guī)則的組成部分:

-w500
場景練習
# 開放(80、22、10-21)端口的訪問,允許ICMP協(xié)議的數據包,禁止其它未被允許的端口。
iptables -F
iptables -I INPUT -i lo -j ACCEPT # 允許本機訪問本機
iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # 允許本機訪問外部網絡
iptables -I INPUT -p tcp --dport 80 -j ACCEPT
iptables -I INPUT -p tcp --dport 10:21 -j ACCEPT
iptables -I INPUT -p tcp --dport 22 -j ACCEPT
iptables -I INPUT -p icmp -j ACCEPT
iptables -A INPUT -j REJECT
# iptables -L INPUT --line-numbers # 列出INPUT 鏈所有的規(guī)則
# iptables -D INPUT 2 # 刪除第 2 行規(guī)則
# 只允許某臺或部分主機訪問80端口
iptables -D INPUT -p tcp --dport 80 -j ACCEPT # 清除本條規(guī)則
iptables -I INPUT -p tcp -s 10.10.1.123 --dport 80 -j ACCEPT
iptables -I INPUT -p tcp -s 10.10.1.0/24 --dport 80 -j ACCEPT
# 常見對外的端口服務:
網站 www
http 80/tcp
https 443/tcp
郵件 mail
smtp 25/tcp
smtps 465/tcp
pop3 110/tcp
pop3s 995/tcp
imap 143/tcp
# 常見不對外的端口服務:
文件服務
NFS 123/udp
SAMBA 137,138,139/tcp 445/tcp
FTP 20/tcp, 21/tcp
遠程管理
SSH 22/tcp
數據庫
MYSQL 3306/tcp
ORACLE 1521/tcp
iptables NAT模式設置
| 分類 | 功能 | 作用鏈 |
|---|---|---|
| SNAT | 源地址轉換 | 出口POSTROUTING |
| DNAT | 目標地址轉換 | 進口PREROUTING |
# vim /etc/sysctl.conf
net.ipv4.ip_forward = 1 # 打開端口轉發(fā)內核功能
# sysctl -p # 使配置生效
# sysctl -a | grep ip_forward # 查看配置是否生效
# snat配置
iptables -t nat -A POSTROUTING -s 10.10.177.0/24 -j SNAT --to 10.10.188.132
# dnat配置
iptables -t nat -A PREROUTING -d 10.10.188.123 -p tcp --dport 80 -j DNAT --to 10.10.177.123:8080
# 查看nat表的規(guī)則
iptables -t nat -L
iptables 防CC攻擊
## 防止 SYN 攻擊
iptables -I INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 100 -j REJECT
## 防止 DDOS 攻擊
# 并發(fā)請求限制
iptables -I INPUT -p tcp --dport 80 -s 10.10.10.1 -m connlimit --connlimit-above 10 -j REJECT
# limit模塊,限速控制異常流量
iptables -A INPUT -p icmp -m limit --limit 3/hour --limit-burst 10 -j ACCEPT
iptables -A INPUT -p icmp -j REJECT