Skip to content

Commit e1106a3

Browse files
committed
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.
1 parent 1dbf216 commit e1106a3

File tree

2 files changed

+8
-5
lines changed

2 files changed

+8
-5
lines changed

sshuttle/firewall.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,11 @@ def rewrite_etc_hosts(hostmap, port):
4747
os.rename(tmpname, HOSTSFILE)
4848

4949

50-
def restore_etc_hosts(port):
51-
rewrite_etc_hosts({}, port)
50+
def restore_etc_hosts(hostmap, port):
51+
# Only restore if we added hosts to /etc/hosts previously.
52+
if len(hostmap) > 0:
53+
debug2('firewall manager: undoing /etc/hosts changes.\n')
54+
rewrite_etc_hosts({}, port)
5255

5356

5457
# Isolate function that needs to be replaced for tests
@@ -275,8 +278,8 @@ def main(method_name, syslog):
275278
debug2('An error occurred, ignoring it.')
276279

277280
try:
278-
debug2('firewall manager: undoing /etc/hosts changes.\n')
279-
restore_etc_hosts(port_v6 or port_v4)
281+
# debug2() message printed in restore_etc_hosts() function.
282+
restore_etc_hosts(hostmap, port_v6 or port_v4)
280283
except BaseException:
281284
try:
282285
debug1("firewall manager: "

tests/client/test_firewall.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def test_rewrite_etc_hosts(tmpdir):
5555
assert line == ""
5656

5757
with patch('sshuttle.firewall.HOSTSFILE', new=str(new_hosts)):
58-
sshuttle.firewall.restore_etc_hosts(10)
58+
sshuttle.firewall.restore_etc_hosts(hostmap, 10)
5959
assert orig_hosts.computehash() == new_hosts.computehash()
6060

6161

0 commit comments

Comments
 (0)