Only write /etc/hosts when necessary.

Without this patch, sshuttle 'restores' /etc/hosts even if it didn't
make any modifications to it. This can be confirmed by running without
--auto-hosts and confirming that the modification time of /etc/hosts
is unchanged while sshuttle is running, but is updated when sshuttle
exits (and a debug2() message is printed indicating the file is
written).

I'm not aware of the previous behavior causing problems. However,
writing an important file unnecessarily as root should be avoided.
This commit is contained in:
Scott Kuhl 2020-10-19 00:17:37 -04:00
parent 1dbf216369
commit e1106a33a9
2 changed files with 8 additions and 5 deletions

View File

@ -47,8 +47,11 @@ def rewrite_etc_hosts(hostmap, port):
os.rename(tmpname, HOSTSFILE)
def restore_etc_hosts(port):
rewrite_etc_hosts({}, port)
def restore_etc_hosts(hostmap, port):
# Only restore if we added hosts to /etc/hosts previously.
if len(hostmap) > 0:
debug2('firewall manager: undoing /etc/hosts changes.\n')
rewrite_etc_hosts({}, port)
# Isolate function that needs to be replaced for tests
@ -275,8 +278,8 @@ def main(method_name, syslog):
debug2('An error occurred, ignoring it.')
try:
debug2('firewall manager: undoing /etc/hosts changes.\n')
restore_etc_hosts(port_v6 or port_v4)
# debug2() message printed in restore_etc_hosts() function.
restore_etc_hosts(hostmap, port_v6 or port_v4)
except BaseException:
try:
debug1("firewall manager: "

View File

@ -55,7 +55,7 @@ def test_rewrite_etc_hosts(tmpdir):
assert line == ""
with patch('sshuttle.firewall.HOSTSFILE', new=str(new_hosts)):
sshuttle.firewall.restore_etc_hosts(10)
sshuttle.firewall.restore_etc_hosts(hostmap, 10)
assert orig_hosts.computehash() == new_hosts.computehash()