您的位置:首页 > 其它

使用iptables防火墙实现简单的IP过滤、SNAT及DNAT

2014-04-04 18:22 615 查看
目标:让内网下(192.168.100.0/24)的机器利用firewall的eth0作PAT上外网,但同时要让192.168.100.2使用10.1.2.62向外发布22/tcp端口,以实现在公网下可以直接利用一个公网IP远程连接到内部SERVER。

拓扑如下:





脚本如下:
#!/bin/bash

inside="eth1"
outside="eth0"
lan="192.168.100.0/24"

#######################################################################

iptables -F
iptables -X
iptables -Z

iptables -t filter-P INPUT DROP
iptables -t filter-P OUTPUT ACCEPT
iptables -t filter-P FORWARD ACCEPT

iptables -t nat -F
iptables -t nat -X
iptables -t nat -Z

iptables -t nat -PPREROUTING ACCEPT
iptables -t nat -PPOSTROUTING ACCEPT
iptables -t nat -POUTPUT ACCEPT

#######################################################################

iptables -t filter-A INPUT -i $outside -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -t filter-A INPUT -i lo -j ACCEPT
iptables -t filter-A INPUT -p icmp -j ACCEPT
iptables -t filter-A INPUT -i $outside -p tcp --dport 22 -j ACCEPT

iptables -t nat -APOSTROUTING -s $lan -o $outside -j MASQUERADE

iptables -t nat -APREROUTING -d 10.1.2.62 -p tcp --dport 22 -j DNAT --to-destination192.168.100.2:22

#######################################################################

/etc/init.d/iptablessave

重点在于做DNAT时需要在firewall的eth0上再绑定一个IP(10.1.2.62/24),如果不绑会找不到10.1.2.62,这点和硬件firewall有点不同。

为了能让firewall的IP Alias能够开机自动生效,需要编辑一个子接口的配置文件。如下:
[root@C1 ~]# vi/etc/sysconfig/network-scripts/ifcfg-eth0:0
DEVICE=eth0:0
ONBOOT=yes
BOOTPROTO=none
IPADDR=10.1.2.62
NETMASK=255.255.255.0

[root@C1 ~]#ifconfig
eth0 Link encap:Ethernet HWaddr 08:00:27:18:22:89
inet addr:10.1.2.61 Bcast:10.1.2.255 Mask:255.255.255.0
inet6 addr:fe80::a00:27ff:fe18:2289/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1593 errors:0 dropped:0overruns:0 frame:0
TX packets:200 errors:0 dropped:0overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:197481 (192.8 KiB) TX bytes:29835 (29.1 KiB)
eth0:0 Link encap:Ethernet HWaddr 08:00:27:18:22:89
inet addr:10.1.2.62 Bcast:10.1.2.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
eth1 Link encap:Ethernet HWaddr 08:00:27:2B:BE:33
inet addr:192.168.100.254 Bcast:192.168.100.255 Mask:255.255.255.0
inet6 addr:fe80::a00:27ff:fe2b:be33/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:62 errors:0 dropped:0overruns:0 frame:0
TX packets:111 errors:0 dropped:0overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:7197 (7.0 KiB) TX bytes:12100 (11.8 KiB)

[root@C2 ~]# route-n
Kernel IP routingtable
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.100.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
169.254.0.0 0.0.0.0 255.255.0.0 U 1002 0 0 eth0
0.0.0.0 192.168.100.254 0.0.0.0 UG 0 0 0 eth0

同时要打开firewall的数据包转发功能:
[root@C1 ~]# cat/etc/sysctl.conf | grep forward
# Controls IPpacket forwarding
net.ipv4.ip_forward= 1
[root@C1 ~]#
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息