#!/usr/bin/python2 # VSYS script to ifdown per-slice virtual network interfaces from the root slice # Thom Haddow - 06/10/09 # # Gets slice name as argv[1] # Takes remaining args on stdin: # - Interface name (eg [tun|tap]-) import sys import pwd import os import re import string if len(sys.argv) != 2: sys.exit(1) # VSYS scripts get slicename as $1 slicename=sys.argv[1] sliceid = pwd.getpwnam(slicename).pw_uid arglines = map(string.strip, sys.stdin.readlines()) if len(arglines)<1: print >>sys.stderr, "Insufficient argument lines." sys.exit(1) vif = arglines[0] # interface name # Create options list if len(arglines)>1: options = arglines[1:] else: options = [] opt_delete = False for optionline in options: if len(optionline)==0: continue try: opt, val = optionline.split('=') except: print >>sys.stderr, "Bad option line: \"%s\"" % (optionline) sys.exit(1) if opt=="delete": if val=="0": opt_delete=False elif val=="1": opt_delete=True else: print >>sys.stderr, "rp_filter value invalid: \"%s\"" % (val) sys.exit(1) else: print >>sys.stderr, "Unknown option: \"%s\"" % (opt) sys.exit(1) # Validate interface name if len(vif)>16: print >>sys.stderr, "Interface name %s invalid"%(vif) sys.exit(1) if re.match(r'(tun|tap)%d-\d+' % sliceid, vif ) is None: print >>sys.stderr, "Interface name %s does not match slice id %d."%(vif, sliceid) sys.exit(1) # Remove iptables rules public_src = os.popen("ifconfig | grep $(ip route | grep default | awk '{print $3}' | awk -F. '{print $1\"[.]\"$2}') | head -1 | awk '{print $2}' | awk -F : '{print $2}'").read().rstrip() cmd_iptables_del_in = "/sbin/iptables -D INPUT -i %s -m mark -m state --state NEW ! --mark %d -j DROP 2>/dev/null" % (vif, sliceid) cmd_iptables_del_out = "/sbin/iptables -D OUTPUT -o %s -m mark -m state --state NEW ! --mark %d -j DROP 2>/dev/null" % (vif, sliceid) cmd_iptables_del_pr = "/sbin/iptables -t nat -D POSTROUTING -s $(ip ro | grep 'dev %s' | head -1 | awk '{print $1}') -j SNAT --to-source %s --random 2>/dev/null" % (vif, public_src,) cmd_gre_del = "ip link del %s 2>/dev/null" % (vif,) cmd_iptables_del_gre_pr = "/sbin/iptables -t mangle -D INPUT -i %s -m mark --mark 0 -j MARK --set-mark %s 2>/dev/null" % (vif, sliceid) os.system(cmd_iptables_del_in) os.system(cmd_iptables_del_out) os.system(cmd_iptables_del_pr) os.system(cmd_iptables_del_gre_pr) # Bring interface down cmd_ifconfig = "/sbin/ifconfig %s down" % (vif) os.system(cmd_ifconfig) # Delete GRE tunnel (if any) if (opt_delete): os.system(cmd_gre_del)