Created
August 7, 2023 23:42
-
-
Save luandro/3b0e86331b3f4a59aadc28e2ac3d04b0 to your computer and use it in GitHub Desktop.
This bash script is used to set up and tear down a simple internet gateway. It uses the ip, iptables, ufw, and dnsmasq utilities to configure network interfaces, set up NAT (Network Address Translation), configure a firewall, and set up a DHCP server.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Check if script is run as root | |
if [ "$EUID" -ne 0 ] | |
then echo "Please run as root" | |
exit | |
fi | |
# Check if required utilities are installed | |
for util in ip iptables ufw dnsmasq; do | |
if ! command -v $util &> /dev/null | |
then | |
echo "$util could not be found, please install it" | |
exit | |
fi | |
done | |
# Set network interfaces | |
ETH_INTERFACE="enp0s25" | |
WIFI_INTERFACE="wlp3s0" | |
ETH_IP_ADDRESS="192.168.0.1" | |
ETH_SUBNET_MASK="255.255.255.0" | |
DHCP_RANGE="192.168.0.100,192.168.0.200" | |
start_gateway() { | |
echo "Setting up internet sharing and DHCP server..." | |
# Configure Ethernet interface with a static IP address | |
ip addr add "$ETH_IP_ADDRESS/$ETH_SUBNET_MASK" dev "$ETH_INTERFACE" | |
ip link set dev "$ETH_INTERFACE" up | |
# Enable IP Forwarding | |
sysctl net.ipv4.ip_forward=1 | |
# Set up NAT using iptables | |
iptables -t nat -A POSTROUTING -o "$WIFI_INTERFACE" -j MASQUERADE | |
# Allow traffic through UFW | |
ufw allow in on "$ETH_INTERFACE" | |
ufw allow out on "$WIFI_INTERFACE" | |
ufw enable | |
# Configure DHCP server (dnsmasq) | |
echo "interface=$ETH_INTERFACE" | sudo tee /etc/dnsmasq.conf | |
echo "dhcp-range=$DHCP_RANGE,12h" | sudo tee -a /etc/dnsmasq.conf | |
sudo systemctl restart dnsmasq | |
echo "Internet sharing and DHCP server are now active." | |
} | |
stop_gateway() { | |
echo "Stopping internet sharing and DHCP server..." | |
# Disable IP Forwarding | |
sysctl net.ipv4.ip_forward=0 | |
# Remove NAT rule using iptables | |
iptables -t nat -D POSTROUTING -o "$WIFI_INTERFACE" -j MASQUERADE | |
# Remove UFW rules | |
ufw delete allow in on "$ETH_INTERFACE" | |
ufw delete allow out on "$WIFI_INTERFACE" | |
ufw disable | |
# Disable DHCP server (dnsmasq) | |
sudo systemctl stop dnsmasq | |
# Remove IP configuration from Ethernet interface | |
ip addr del "$ETH_IP_ADDRESS/$ETH_SUBNET_MASK" dev "$ETH_INTERFACE" | |
echo "Internet sharing and DHCP server have been stopped." | |
} | |
case "$1" in | |
start) | |
start_gateway | |
;; | |
stop) | |
stop_gateway | |
;; | |
*) | |
echo "Usage: $0 {start|stop}" | |
exit 1 | |
esac | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment