Blog | G5 Cyber Security

Block Ads: Validate /etc/hosts Files

TL;DR

Using a third-party provider to block ads with your /etc/hosts file is effective, but you need to regularly check the list hasn’t been compromised. This guide shows how to validate those lists and keep your system safe.

1. Understand the Risk

Your /etc/hosts file maps domain names to IP addresses. Ad-blocking providers give you a list of domains (ad servers, trackers) that redirect to 127.0.0.1 (your own computer) or 0.0.0.0 (nowhere). If this list is tampered with, it could:

2. Choose a Validation Method

There are several ways to validate your /etc/hosts file:

3. Checksum Validation (If Available)

Some providers publish a checksum for their /etc/hosts file. Here’s how to use it:

  1. Download the Checksum: Get the latest checksum from the provider’s website.
  2. Calculate Your File’s Checksum: Use a command-line tool like sha256sum.
sha256sum /etc/hosts
  • Compare: If the checksums match, your file is likely valid. If they don’t, download a fresh copy from the provider.
  • 4. Automated Script Validation (Recommended)

    This method uses a script to automatically download and compare lists.

    1. Download the Latest List: Get the URL for the latest /etc/hosts file from your provider.
    2. Create a Script: Here’s an example Bash script (save it as, e.g., check_hosts.sh):
      #!/bin/bash
      
      # Configuration - CHANGE THESE VALUES!
      HOSTS_FILE="/etc/hosts"
      PROVIDER_URL="https://example.com/hosts.txt" # Replace with your provider's URL
      BACKUP_DIR="/var/tmp/hosts_backups"
      
      # Create backup directory if it doesn't exist
      mkdir -p "$BACKUP_DIR"
      
      # Backup current hosts file
      cp "$HOSTS_FILE" "$BACKUP_DIR/hosts.backup.$(date +%Y%m%d)"
      
      # Download the latest hosts file
      wget -q -O /tmp/new_hosts "$PROVIDER_URL"
      
      # Compare the files
      diff "$HOSTS_FILE" /tmp/new_hosts > /dev/null
      
      if [ $? -eq 0 ]; then
      echo "Hosts file is up to date."
      else
      echo "Hosts file has changes. Replacing..."
      cp /tmp/new_hosts "$HOSTS_FILE"
      fi
      
      rm /tmp/new_hosts
      
    3. Make the Script Executable:
      chmod +x check_hosts.sh
    4. Run the Script Regularly: Use cron to schedule it (e.g., daily).
    5. Edit your crontab:
      crontab -e
    6. Add a line like this (runs at 3 AM every day):
      0 3 * * * /path/to/check_hosts.sh >/dev/null 2>&1

    5. Important Considerations

    Exit mobile version