NA-HW1 Ubuntu Router NAT 設定

NA-hw1 Ubuntu Router

Create two virtual machine

router

os: ubuntu: 20.04
username: router
passwd: 000000

interfaces:

  1. enp0s3: NAT
  2. enp0s8: Intranet
  3. enp0s9: Host-Only(only for ssh)

agent

os: alpine
username: agent

interfaces:

  1. Intranet with MAC address 08:00:27:57:81:FE

client1

os: ubuntu: 20.04
username: client
passwd: 000000

interfaces:

  1. enp0s3: NAT
  2. enp0s9: Host-Only(only for ssh)

client2

os: ubuntu: 20.04
username: client
passwd: 000000

interfaces:

  1. enp0s3: NAT
  2. enp0s8: Intranet
  3. enp0s9: Host-Only(only for ssh)

Configure

netplan conf

configuration(/etc/netplan/XXX.conf):

1
2
3
4
5
6
7
8
enp0s3:
dhcp4: true
enp0s8
dhcp4: false
addresses: [10.113.40.254/24]
enp0s9
dhcp4: false
addresses: [192.168.56.2/24]

apply:

1
$ netplan apply

DHCP

Install: sudo apt install isc-dhcp-server
Configuration:

  1. /etc/default/isc-dhcp-server
1
2
INTERFACESv4="enp0s8"
INTERFACESv6="enp0s8"
  1. /etc/dhcp/dhcpd.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
option domain-name "stu40.hw1.nasa";
option domain-name-servers 8.8.8.8;
max-lease-time 7200;
default-lease-time 600;
authoritative;

subnet 10.113.40.0 netmask 255.255.255.0 {
option routers 10.113.40.254;
option subnet-mask 255.255.255.0;
option domain-search "stu40.hw1.nasa";
option domain-name-servers 8.8.8.8;
range 10.113.40.111 10.113.40.122;
range 10.113.40.124 10.113.40.222;
}

host agent{
hardware ethernet 08:00:27:57:81:FE;
fixed-address 10.113.40.123;
}

Enable:sudo systemctl enable isc-dhcp-server
Start:sudo systemctl start isc-dhcp-server
Status:sudo systemctl status isc-dhcp-server

Test: 啟用 agent 看他是否正確拿到 10.113.40.123 這個 IP。啟用 client2 看他是否正確拿到 10.113.40.111 ~ 10.113.40.222 的IP。

NAT

哪怕 agent 拿到 IP,他依舊無法 access WAN,因為一些 NAT 的設定沒做,使得封包出不去、進不來。

設置 /etc/sysctl.conf

確定 net.ipv4.ip_forward=1 沒有被註解。

APPLY: sudo sysctl -p

設置 iptables

1
2
3
4
5
6
EXTIF="enp0s3"
INTIF="enp0s8"

iptables -t nat -A POSTROUTING -o $EXTIF -j MASQUERADE
iptables -A FORWARD -i $EXTIF -o $INTIF -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i $INTIF -o $EXTIF -j ACCEPT

測試:開啟 client2 在用 ifconfig 確認拿到 ip 後,嘗試 ping 8.8.8.8。
註:iptable 的規則並不會自動儲存,會在重啟之後消失,可以進行存檔或是用 iptable persistent 的套件,參考

Debug 資料

  1. 在做一些設定的時候突然無法做 DNS resolve,然後設定 /etc/resolv.conf 也一直被覆寫。
    https://www.tecmint.com/set-permanent-dns-nameservers-in-ubuntu-debian/

  2. 改 hostname 後無法 sudo,或是 sudo 噴錯
    https://blog.longwin.com.tw/2008/11/linux-sudo-unable-to-resolve-host-2008/

  3. DHCP_ERROR: dhcpd: Abandoning IP address: pinged before offer
    https://marc.info/?l=dhcp-server&m=99904900204718&w=2