Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

How to Check for a Modified Hosts File with PowerShell

In the vast realm of IT, the hosts file stands as a silent sentinel, ensuring smooth network communications. For those unfamiliar, the hosts file is a text file that maps hostnames to IP addresses. It’s used by the operating system to resolve hostnames to IP addresses when a computer tries to connect to a network resource. But what happens when the hosts file is tampered with or modified? How can IT professionals and Managed Service Providers (MSPs) ensure the integrity of this crucial file? Enter the script we’re about to delve into.

Understanding the Hosts File

The hosts file, in its essence, is the computer system’s address book. It plays a pivotal role in directing network traffic, ensuring that users land on the correct websites and services. However, its significance also makes it a prime target for malicious actors.

The Potential Risks of Unauthorized Modifications

An attacker, with nefarious intentions, could modify the hosts file to redirect traffic to a malicious website or server. Such alterations can have dire consequences:

  • Stealing Personal Information: By redirecting users to counterfeit sites, attackers can phish for personal details, leading to identity theft.
  • Malware Installation: Users can be tricked into downloading malicious software, thinking they are on a legitimate site.
  • Disruption of Network Communications: Essential services can be blocked, causing operational disruptions.

Given these risks, it’s paramount for IT professionals and MSPs to have tools that can swiftly detect any unauthorized changes. This is where our script comes into play.

The Script

#Requires -Version 5.1

<#
.SYNOPSIS
    Checks if the hosts file was modified from last run.
.DESCRIPTION
    Checks if the hosts file was modified from last run.
    On first run this will not produce an error, but will create a cache file for later comparison.
.EXAMPLE
    No parameters needed.
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes:
    Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param (
    # Path and file of the hosts file
    [string]
    $HostsPath = "C:WindowsSystem32driversetchosts",
    # Path and file where the cache file will be saved for comparison
    [string]
    $CachePath = "C:ProgramDataNinjaRMMAgentscriptingTest-HostsFile.clixml"
)

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }

    # Check if hosts file exists
    if ($(Test-Path -Path $HostsPath)) {
        # Get content and create hash of hosts file
        $HostsContent = Get-Content -Path $HostsPath
        $HostsHash = Get-FileHash -Path $HostsPath -Algorithm SHA256

        $Current = [PSCustomObject]@{
            Content = $HostsContent
            Hash    = $HostsHash
        }

        # Check if this is first run or not
        if ($(Test-Path -Path $CachePath)) {
            # Compare last content and hash
            $Cache = Import-Clixml -Path $CachePath
            $ContentDifference = Compare-Object -ReferenceObject $Cache.Content -DifferenceObject $Current.Content -CaseSensitive
            $HashDifference = $Cache.Hash -like $Current.Hash
            $Current | Export-Clixml -Path $CachePath -Force -Confirm:$false
            if (-not $HashDifference) {
                Write-Host "Hosts file has changed since last run!"
                Write-Host ""
                $ContentDifference | ForEach-Object {
                    if ($_.SideIndicator -like '=>') {
                        Write-Host "Added: $($_.InputObject)"
                    }
                    elseif ($_.SideIndicator -like '<=') {
                        Write-Host "Removed: $($_.InputObject)"
                    }
                }
                exit 1
            }
        }
        else {
            Write-Host "First run, saving comparison cache file."
            $Current | Export-Clixml -Path $CachePath -Force -Confirm:$false
        }
    }
    else {
        Write-Error "Hosts file is missing!"
        exit 1
    }
    exit 0
}
end {}

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

A Deep Dive into the Script

The provided PowerShell script is designed to check if the hosts file has been modified since its last run. Here’s a breakdown of its functionality:

  1. Elevation Check: The script first checks if it’s running with administrator privileges. This is crucial because any attempt to read or modify system files requires elevated permissions.
  2. Hosts File Verification: It then verifies the existence of the hosts file. If the file is missing, the script flags an error.
  3. Hash Comparison: The script calculates a hash (SHA256) of the current hosts file and compares it with a cached version from the last run. If there’s a mismatch, it indicates the file has been modified.
  4. Content Comparison: Beyond just checking the hash, the script also compares the content line by line, highlighting any additions or removals.

Benefits for IT Professionals and MSPs

  • Proactive Monitoring: This script offers a proactive approach to monitor the hosts file, ensuring its integrity and alerting administrators of any unauthorized changes.
  • Detailed Insights: By comparing content differences, IT teams can quickly identify what was added or removed, aiding in swift remediation.
  • Automation Ready: Given its design, the script can be integrated into automated workflows, allowing for regular checks without manual intervention.

The Power of NinjaOne

NinjaOne is more than just an IT management solution. It’s a comprehensive platform that empowers IT professionals and MSPs to stay ahead of potential threats. By integrating our hosts file check script into NinjaOne:

  • Centralized Alerts: Receive alerts directly on the NinjaOne dashboard whenever the hosts file is modified. This immediate notification ensures that you can act swiftly, protecting your systems from potential attacks.
  • Scheduled Checks: Automate the script to run at specified intervals, ensuring continuous monitoring.
  • Detailed Reporting: Combine the insights from the script with NinjaOne’s reporting capabilities for a holistic view of your IT environment.

In conclusion, the hosts file, while often overlooked, is a cornerstone of network communications. Ensuring its integrity is paramount. Our script, especially when combined with the power of NinjaOne, provides IT teams with the tools they need to monitor, detect, and act against unauthorized modifications, ensuring a secure and smooth IT environment.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).