Skip to content

Instantly share code, notes, and snippets.

@gilangvperdana
Last active September 7, 2024 10:17
Show Gist options
  • Save gilangvperdana/cbcda28d11f186ebfe785dbfa19688c4 to your computer and use it in GitHub Desktop.
Save gilangvperdana/cbcda28d11f186ebfe785dbfa19688c4 to your computer and use it in GitHub Desktop.
Make your Ubuntu Server be Router!

Goals

  • Can use Ubuntu Server 20.04 LTS to be Router Gateway include DHCP Server
  • Client who connected to Ubuntu Server can be access Internet

Environement

  • Ubuntu 20.04 LTS
  • 2 Interface
    • 1 Interface from WAN / ISP (enp2s0)
    • 1 Interface for distribution clients (enx00e04c534458)

Set netplan

nano /etc/netplan/01-network-manager-all.yaml
network:
    ethernets:
        enp2s0:
            dhcp4: true
        enx00e04c534458:
            addresses:
            - 192.168.2.1/24
            dhcp4: false
            nameservers:
                addresses:
                - 8.8.8.8
                - 8.8.4.4
                search: []
    version: 2
sudo netplan generate
sudo netplan apply

Install DHCP Server

sudo apt-get install isc-dhcp-server
sudo nano /etc/default/isc-dhcp-server
## Declare Interface to User
INTERFACESv4="enx00e04c534458"

Configure pool for DHCP

option domain-name "home.local";
option domain-name-servers 8.8.8.8, 8.8.4.4;
default-lease-time 600;
max-lease-time 7200;
ddns-update-style none;
authoritative;
log-facility local7;
subnet 192.168.2.0 netmask 255.255.255.0 {
     range 192.168.2.101 192.168.2.200;
     option subnet-mask 255.255.255.0;
     option routers 192.168.2.1;
     option broadcast-address 192.168.2.255;
}
## Make service auto-restart
nano /lib/systemd/system/isc-dhcp-server.service

---
[Service]
Restart=on-failure
sudo systemctl restart isc-dhcp-server
sudo systemctl enable isc-dhcp-server
sudo systemctl status isc-dhcp-server

Create Auto Forwarding Script

nano /etc/rc.local
#!/bin/bash

# /etc/rc.local

# Default policy to drop all incoming packets.
#iptables -P INPUT DROP
#iptables -P FORWARD DROP

# Accept incoming packets from localhost and the LAN interface.
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -i enx00e04c534458 -j ACCEPT

# Accept incoming packets from the WAN if the router initiated the connection.
iptables -A INPUT -i enp2s0 -m conntrack \
--ctstate ESTABLISHED,RELATED -j ACCEPT

# Forward LAN packets to the WAN.
iptables -A FORWARD -i enx00e04c534458 -o enp2s0 -j ACCEPT

# Forward WAN packets to the LAN if the LAN initiated the connection.
iptables -A FORWARD -i enp2s0 -o enx00e04c534458 -m conntrack \
--ctstate ESTABLISHED,RELATED -j ACCEPT

# NAT traffic going out the WAN interface.
iptables -t nat -A POSTROUTING -o enp2s0 -j MASQUERADE

# rc.local needs to exit with 0
exit 0
sudo chmod +x /etc/rc.local
crontab -e
@reboot /bin/bash /etc/rc.local
reboot

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment