TL;DR
Attackers can modify your computer’s /etc/hosts file to redirect websites to malicious locations. This guide explains how these attacks work and how to protect yourself, detect changes, and restore the correct file.
What is the /etc/hosts File?
The /etc/hosts file maps domain names (like google.com) to IP addresses. Your computer checks this file *before* contacting a DNS server. This means a malicious entry in /etc/hosts can override legitimate DNS records, sending you to the wrong website even if your DNS is correct.
How Attacks Happen
Attackers typically need administrator (root) access to modify /etc/hosts. They might get this through:
- Malware: Viruses, Trojans, and other malware can install themselves with admin privileges.
- Compromised Accounts: If an attacker gains control of your user account with sufficient permissions (e.g., via a weak password), they could modify the file.
Detecting /etc/hosts File Changes
- Check the File Contents: The
/etc/hostsfile should contain only a few entries, typically localhost (127.0.0.1) and possibly your computer’s hostname. Any other entries are suspicious.sudo nano /etc/hosts - Compare to a Known Good Version: If you have a backup of your original
/etc/hostsfile, compare it to the current one using a tool likediff.diff /etc/hosts /path/to/backup/hosts.bak - Use Hosts File Monitoring Tools: Several tools can automatically detect changes to the
/etc/hostsfile. Examples include:- Linux Malware Detect (LMD): https://www.rfxnelson.com/linux-malware-detect/
- chkrootkit: A rootkit detection tool that also checks the hosts file.
Restoring the /etc/hosts File
- Backup the Current File (Important!): Before making any changes, create a backup of the potentially compromised
/etc/hostsfile.sudo cp /etc/hosts /etc/hosts.bak - Replace with a Known Good Version: If you have a backup, restore it.
sudo cp /path/to/backup/hosts.bak /etc/hosts - If No Backup Exists: Create a new
/etc/hostsfile with the default contents:sudo nano /etc/hostsAdd these lines (adjust your hostname as needed):
127.0.0.1 localhost::1 localhost ip6-localhost ip6-loopbackff02::1 ip6-allnodes ip6-allinterfaces - Clear DNS Cache: After restoring the file, clear your computer’s DNS cache to ensure it uses the new
/etc/hostsentries.- Linux (systemd-resolved):
sudo systemd-resolve --flush-caches - Linux (nscd):
sudo /etc/init.d/nscd restart
- Linux (systemd-resolved):
Preventing Future Attacks
- Strong Passwords: Use strong, unique passwords for all user accounts.
- Keep Software Updated: Regularly update your operating system and software to patch security vulnerabilities.
- Antivirus/Anti-Malware Software: Install and keep antivirus/anti-malware software up-to-date.
- Be Careful with Downloads: Avoid downloading files from untrusted sources.
- Limit Admin Access: Only grant administrator privileges to users who absolutely need them.

