Linux配置軟路由

寻找繁星發表於2024-09-03

假設出口網口是end0,入口網口是end1

outdev=end0
indev=end1
# 子網不要與其他interface的IP重合
prefix=10.233.233

配置出口網口IP

#nmcli dev set $indev managed no
ip link set up dev $indev
ip addr add $prefix.1/24 dev $indev

配置DHCP

apt install isc-dhcp-server
cp /etc/dhcp/dhcpd.conf /etc/dhcp/dhcpd.conf.$(date +%s%N)

cat > /etc/dhcp/dhcpd.conf <<EOF
option domain-name-servers 223.6.6.6;
option subnet-mask 255.255.255.0;
option routers $prefix.1;
subnet $prefix.0 netmask 255.255.255.0 {
  range $prefix.2 $prefix.254;
}

default-lease-time 600;
max-lease-time 7200;
EOF

systemctl restart isc-dhcp-server

223.6.6.6是阿里的DNS server。其他DNS server: https://www.zhihu.com/question/32229915/answer/3572478879

參考:https://wiki.archlinux.org/title/Dhcpd

開啟轉發

# 檢視是否開啟了轉發
sysctl net.ipv4.ip_forward
# 開啟轉發
sysctl -w net.ipv4.ip_forward=1

配置NAT

iptables -t nat -A POSTROUTING -s $prefix.0/24 -o $outdev -j MASQUERADE

讓防火牆不要攔截從indev到outdev的流量:

iptables -t filter -A FORWARD -i $indev -o $outdev -j ACCEPT

IPv6 NAT

一般認為IPv6是不需要NAT的。但是在類似校園網的環境,每個接入的IPv6地址都需要進行認證,這時候就可以用IPv6 NAT,只需要一個透過認證的IP就可以代理整個子網的流量。

# 子網字首
prefix6=fd00:1
# 生成link local address,這樣鏈路才能工作
sysctl -w net.ipv6.conf.$indev.addr_gen_mode=0

# 設定靜態IP
ip -6 addr add $prefix6::1/64 dev $indev

# 開啟IPv6轉發
sysctl -w net.ipv6.conf.all.forwarding=1
# 接受router advertisements
sysctl -w net.ipv6.conf.$indev.accept_ra=2

ip6tables -t nat -A POSTROUTING -o $outdev -j MASQUERADE
ip6tables -t filter -A FORWARD -i $indev -o $outdev -j ACCEPT

相關文章