-
Notifications
You must be signed in to change notification settings - Fork 3
/
hooks
executable file
·49 lines (46 loc) · 2.57 KB
/
hooks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/bin/bash
RULES_JSON=/etc/libvirt/hooks/hooks.json
IFACE_WAN=$(jq -cre '."iface-WAN"' ${RULES_JSON})
EXTIP=$(jq -cre '."ip-WAN"' ${RULES_JSON})
INT_NET=$(jq -cre '."net-LAN"' ${RULES_JSON})
rules=$(jq -ce '."forward-rules"[] | select(."vm-name"=="'${1}'")' ${RULES_JSON})
if [ $? -eq 0 ]; then
GUEST_IP=$(echo "${rules}" | jq -r '.ip')
GUEST_EXTIP=$(echo "${rules}" | jq -r '.extip')
# If 'extip' is set route **all** traffic for this external ip to the specified internal ip.
if [ "$GUEST_EXTIP" != "" ]; then
if [ "${2}" = "stopped" ] || [ "${2}" = "reconnect" ]; then
/sbin/iptables -D FORWARD -o virbr0 -p tcp -d ${GUEST_IP} -j ACCEPT
/sbin/iptables -t nat -D PREROUTING -p tcp -d ${GUEST_EXTIP} -j DNAT --to ${GUEST_IP}
fi
if [ "${2}" = "start" ] || [ "${2}" = "reconnect" ]; then
/sbin/iptables -I FORWARD 1 -o virbr0 -p tcp -d ${GUEST_IP} -j ACCEPT
/sbin/iptables -t nat -I PREROUTING 1 -p tcp -d ${GUEST_EXTIP} -j DNAT --to ${GUEST_IP}
fi
fi
for mapping in $(echo "${rules}" | jq -c '."port-mappings"[]'); do
GUEST_PORT=$(echo "${mapping}" | jq -r '."destination-port"')
HOST_PORT=$(echo "${mapping}" | jq -r '."source-port"')
PROTOCOL=$(echo "${mapping}" | jq -r '."protocol"' | sed -e 's/null/tcp/')
if [ "${2}" = "stopped" ] || [ "${2}" = "reconnect" ]; then
if [ "${GUEST_PORT}x" != "nullx" ]; then
/sbin/iptables -D FORWARD -o virbr0 -d ${GUEST_IP} -p ${PROTOCOL} --dport ${GUEST_PORT} -j ACCEPT
/sbin/iptables -t nat -D PREROUTING -p ${PROTOCOL} -d ${EXTIP} --dport ${HOST_PORT} -j DNAT --to ${GUEST_IP}:${GUEST_PORT}
else
/sbin/iptables -D FORWARD -o virbr0 -d ${GUEST_IP} -p ${PROTOCOL} --dport ${HOST_PORT} -j ACCEPT
/sbin/iptables -t nat -D PREROUTING -p ${PROTOCOL} -d ${EXTIP} --dport ${HOST_PORT} -j DNAT --to ${GUEST_IP}
/sbin/iptables -t nat -D POSTROUTING -s ${INT_NET} -d ${GUEST_IP} -p ${PROTOCOL} --dport ${HOST_PORT} -j MASQUERADE
fi
fi
if [ "${2}" = "start" ] || [ "${2}" = "reconnect" ]; then
if [ "${GUEST_PORT}x" != "nullx" ]; then
/sbin/iptables -I FORWARD -o virbr0 -d ${GUEST_IP} -p ${PROTOCOL} --dport ${GUEST_PORT} -j ACCEPT
/sbin/iptables -t nat -I PREROUTING -p ${PROTOCOL} -d ${EXTIP} --dport ${HOST_PORT} -j DNAT --to ${GUEST_IP}:${GUEST_PORT}
else
/sbin/iptables -I FORWARD -o virbr0 -d ${GUEST_IP} -p ${PROTOCOL} --dport ${HOST_PORT} -j ACCEPT
/sbin/iptables -t nat -I PREROUTING -p ${PROTOCOL} -d ${EXTIP} --dport ${HOST_PORT} -j DNAT --to ${GUEST_IP}
/sbin/iptables -t nat -I POSTROUTING -s ${INT_NET} -d ${GUEST_IP} -p ${PROTOCOL} --dport ${HOST_PORT} -j MASQUERADE
fi
fi
done
fi