2 # VSYS script to configure per-slice virtual network interfaces from the root slice
3 # Thom Haddow - 06/10/09
5 # Gets slice name as argv[1]
6 # Takes remaining args on stdin:
7 # - Interface name (eg [tun|tap]<sliceid>-<n>)
8 # - IP address (eg 1.2.3.4)
9 # - Netmask (as int, e.g. 24)
18 netblock_config="vnetblocks.conf"
20 if len(sys.argv) != 2: sys.exit(1)
22 # VSYS scripts get slicename as $1
24 sliceid = pwd.getpwnam(slicename).pw_uid
26 # Read netblock allocation file
29 for line in open(netblock_config,'r'):
30 if line.startswith('#'): continue # skip comments
31 slice, netblock = line.split()
32 if slice == slicename: # found slice's alloc
33 base, mask = netblock.split('/')
37 print >>sys.stderr, "Could not find entry for slice %s in netblock config file %s" % (slicename, netblock_config)
41 ### Read args from stdin
42 vif = sys.stdin.readline().strip() # interface name
43 vip = sys.stdin.readline().strip() # IP
44 vmask = int(sys.stdin.readline().strip()) # netmask as int
46 # TODO further config args? txqueue, nat? Can add these later...
50 # Convert network base addr to int format by unpacking as 32bit net-ordered long (!L)
51 base_int = struct.unpack('!L',socket.inet_aton(base))[0]
56 # Validate interface name
58 print >>sys.stderr, "Interface name %s invalid"%(vif)
61 if re.match(r'(tun|tap)%d-\d+' % sliceid, vif ) is None:
62 print >>sys.stderr, "Interface name %s does not match slice id %d."%(vif, sliceid)
67 # Validate requested IP and convert to int format.
69 vip_int = struct.unpack('!L',socket.inet_aton(vip))[0]
71 print >>sys.stderr, "Invalid IP: %s" % vip
74 # Check IP is in netblock
75 if (vip_int>>(32-mask)) != (base_int>>(32-mask)):
76 print >>sys.stderr, "Requested IP %s not in netblock %s/%d" % (vip,base,mask)
79 # TODO. Check IP is not in use?
81 # Validate mask: Check requested mask is sane and within our netblock
82 if vmask>32 or vmask <8:
83 print >>sys.stderr, "Requested netmask /%d is invalid" %(vmask)
87 print >>sys.stderr, "Requested netmask /%d larger than allocation /%d" %(vmask, mask)
92 ### Configure interface
94 cmd_ifconfig = "/sbin/ifconfig %s %s/%d" % (vif, vip, vmask)
95 os.system(cmd_ifconfig)
97 # Add iptables rules (Clearing old ones first, if they exist)
98 cmd_iptables_in = "/sbin/iptables -A INPUT -i %s -m mark ! --mark %d -j DROP" % (vif, sliceid)
99 cmd_iptables_del_in = "/sbin/iptables -D INPUT -i %s -m mark ! --mark %d -j DROP 2>/dev/null" % (vif, sliceid)
100 cmd_iptables_out = "/sbin/iptables -A OUTPUT -o %s -m mark ! --mark %d -j DROP" % (vif, sliceid)
101 cmd_iptables_del_out = "/sbin/iptables -D OUTPUT -o %s -m mark ! --mark %d -j DROP 2>/dev/null" % (vif, sliceid)
103 os.system(cmd_iptables_del_in)
104 os.system(cmd_iptables_in)
105 os.system(cmd_iptables_del_out)
106 os.system(cmd_iptables_out)