That time Defender would block WSL hosts file even after allowed

Fun Fact: By default WSL will generate /etc/hosts based on your Windows hosts file. This happens at least once per reboot or perhaps more often. I’m not sure what conditions cause it to regenerate.

A while back (maybe 2 months or so?) Microsoft Defender began flagging modified hosts files as a threat: Win32/HostsFileHijack. I’ve used Spybot Anti-beacon so I had to restore/allow the Windows hosts file.

At that same time Defender also started flagging the WSL /etc/hosts file. The first time it happened, I restored/allowed but could not access the file. I don’t know why.

A couple days later (after a reboot? can’t remember) the file just wasn’t there and I would receive messages couldn't resolve localhost (or something similar) when running ping. At that point I copied /etc/hosts from a working Ubuntu install.

I had never bothered to look at /etc/hosts which has a comment stating it is auto generated and the original file wasn’t there after Defender nuked it.

So for the past while every so often I’ve had to deal with Defender flagging the WSL /etc/hosts file. This also causes windows backup to fail. If the threat were real this is quite reasonable, however in this case meh. Luckily I haven’t needed backups during this time.

I incorrectly ASSumed it was re-flagging an allowed file, which in a way it is… but I guess if the file is regenerated it’s a different file for Defender even though the contents are the same. ¯\_(ツ)_/¯

Today I finally bothered to try and view the file again after restore/allow and I was able to see it!! This lovely comment greeted me at the top:

# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateHosts = false

Below that the contents of the Windows hosts file. DING!

So even though I allowed the Windows hosts file and Defender hasn’t flagged it anymore, Defender would flag the WSL /etc/hosts file every time it was regenerated even though it had been restored/allowed at least a dozen times…

why-angry-why

So if you want more info on /etc/wsl.conf check out the informative blog post here: https://devblogs.microsoft.com/commandline/automatically-configuring-wsl/