用Linux做路由器

今日完成了一个专线项目, 根据集团要求, 需要使用 NAT 的方式联通两个办公区之间的内部网络, 使得可以互相访问服务器资源, 并且保存3个月的 NAT 日志, 出问题可以快速定位到人.

由于我们办公区没有路由器设备, 于是采用 Linux 服务器做 iptables 转发来实现 NAT 功能, 并且 iptables 可以记录日志; 此项目设计的客户端和服务器不足百台, 不会有太高的并发访问, 一台中等配置的 Linux 服务器完全可以满足要求.

拓扑结构

拓扑

我负责的区域在左侧.

  • 办公区和总部通过一条 20M 的 MSTP 线路相连, 互联网段是172.17.176.48/29.
  • 在办公区10.250.0.0/16可以通过 SNAT 方式访问总部网络10.44.0.0/16, 源 IP 需要 NAT 为172.17.176.50/29
  • 在总部可以通过访问互联地址172.17.176.51/29访问办公区的数据库服务器10.250.8.241

基本配置

首先在我们10.250.0.0/16这个三层交换机上增加10.44.0.0/16的路由:

1
ip route-static 10.44.0.0 255.255.0.0 10.250.254.251

若要实现双向的 NAT, 还有一个必要条件是一台最小化安装的 Linux 服务器, 最少配置2个网卡, 在此场景下, 网卡配置为:

  • eth0作为内部网卡, IP 地址是10.250.254.251;
  • eth1作为互联网卡, IP 地址是172.17.176.50;
  • eth1对端的 IP 为172.17.176.49.

服务器的路由配置, 需要能够访问办公区正常的网络资源, 同时将10.44.0.0/16路由至互联网卡:

1
2
3
4
5
6
7
# netstat -nr
Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
172.17.176.48 0.0.0.0 255.255.255.248 U 0 0 0 eth1
10.250.254.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
10.44.0.0 172.17.176.49 255.255.0.0 UG 0 0 0 eth1
10.250.0.0 10.250.254.254 255.0.0.0 UG 0 0 0 eth0

开启Linux 内核的转发功能, 编辑/etc/sysctl.conf, 加入如下语句:

1
net.ipv4.ip_forward = 1

访问总部网络资源

此步骤涉及到 SNAT 的概念.

所谓 SNAT, 即将一段 IP 包的源地址改变, 由于总部的 ACL 策略中仅允许172.17.176.48/29网段访问, 所以我们访问总部时就必须将源地址 NAT 为上述网段.

iptables 的 nat tables 有3个内置的 chain, 分别是PREROUTING, POSTROUTINGOUTPUTchain

PREROUTING chain – Alters packets before routing. i.e Packet translation happens immediately after the packet comes to the system (and before routing). This helps to translate the destination ip address of the packets to something that matches the routing on the local server. This is used for DNAT (destination NAT).
POSTROUTING chain – Alters packets after routing. i.e Packet translation happens when the packets are leaving the system. This helps to translate the source ip address of the packets to something that might match the routing on the desintation server. This is used for SNAT (source NAT).
OUTPUT chain – NAT for locally generated packets on the firewall.

我们需要使用的是POSTROUTING chain.

1
# iptables -A POSTROUTING -s 10.250.0.0/16 -o eth1 -j SNAT --to-source 172.17.176.50

解释一下, 就是将来自10.250.0.0/16网段的包, 由 eth1 网口出去时的源 IP 变更为172.17.176.50; 我们之前已经将路由配置为访问10.44网段时都走 eth1, 所以此行解决了访问总部的问题.

如果查看, 可以看到此条目已经生效:

1
2
3
# iptables -L -t nat
target prot opt source destination
NAT all -- 10.250.0.0/16 0.0.0.0/0 to:172.17.176.50

检查生效后可以使用/etc/init.d/iptables save 将此条保存到/etc/sysconfig/iptables 中, 这样重启iptables 后也不会丢是配置.

总部访问办公区服务器

此步骤不仅涉及 SNAT, 还涉及到了 DNAT 的概念.

DNAT 即将一段 IP 包的目的地址改变. 此方式

Author

Archean Zhang

Posted on

2014-02-07

Updated on

2022-07-11

Licensed under

Comments