配置Linux 內(nèi)核并利用iptables 做端口映射
配置Linux 內(nèi)核并利用iptables 做端口映射的具體工作如下:
主機 IP:192.168.1.100
目標(biāo)機 IP:192.168.2.101
要求將到主機 192.168.1.100:11101 的請求映射到內(nèi)部網(wǎng)目標(biāo)機的 sshd 服務(wù)端口上,即:192.168.2.101:22。
配置Linux內(nèi)核(以 2.6.18 為例)
如果執(zhí)行 iptable -L 出現(xiàn)以下信息,那么就需要重新配置和編譯內(nèi)核:
iptables v1.4.2: can't initialize iptables table `filter': Table does not exist (do you need to insmod?)
Perhaps iptables or your kernel needs to be upgraded.
配置選項:
Networking —->
Networking options —->
[*] Network packet filtering (replaces ipchains) —>
Core Netfilter Configuration —>
<*> Netfilter Xtables support (required for ip_tables)
IP: Netfilter Configuration —>
<*> Connection tracking (required for masq/NAT)
<*> IP tables support (required for filtering/masq/NAT)
<*> IP range match support
<*> Packet filtering
<*> REJECT target support
<*> Full NAT
以上配置只為端口映射準(zhǔn)備,如果需要其它功能,請根據(jù)需要增加相關(guān)的配置。
編譯安裝內(nèi)核步驟略過。
iptabes
iptables 規(guī)則如下:
iptables -t nat -A PREROUTING -p tcp –dport 11101 -d 192.168.1.100 -j DNAT –to-destination 192.168.2.101:22
#p#
查看 iptables 規(guī)則定義:
# iptables -t nat -L
Chain PREROUTING (policy ACCEPT)
target prot opt source destination
DNAT tcp – anywhere 192.168.1.100 tcp dpt:11101 to:192.168.2.101:22
Chain POSTROUTING (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
ip_forward
除此之外,需要在主機上打開 ip 轉(zhuǎn)發(fā)以保持連接通道。
查看是否已打開 ip 轉(zhuǎn)發(fā)(1 表示打開):
cat /proc/sys/net/ipv4/ip_forward
如果未打開,則用以下命令打開:
echo 1 > /proc/sys/net/ipv4/ip_forward
保存設(shè)置
以上 iptables 設(shè)置和 ip 轉(zhuǎn)發(fā)設(shè)置在重啟系統(tǒng)之后就會消失,因此如果有需要,請將設(shè)置保存。
保存 iptables 設(shè)置:
/etc/init.d/iptables save
設(shè)置系統(tǒng)啟動時自動加載 iptables 設(shè)置(以 gentoo 為例):
rc-update add iptables default
保存 ip_forward 設(shè)置(在 /etc/sysctl.conf 中設(shè)置):
net.ipv4.ip_forward = 1
安全隱患
在打開了 ip_forward 后,一般要同時打開 rp_filter (Reverse Path filter),對數(shù)據(jù)包的源地址進(jìn)行檢查。
如果在沒有打開這個設(shè)置,就很容易受到來自內(nèi)部網(wǎng)的 IP 欺騙。
打開 rp_filter:
for f in /proc/sys/net/ipv4/conf/*/rp_filter ; do echo 1 > $f ; done
保存設(shè)置(在 /etc/sysctl.conf 中設(shè)置):
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.rp_filter = 1
測試
ssh root@192.168.1.100 -p 11101
看看是不是能夠連接到 192.168.2.101 主機上了?
通過上文的描述,我們清楚的知道了配置Linux內(nèi)核和利用iptables 做端口映射的具體過程,希望對大家有幫助!
【編輯推薦】