一、rp_filter參數介紹
rp_filter參數用於控制系統是否開啟對數據包源地址的校驗。
首先看一下Linux內核文檔documentation/networking/ip-sysctl.txt中的描述:
rp_filter - INTEGER
0 - No source validation.
1 - Strict mode as defined in RFC3704 Strict Reverse Path
Each incoming packet is tested against the FIB and if the interface
is not the best reverse path the packet check will fail.
By default failed packets are discarded.
2 - Loose mode as defined in RFC3704 Loose Reverse Path
Each incoming packet's source address is also tested against the FIB
and if the source address is not reachable via any interface
the packet check will fail.
0 - No source validation.
1 - Strict mode as defined in RFC3704 Strict Reverse Path
Each incoming packet is tested against the FIB and if the interface
is not the best reverse path the packet check will fail.
By default failed packets are discarded.
2 - Loose mode as defined in RFC3704 Loose Reverse Path
Each incoming packet's source address is also tested against the FIB
and if the source address is not reachable via any interface
the packet check will fail.
Current recommended practice in RFC3704 is to enable strict mode
to prevent IP spoofing from DDos attacks. If using asymmetric routing
or other complicated routing, then loose mode is recommended.
The max value from conf/{all,interface}/rp_filter is used
when doing source validation on the {interface}.
Default value is 0. Note that some distributions enable it in startup scripts.
即rp_filter參數有三個值,0、1、2,具體含義:
0:不開啟源地址校驗。
1:開啟嚴格的反向路徑校驗。對每個進來的數據包,校驗其反向路徑是否是最佳路徑。如果反向路徑不是最佳路徑,則直接丟棄該數據包。
2:開啟松散的反向路徑校驗。對每個進來的數據包,校驗其源地址是否可達,即反向路徑是否能通(通過任意網口),如果反向路徑不同,則直接丟棄該數據包。
二、rp_filter參數示例
假設機器有2個網口:
eth0: 192.168.1.100
eth1:200.153.1.122
數據包源IP:10.75.153.98,目的IP:200.153.1.122
系統路由表配置為:
[root@localhost ~]# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default 192.168.1.234 0.0.0.0 UG 0 0 0 eth0
192.168.120.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
10.75.153.98 0.0.0.0 255.255.255.0 U 0 0 0 eth0
系統rp_filter參數的配置為:
[root@localhost ~]# sysctl -a | grep rp_filter
net.ipv4.conf.all.rp_filter=1
net.ipv4.conf.default.rp_filter=1
如上所示,數據包發到了eth1網卡,如果這時候開啟了rp_filter參數,並配置為1,則系統會嚴格校驗數據包的反向路徑。從路由表中可以看出,返回響應時數據包要從eth0網卡出,即請求數據包進的網卡和響應數據包出的網卡不是同一個網卡,這時候系統會判斷該反向路徑不是最佳路徑,而直接丟棄該請求數據包。(業務進程也收不到該請求數據包)

解決辦法:
1.修改路由表,使響應數據包從eth1出,即保證請求數據包進的網卡和響應數據包出的網卡為同一個網卡。
2.關閉rp_filter參數。(注意all和default的參數都要改)
1)修改/etc/sysctl.conf文件,然后sysctl -p刷新到內存。
2)使用sysctl -w直接寫入內存:sysctl -w net.ipv4.conf.all.rp_filter=0
3)修改/proc文件系統: echo "0">/proc/sys/net/ipv4/conf/all/rp_filter
三、開啟rp_filter參數的作用
1. 減少DDoS攻擊
校驗數據包的反向路徑,如果反向路徑不合適,則直接丟棄數據包,避免過多的無效連接消耗系統資源。
2. 防止IP Spoofing
校驗數據包的反向路徑,如果客戶端偽造的源IP地址對應的反向路徑不在路由表中,或者反向路徑不是最佳路徑,則直接丟棄數據包,不會向偽造IP的客戶端回復響應。
Ps:兩種常見的非法攻擊手段:
1. DDos攻擊(Distribute Deny of Service)
分布式拒絕服務攻擊。通過構造大量的無用數據包向目標服務發起請求,占用目標服務主機大量的資源,還可能造成網絡擁塞,進而影響到正常用戶的訪問。
2. IP Spoofing(IP欺騙)
IP Spoofing指一個客戶端通過偽造源IP,冒充另外一個客戶端與目標服務進行通信,從而達到某些不可告人的秘密。