Blog | G5 Cyber Security

Hosts File Attacks: Prevention & Recovery

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:

Detecting /etc/hosts File Changes

  1. Check the File Contents: The /etc/hosts file 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
  2. Compare to a Known Good Version: If you have a backup of your original /etc/hosts file, compare it to the current one using a tool like diff.
    diff /etc/hosts /path/to/backup/hosts.bak
  3. Use Hosts File Monitoring Tools: Several tools can automatically detect changes to the /etc/hosts file. Examples include:

Restoring the /etc/hosts File

  1. Backup the Current File (Important!): Before making any changes, create a backup of the potentially compromised /etc/hosts file.
    sudo cp /etc/hosts /etc/hosts.bak
  2. Replace with a Known Good Version: If you have a backup, restore it.
    sudo cp /path/to/backup/hosts.bak /etc/hosts
  3. If No Backup Exists: Create a new /etc/hosts file with the default contents:
    sudo nano /etc/hosts

    Add these lines (adjust your hostname as needed):

    127.0.0.1   localhost
    ::1         localhost ip6-localhost ip6-loopback
    ff02::1     ip6-allnodes ip6-allinterfaces
  4. Clear DNS Cache: After restoring the file, clear your computer’s DNS cache to ensure it uses the new /etc/hosts entries.
    • Linux (systemd-resolved):
      sudo systemd-resolve --flush-caches
    • Linux (nscd):
      sudo /etc/init.d/nscd restart

Preventing Future Attacks

  1. Strong Passwords: Use strong, unique passwords for all user accounts.
  2. Keep Software Updated: Regularly update your operating system and software to patch security vulnerabilities.
  3. Antivirus/Anti-Malware Software: Install and keep antivirus/anti-malware software up-to-date.
  4. Be Careful with Downloads: Avoid downloading files from untrusted sources.
  5. Limit Admin Access: Only grant administrator privileges to users who absolutely need them.
Exit mobile version