SHARE
TWEET

Untitled

a guest Apr 23rd, 2019 84 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/bash
  2.  
  3. # Rules for vm names matching "{vm-name}"
  4. if [ "${1}" = "{vm-name}" ]; then
  5.   # IP of the {vm-name} vm on the nat "network"
  6.   GUEST_IP="192.168.122.2"
  7.   # Addresses (ipv4 separated with spaces) that should be allowed access
  8.   SOURCES=""
  9.   # Ports (separated with spaces that should be forwarded 1:1 (port 443 forwards to port 443 etc.)
  10.   PORTS=""
  11.   # Name of the network interface (usually virbr#)
  12.   INTERFACE="virbr0"
  13.   COMMENT="added by libvirt hook"
  14.  
  15.   # When the machine is stopped or restarted
  16.   if [ "${2}" = "stopped" ] || [ "${2}" = "reconnect" ]; then
  17.     # Remove the rule for new traffic in the FORWARD chain
  18.     /sbin/iptables -D FORWARD -o $INTERFACE -d $GUEST_IP -m comment --comment "$COMMENT" -j ACCEPT
  19.  
  20.     # Remove rules for each source with each port
  21.     for SOURCE in $SOURCES; do
  22.       for PORT in $PORTS; do
  23.         /sbin/iptables -t nat -D PREROUTING -s $SOURCE -p tcp --dport $PORT -m comment --comment "$COMMENT" -j DNAT --to $GUEST_IP:$PORT
  24.       done
  25.     done
  26.   fi
  27.  
  28.   # When the machine is started
  29.   if [ "${2}" = "start" ] || [ "${2}" = "reconnect" ]; then
  30.     # Check if a RELATED,ESTABLISHED rule exists for the interface
  31.     iptables -vnL FORWARD --line-numbers |grep "RELATED,ESTABLISHED" |grep "${INTERFACE}" |awk -F ' ' '{print $1}' > /dev/null 2>&1
  32.  
  33.     # Set count variable to 1 (it will be used later explicitly as 1 if test condition fails otherwise I'd use 0)
  34.     LINE_NUMBER=1
  35.     # If the RELATED,ESTABLISHED rule exists for the interface, set the LINE_NUMBER to the line number of that line plus 1
  36.     if [ $? -eq 0 ]; then
  37.       LINE_NUMBER=$(($(iptables -vnL FORWARD --line-numbers |grep "RELATED,ESTABLISHED" |grep "${INTERFACE}" |awk -F ' ' '{print $1}') + 1))
  38.     fi
  39.  
  40.     # Create the appropriate forward rule on the correct line number
  41.     /sbin/iptables -I FORWARD $LINE_NUMBER -o $INTERFACE -d $GUEST_IP -m comment --comment "$COMMENT" -j ACCEPT
  42.  
  43.     # Create a rule to allow each source address on each 1:1 forwarded port
  44.     for SOURCE in $SOURCES; do
  45.       for PORT in $PORTS; do
  46.         /sbin/iptables -t nat -I PREROUTING -s $SOURCE -p tcp --dport $PORT -m comment --comment "$COMMENT" -j DNAT --to $GUEST_IP:$PORT
  47.       done
  48.     done
  49.   fi
  50. fi
  51.  
  52. exit 0
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top