2008年9月4日 星期四

How to Set port forwarding

Network topology
1.PC1: NAT+DHCP server(eth0 for public IP and eth1 for DHCP server)
  eth0 IP: 61.220.51.26
     submask: 255.255.255.0
     gateway: 61.220.51.254
  eth1 IP: 192.168.4.254
     submask: 255.255.255.0
2.PC2: Client1
  WindowsXP,static DHCP(192.168.4.199)
  With port 80 enabled
3.PC3: Client2
  WindowsXP,dynamic DHCP(192.168.4.198)
  With port 8080 enabled

PC2 and PC3 can access internet though PC1

Target
1. disable PC1's SSH port(22)
2. mapping port 80 to PC2
3. mapping port 8080 to PC3

Instructions
1.Modify files already set for iptables(iptables.rules)
#!/bin/sh
##### iptables.rule #####
EIF="eth0" # 對外的網路介面
IIF="eth1" # 對內的網路介面
INNET="192.168.4.0/24" # 內部子網域

# forwarding
# 讓內部網路的封包可以轉送到外部
echo "1" > /proc/sys/net/ipv4/ip_forward

# flush all rules
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X

# 定義 policy
# Policy指的是當進來的封包不屬於rule中的任何一條時,所預設的動作。
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT

# localhost
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# 讓主機主動建立的連線可以進來
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

# 設定主機上提供的服務可讓外部網路存取
iptables -A INPUT -i $EIF -p tcp --dport 22 -j DROP # ssh
iptables -A INPUT -i $EIF -p udp --dport 22 -j ACCEPT
iptables -A INPUT -i $EIF -p tcp --dport 80 -j ACCEPT # http
iptables -A INPUT -i $EIF -p icmp -j ACCEPT #ICMP(ping,...)
# ... 其餘省略

# NAT
iptables -t nat -A POSTROUTING -o $EIF -s $INNET -j MASQUERADE
iptables -t nat -A PREROUTING -p tcp -i $EIF --dport 80 -j DNAT --to 192.168.4.199:80
iptables -t nat -A PREROUTING -p tcp -i $EIF --dport 8080 -j DNAT --to 192.168.4.198:8080

2.reload to let it work
./iptables.rules

Reference:vbird

沒有留言: