Created
August 26, 2024 16:04
-
-
Save arbabnazar/237ce54f523731cba94a3462fb7a96f7 to your computer and use it in GitHub Desktop.
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 | |
# This script is written to make your EC2 Linux machine Router | |
# With this you can setup your linux machine as gateway. | |
#################################################################################### | |
####### Dont forget to disable source/destination checks on the NAT instance ####### | |
#################################################################################### | |
# Deleting all the iptables rules | |
iptables --flush | |
iptables --table nat --flush | |
iptables --delete-chain | |
iptables --table nat --delete-chain | |
# Defining interfaces for gateway. | |
INTERFACE=$(ip route get 8.8.8.8 | awk -- '{printf $5}') | |
VPC_CIDR="$(hostname -I | cut -d '.' -f1,2).0.0/16" | |
# Turning on IP Forwarding | |
echo "net.ipv4.ip_forward = 1" | sudo tee -a /etc/sysctl.conf | |
sudo sysctl -p | |
# Making a catchall rules for routing and masking the private IP | |
/usr/sbin/iptables -A INPUT -i $INTERFACE -m state --state ESTABLISHED,RELATED -j ACCEPT | |
/usr/sbin/iptables --table nat --append POSTROUTING --out-interface $INTERFACE --source "$VPC_CIDR" -j MASQUERADE | |
/usr/sbin/iptables -A OUTPUT -j ACCEPT | |
#Create Script to run on startup | |
cat > /etc/nat.sh <<EOL | |
#!/bin/bash | |
/usr/sbin/iptables -A INPUT -i $INTERFACE -m state --state ESTABLISHED,RELATED -j ACCEPT | |
/usr/sbin/iptables --table nat --append POSTROUTING --out-interface $INTERFACE --source "$VPC_CIDR" -j MASQUERADE | |
/usr/sbin/iptables -A OUTPUT -j ACCEPT | |
EOL | |
chmod +x /etc/nat.sh | |
# Create Startup service | |
touch /etc/systemd/system/nat.service | |
chmod 0664 /etc/systemd/system/nat.service | |
cat > /etc/systemd/system/nat.service <<EOF | |
[Unit] | |
After=network.target | |
[Service] | |
ExecStart=/etc/nat.sh | |
[Install] | |
WantedBy=default.target | |
EOF | |
systemctl daemon-reload | |
systemctl enable nat.service |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment