Skip to content

Instantly share code, notes, and snippets.

@johnlettman
Created February 8, 2017 20:20
Show Gist options
  • Save johnlettman/63e1187d4ddb7f0b75a8189d7e80dfda to your computer and use it in GitHub Desktop.
Save johnlettman/63e1187d4ddb7f0b75a8189d7e80dfda to your computer and use it in GitHub Desktop.
Quick GNU/Linux Masquerade Script
#!/bin/bash
###########################################
# Quick GNU/Linux Masquerade Script #
# John Lettman <jlettman@openmailbox.org> #
###########################################
# Help text
read -d '' HELP <<- EOF
Usage: quick-masq [-h/--help | [IN_PORT] [OUT_PORT]]
Quickly initialize network masquerading (network gateway) via iptables and procfs.
Report bugs to: John Lettman <jlettman@openmailbox.org>
Source:
EOF
IN_PORT=$1
OUT_PORT=$2
# Detect help condition
if [ $# -lt 2 -o "$1" == "-h" -o "$1" == "--help" ]; then
echo "$HELP" # Print usage and help information if help condition is met
exit
fi
# Check if running as root
if [ "$EUID" -ne 0 ]; then
echo "Please run as root."
exit -1
fi
echo "Masquerading packets: [$IN_PORT] -> [$OUT_PORT]."
# Flush old entries from iptables (DESTRUCTIVE!)
iptables --flush
iptables --table nat --flush
iptables --delete-chain
iptables --table nat --delete-chain
# Add NAT and FORWARD table entries to enable masquerade per user configuration
iptables --table nat --append POSTROUTING --out-interface $OUT_PORT -j MASQUERADE
iptables --append FORWARD --in-interface $IN_PORT -j ACCEPT
# Enable kernel IPv4 packet forwarding functionality through procfs
echo 1 > /proc/sys/net/ipv4/ip_forward
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment