Permalink
Browse files

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.
  • Loading branch information...
1 parent 384d0e7 commit 77cf37e0fa668f774edb7f4b1891146ce78a0ae2 @apenwarr apenwarr committed May 9, 2010
Showing with 10 additions and 1 deletion.
  1. +10 −1 firewall.py
View
@@ -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)

0 comments on commit 77cf37e

Please sign in to comment.