Last active 1705433123

Port forward wrapper for firewalld

Jarno Rankinen revised this gist 1650365210. Go to revision

1 file changed, 71 insertions

port_forward(file created)

@@ -0,0 +1,71 @@
1 + #!/bin/bash
2 +
3 + if [[ "$1" == "stop" ]]; then
4 + printf "Reloading firewall.. "
5 + firewall-cmd --reload
6 + exit $?
7 + fi
8 +
9 + function usage () {
10 + printf "\nUsage:
11 +
12 + $0 FROM_PORT TO_ADDR:TO_PORT [PROTO]
13 + $0 stop
14 +
15 + FROM_PORT External port on public zone
16 + TO_ADDR Destination address
17 + TO_PORT Destination port
18 + PROTO Protocol (tcp/udp, optional,
19 + defaults to tcp)
20 + stop Remove port forwarding
21 +
22 + Example:
23 +
24 + $0 8080 192.168.122.122:80
25 + - will forward connections coming to port 80 to
26 + a VM with address 192.168.122.122
27 + \n"
28 + exit 0
29 + }
30 +
31 + function forward () {
32 + echo "Creating port forward from port $FROM_PORT/$PROTO to $TO_ADDR:$TO_PORT."
33 +
34 + printf "Enabling masquerade... "
35 + firewall-cmd --add-masquerade
36 + printf "Adding port forward... "
37 + firewall-cmd --add-forward-port=port=${FROM_PORT}:proto=${PROTO}:toport=${TO_PORT}:toaddr=${TO_ADDR}
38 + # iptables -D LIBVIRT_FWI -o virbr0 -j REJECT --reject-with icmp-port-unreachable
39 + # iptables -D LIBVIRT_FWO -i virbr0 -j REJECT --reject-with icmp-port-unreachable
40 +
41 + echo "Done."
42 + exit 0
43 + }
44 +
45 +
46 +
47 + if [ "$#" -lt 2 ] || [ "$#" -gt 3 ]; then
48 + usage
49 + fi
50 +
51 + if [ "$UID" -ne 0 ]; then
52 + echo "Run as root."
53 + exit 1
54 + fi
55 +
56 + FROM_PORT=$1
57 + TO_ADDR=${2%:*}
58 + TO_PORT=${2##*:}
59 + PROTO=${3:-'tcp'}
60 +
61 + if [[ ! "$TO_ADDR" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
62 + printf "Resolved %s as " "$TO_ADDR"
63 + TO_ADDR=`dig +short "$TO_ADDR" | head -1`
64 + printf "%s\n" "$TO_ADDR"
65 + fi
66 +
67 + if [[ "$PROTO" != "tcp" ]] && [[ "$PROTO" != "udp" ]]; then
68 + usage
69 + fi
70 +
71 + forward
Newer Older