Allow creation of tun / tap devices with the ability to nat random ports
authorSapan Bhatia <gwsapan@gmail.com>
Mon, 11 Oct 2010 21:51:24 +0000 (17:51 -0400)
committerSapan Bhatia <gwsapan@gmail.com>
Mon, 11 Oct 2010 21:51:24 +0000 (17:51 -0400)
exec/vif_up [changed mode: 0755->0644]
fd_tuntap.c

old mode 100755 (executable)
new mode 100644 (file)
index 2829b58..0f905c6
@@ -101,6 +101,7 @@ if vmask<mask:
 
 opt_txqueuelen = None
 opt_rp_filter = None
+opt_snat = None
 
 
 for optionline in options:
@@ -127,6 +128,10 @@ for optionline in options:
             sys.exit(1)
         opt_txqueuelen = intval
 
+    elif opt=="snat":
+       intval = int(val)
+       if val=="1":
+         opt_snat = True
     else:
         print >>sys.stderr, "Unknown option: \"%s\"" % (opt)
         sys.exit(1)
@@ -148,12 +153,24 @@ cmd_iptables_del_in = "/sbin/iptables -D INPUT -i %s -m mark -m state --state NE
 cmd_iptables_out = "/sbin/iptables -A OUTPUT -o %s -m state --state NEW -m mark ! --mark %d -j DROP" % (vif, sliceid)
 cmd_iptables_del_out = "/sbin/iptables -D OUTPUT -o %s -m state --state NEW -m mark ! --mark %d -j DROP 2>/dev/null" % (vif, sliceid)
 
+public_src = os.popen("ip route get 1.1.1.1 | head -1 | awk '{print $7;}'").read().rstrip();
+cmd_iptables_pr = "/sbin/iptables -t nat -A POSTROUTING -s %s/%d -j SNAT --to-source %s --random" % (vip, vmask, public_src)
+cmd_iptables_del_pr = "/sbin/iptables -t nat -D POSTROUTING -s %s/%d -j SNAT --to-source %s --random" % (vip, vmask, public_src)
+
 os.system(cmd_iptables_del_in)
 os.system(cmd_iptables_in)
 os.system(cmd_iptables_del_out)
 os.system(cmd_iptables_out)
 
+if (opt_snat):
+    os.system(cmd_iptables_del_pr)
+    os.system(cmd_iptables_pr)
+    #print cmd_iptables_del_pr
+    #print cmd_iptables_pr
+
 # Process additional options
 if opt_rp_filter is not None:
     rp_cmd = "/sbin/sysctl net.ipv4.conf.%s.rp_filter=%s" % (vif, opt_rp_filter)
     os.system(rp_cmd)
+
+
index 45e66be..ddcd431 100644 (file)
@@ -107,6 +107,7 @@ int main(int argc, char *argv[])
     /* Open tun device */
     if( (tap_fd = open("/dev/net/tun", O_RDWR)) < 0 ) {
         system("modprobe tun");
+        system("ln -sf /dev/net/tun /dev/stdtun");
         if( (tap_fd = open("/dev/net/tun", O_RDWR)) < 0 ) {
             perror("ERROR: tun_alloc():open(/dev/net/tun)");
             exit(-1);