#!/bin/bash

### Wrapper to create anti spoof rules for selected interface
# v0.0.1 2012 Sergio Kviato sergey.kviato@onapp.com
#

### Setup ###
OVSVSCTL=$(whereis -b ovs-vsctl | awk '{print $2}')
OVSOFCTL=$(whereis -b ovs-ofctl | awk '{print $2}')
RUNPATH="/var/run/openvswitch"
OVSVSCTL="$OVSVSCTL --db=unix:$RUNPATH/db.sock"
INTERFACE=""
IP=""
MAC=""
CLEAR=0
DL_TYPE="0x0800"

### The Code ###
# Check if there any arguments
if [ -z $1 ]
then
	echo "There no arguments"
	exit 1
fi

# Process command line arguments
# --add/del action to do, add or remove rule
# --int interface name
# -4 for IPv4 (default)
# -6 for IPv6
# --clear clear all ruls for dedicated interface
# --ip-address IP address binded to VM interface
# --mac-address MAC address binded to VM interface

for arg in {1..20}                                                                                                           
do                                                                                                                           
    case "${!arg}" in
	"--del")
	COMMAND="del-flows"
	ACTION=""
	;;
	"--add")
	COMMAND="add-flow"
	ACTION="action=normal"
	;;
	"--clear")
	COMMAND="del-flows"
	CLEAR=1
	;;
	"--int")
        ((argn=arg+1))
        INTERFACE=${!argn}
	;;
	"--ip-address")
	((argn=arg+1))
	IP=${!argn}
	;;
	"--mac-address")
	((argn=arg+1))
	MAC=${!argn}
	;;
	"-6")
	DL_TYPE="0x86dd"
	;;
    esac
done

# Find switch by interface name
SWITCH=$($OVSVSCTL port-to-br $INTERFACE)
# Find a port number
PORT=$($OVSVSCTL -- get Interface $INTERFACE ofport)

if [ $CLEAR -eq 1 ]; then
    $OVSOFCTL $COMMAND $SWITCH "in_port=$PORT"
    exit 0
fi

# Add ability to answer only using correct MAC and IP address
# Only Port which we defined can ansver on this request
# On interface that belongs to VM
$OVSOFCTL $COMMAND $SWITCH "in_port=$PORT dl_type=0x0806 nw_proto=2 arp_sha=$MAC nw_src=$IP $ACTION"
$OVSOFCTL $COMMAND $SWITCH "in_port=$PORT dl_type=$DL_TYPE dl_src=$MAC priority=1 nw_src=$IP $ACTION"

exit 0
