#!/bin/bash # script called from /etc/qemu-ifup to forward traffic from # a tap network interface to an existing interface. # # Usage: qemu_forward [-noflush] tap_ip broadcast netmask tap_interface eth_interface # # qemu_forward [-noflush] tap_ip broadcast netmask tap_interface # (find eth interface automatically) # # if -noflush is specified, existing iptables policies and rules # are kept (needed to run several qemu instances) NOFLUSH="" if [ "$1" = "-noflush" ]; then shift NOFLUSH=yes fi TAP_IP=$1 TAP_BROADCAST=$2 TAP_NETMASK=$3 shift shift shift # tap interface TAP_IF="$1" if ! ifconfig -a | grep -q "^$TAP_IF"; then echo "qemu_forward: Tap interface '$TAP_IF' doesn't exist, aborting." exit 1 fi # The network interface to forward traffic to IF="$2" if [ -z "$IF" ]; then # use default route's interface if possible IF=`route -n | grep '^0.0.0.0' | xargs echo | cut -d\ -f8` if [ -z "$IF" ]; then # otherwise get first configured interface IF=`ifconfig -s | tail +2 | grep -v '^lo\|^tun\|^tap\|^br0' | head -1 | cut -d\ -f1` fi fi if ! ifconfig -a | grep -q "^$IF"; then echo "qemu_forward: couldn't find ethernet interface, aborting." exit 1 fi echo ifconfig $TAP_IF $TAP_IP broadcast $TAP_BROADCAST netmask $TAP_NETMASK up if ! ifconfig $TAP_IF $TAP_IP broadcast $TAP_BROADCAST netmask $TAP_NETMASK up; then echo "qemu_forward: couldn't configure interface $TAP_IF, aborting." exit 1 fi IPTABLES=/sbin/iptables if [ -z "$NOFLUSH" ]; then # Flush tables : for f in filter nat mangle; do $IPTABLES -t $f -F $IPTABLES -t $f -X $IPTABLES -t $f -F done $IPTABLES -P INPUT ACCEPT $IPTABLES -P OUTPUT ACCEPT $IPTABLES -P FORWARD ACCEPT fi #$IPTABLES -A INPUT -i $TAP_IF -j ACCEPT #$IPTABLES -A OUTPUT -o $TAP_IF -j ACCEPT #$IPTABLES -A FORWARD -i $TAP_IF -j ACCEPT #$IPTABLES -A FORWARD -o $TAP_IF -j ACCEPT #$IPTABLES -A FORWARD -s 172.20.0.0/24 -i $TAP_IF -o eth0 -j ACCEPT $IPTABLES -t nat -A POSTROUTING -o eth0 -j MASQUERADE # enable forwarding if ! cat /etc/sysctl.conf | sed -e 's/#.*//' | grep -q 'net/ipv4/ip_forward=1'; then echo 'net/ipv4/ip_forward=1' >> /etc/sysctl.conf fi sysctl -p