From 77cf37e0fa668f774edb7f4b1891146ce78a0ae2 Mon Sep 17 00:00:00 2001 From: Avery Pennarun Date: Sun, 9 May 2010 11:22:05 -0400 Subject: [PATCH] firewall: preserve permissions on /etc/hosts Pointed out by nisc on github. If people use an unusual umask or have funny permissions on /etc/hosts, sshuttle would screw it up. We also use hardlinks to atomically backup the original /etc/hosts to /etc/hosts.sbak the first time, rather than manually copying it. Not sure why I didn't think of that before. --- firewall.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/firewall.py b/firewall.py index fd0c8c1..3444c7c 100644 --- a/firewall.py +++ b/firewall.py @@ -140,15 +140,17 @@ def rewrite_etc_hosts(port): BAKFILE='%s.sbak' % HOSTSFILE APPEND='# sshuttle-firewall-%d AUTOCREATED' % port old_content = '' + st = None try: old_content = open(HOSTSFILE).read() + st = os.stat(HOSTSFILE) except IOError, e: if e.errno == errno.ENOENT: pass else: raise if old_content.strip() and not os.path.exists(BAKFILE): - open(BAKFILE, 'w').write(old_content) + os.link(HOSTSFILE, BAKFILE) tmpname = "%s.%d.tmp" % (HOSTSFILE, port) f = open(tmpname, 'w') for line in old_content.rstrip().split('\n'): @@ -158,6 +160,13 @@ def rewrite_etc_hosts(port): for (name,ip) in sorted(hostmap.items()): f.write('%-30s %s\n' % ('%s %s' % (ip,name), APPEND)) f.close() + + if st: + os.chown(tmpname, st.st_uid, st.st_gid) + os.chmod(tmpname, st.st_mode) + else: + os.chown(tmpname, 0, 0) + os.chmod(tmpname, 0644) os.rename(tmpname, HOSTSFILE)