Come utilizzare PowerShell per la verifica degli hash dei file nella sicurezza IT

Nel panorama IT odierno, garantire l’integrità e la sicurezza dei dati è fondamentale. Un metodo efficace per verificare l’integrità dei file è l’utilizzo dei valori hash. Un valore hash agisce come un’impronta digitale per i file, consentendo ai professionisti IT di verificare se i file sono stati manomessi o corrotti. In questo articolo analizzeremo uno script PowerShell progettato per cercare file con valori hash specifici, uno strumento prezioso per i professionisti IT e i Managed Service Provider (MSP).

Background

Lo script PowerShell per la verifica degli hash fornito è progettato per avvisare gli utenti se viene trovato un file con un hash e un’estensione specificati all’interno di una determinata directory e delle sue sottodirectory. L’hashing dei file è una pratica comune nell’IT per verificare l’integrità dei file e rilevare modifiche non autorizzate. Questo script semplifica e automatizza il processo di verifica, rendendo più facile per i professionisti IT garantire la sicurezza e l’integrità dei loro sistemi.

Lo script per la verifica degli hash

#Requires -Version 5.1

<#
.SYNOPSIS
    Alerts if a file with the extension and specified hash is found in the given search directory or subdirectories. Warning: Hashing large files may impact performance.
.DESCRIPTION
    Alerts if a file with the extension and specified hash is found in the given search directory or subdirectories. Warning: Hashing large files may impact performance.
.EXAMPLE
    -Hash "F55A61A82F4F5943F86565E1FA2CCB4F" -SearchPath "C:" -FileType ".ico" -CustomField "multiline"
    WARNING: Backslash missing from the search path. Changing it to C:\.
    WARNING: File with MD5 hash of F55A61A82F4F5943F86565E1FA2CCB4F found!

    File Name         Path                                                                                    
    ---------         ----                                                                                    
    zoo_ecosystem.ico C:\Users\Administrator\Desktop\Find-FileHash\Test Folder 1\zoo_ecosystem.ico            
    zoo_ecosystem.ico C:\Users\Administrator\Desktop\Find-FileHash\TestFolder1\Test Folder 1\zoo_ecosystem.ico
    zoo_ecosystem.ico C:\Users\Administrator\Desktop\Find-FileHash\TestFolder2\Test Folder 1\zoo_ecosystem.ico

    Attempting to set Custom Field 'multiline'.
    Successfully set Custom Field 'multiline'!

PARAMETER: -Hash "REPLACEMEWITHAVALIDHASH"
    Files with this hash should cause the alert to trigger.

PARAMETER: -Algorithm "MD5"
    Hashing algorithm used for the above hash.

PARAMETER: -SearchPath "C:\ReplaceMeWithAValidSearchPath"
   Specifies one or more starting directories for the search, separated by commas. The search will recursively include all subdirectories from these starting points.

PARAMETER: -Timeout "15"
    Once this timeout is reached, the script will stop searching for files that match your given hash.

PARAMETER: -FileType ".exe"
    Specifies the file extension to filter the search. Only files with this extension will be analyzed for a hash match. Example: '.exe'

PARAMETER: -CustomField "NameOfMultiLineCustomField"
    Specifies the name of an optional multiline custom field where results can be sent. 

.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/it/condizioni-utilizzo
    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 (
    [Parameter()]
    [String]$Hash,
    [Parameter()]
    [String]$SearchPath = "C:\Windows",
    [Parameter()]
    [String]$FileType,
    [Parameter()]
    [Int]$Timeout = 15,
    [Parameter()]
    [String]$Algorithm = "MD5",
    [Parameter()]
    [String]$CustomField
)

begin {
    # Set parameters using dynamic script variables.
    if ($env:hash -and $env:hash -notlike "null") { $Hash = $env:hash }
    if ($env:hashType -and $env:hashType -notlike "null") { $Algorithm = $env:hashType }
    if ($env:searchPath -and $env:searchPath -notlike "null") { $SearchPath = $env:searchPath }
    if ($env:timeoutInMinutes -and $env:timeoutInMinutes -notlike "null") { $Timeout = $env:timeoutInMinutes }
    if ($env:fileExtensionToSearchFor -and $env:fileExtensionToSearchFor -notlike "null") { $FileType = $env:fileExtensionToSearchFor }
    if ($env:customFieldName -and $env:customFieldName -notlike "null") { $CustomField = $env:customFieldName }

    # If given a comma-separated list, split the paths.
    $PathsToSearch = New-Object System.Collections.Generic.List[String]
    if ($SearchPath -match ",") {
        $SearchPath -split "," | ForEach-Object { $PathsToSearch.Add($_.Trim()) }
    }
    else {
        $PathsToSearch.Add($SearchPath)
    }

    $ReplacementPaths = New-Object System.Collections.Generic.List[Object]
    $PathsToRemove = New-Object System.Collections.Generic.List[String]

    # If given a drive without the backslash add it in.
    $PathsToSearch | ForEach-Object {
        if ($_ -notmatch '^[A-Z]:\\$' -and $_ -match '^[A-Z]:$') {
            $NewPath = "$_\"
            $ReplacementPaths.Add(
                [PSCustomObject]@{
                    Index   = $PathsToSearch.IndexOf("$_")
                    NewPath = $NewPath
                }
            )
                
            Write-Warning "Backslash missing from the search path. Changing it to $NewPath."
        }
    }

    # Apply replacements
    $ReplacementPaths | ForEach-Object {
        $PathsToSearch[$_.index] = $_.NewPath 
    }

    # Check if the search path is valid.
    $PathsToSearch | ForEach-Object {
        if (-not (Test-Path $_)) {
            Write-Host -Object "[Error] $_ does not exist!"
            $PathsToRemove.Add($_)
            $ExitCode = 1
        }
    }

    $PathsToRemove | ForEach-Object {
        $PathsToSearch.Remove($_) | Out-Null
    }


    # Error out if no valid paths to search.
    if ($PathsToSearch.Count -eq 0) {
        Write-Host "[Error] No valid paths to search!"
        exit 1
    }

    # A file extension is required.
    if (-not $FileType) {
        Write-Host -Object "[Error] File Type is required!"
        exit 1
    }

    # If we were given the extension without the . we'll add it back in
    if ($FileType -notmatch '^\.') {
        $FileType = ".$FileType"
        Write-Warning -Message "Extension missing changing filetype to $FileType."
    }

    # The timeout has to be between 1 and 120
    if ($Timeout -lt 1 -or $Timeout -gt 120) {
        Write-Host "[Error] Invalid timeout given of $Timeout minutes. Please enter a value between 1 and 120."
        exit 1
    }

    # PowerShell 5.1 supports more algorithms than this, however PowerShell 7 does not.
    $ValidAlgorithms = "SHA1", "SHA256", "SHA384", "SHA512", "MD5"
    if ($ValidAlgorithms -notcontains $Algorithm) {
        Write-Host "[Error] Invalid Algorithm selected. Only SHA1, SHA256, SHA384, SHA512 and MD5 are supported."
        exit 1
    }

    # Helper function to make it easier to set custom fields.
    function Set-NinjaProperty {
        [CmdletBinding()]
        Param(
            [Parameter(Mandatory = $True)]
            [String]$Name,
            [Parameter()]
            [String]$Type,
            [Parameter(Mandatory = $True, ValueFromPipeline = $True)]
            $Value,
            [Parameter()]
            [String]$DocumentName
        )
    
        $Characters = $Value | Measure-Object -Character | Select-Object -ExpandProperty Characters
        if ($Characters -ge 10000) {
            throw [System.ArgumentOutOfRangeException]::New("Character limit exceeded, value is greater than 10,000 characters.")
        }
        
        # If we're requested to set the field value for a Ninja document we'll specify it here.
        $DocumentationParams = @{}
        if ($DocumentName) { $DocumentationParams["DocumentName"] = $DocumentName }
        
        # This is a list of valid fields that can be set. If no type is given, it will be assumed that the input doesn't need to be changed.
        $ValidFields = "Attachment", "Checkbox", "Date", "Date or Date Time", "Decimal", "Dropdown", "Email", "Integer", "IP Address", "MultiLine", "MultiSelect", "Phone", "Secure", "Text", "Time", "URL", "WYSIWYG"
        if ($Type -and $ValidFields -notcontains $Type) { Write-Warning "$Type is an invalid type! Please check here for valid types. https://ninjarmm.zendesk.com/hc/en-us/articles/16973443979789-Command-Line-Interface-CLI-Supported-Fields-and-Functionality" }
        
        # The field below requires additional information to be set
        $NeedsOptions = "Dropdown"
        if ($DocumentName) {
            if ($NeedsOptions -contains $Type) {
                # We'll redirect the error output to the success stream to make it easier to error out if nothing was found or something else went wrong.
                $NinjaPropertyOptions = Ninja-Property-Docs-Options -AttributeName $Name @DocumentationParams 2>&1
            }
        }
        else {
            if ($NeedsOptions -contains $Type) {
                $NinjaPropertyOptions = Ninja-Property-Options -Name $Name 2>&1
            }
        }
        
        # If an error is received it will have an exception property, the function will exit with that error information.
        if ($NinjaPropertyOptions.Exception) { throw $NinjaPropertyOptions }
        
        # The below type's require values not typically given in order to be set. The below code will convert whatever we're given into a format ninjarmm-cli supports.
        switch ($Type) {
            "Checkbox" {
                # While it's highly likely we were given a value like "True" or a boolean datatype it's better to be safe than sorry.
                $NinjaValue = [System.Convert]::ToBoolean($Value)
            }
            "Date or Date Time" {
                # Ninjarmm-cli expects the  Date-Time to be in Unix Epoch time so we'll convert it here.
                $Date = (Get-Date $Value).ToUniversalTime()
                $TimeSpan = New-TimeSpan (Get-Date "1970-01-01 00:00:00") $Date
                $NinjaValue = $TimeSpan.TotalSeconds
            }
            "Dropdown" {
                # Ninjarmm-cli is expecting the guid of the option we're trying to select. So we'll match up the value we were given with a guid.
                $Options = $NinjaPropertyOptions -replace '=', ',' | ConvertFrom-Csv -Header "GUID", "Name"
                $Selection = $Options | Where-Object { $_.Name -eq $Value } | Select-Object -ExpandProperty GUID
        
                if (-not $Selection) {
                    throw [System.ArgumentOutOfRangeException]::New("Value is not present in dropdown")
                }
        
                $NinjaValue = $Selection
            }
            default {
                # All the other types shouldn't require additional work on the input.
                $NinjaValue = $Value
            }
        }
        
        # We'll need to set the field differently depending on if its a field in a Ninja Document or not.
        if ($DocumentName) {
            $CustomField = Ninja-Property-Docs-Set -AttributeName $Name -AttributeValue $NinjaValue @DocumentationParams 2>&1
        }
        else {
            $CustomField = Ninja-Property-Set -Name $Name -Value $NinjaValue 2>&1
        }
        
        if ($CustomField.Exception) {
            throw $CustomField
        }
    }

    # Test for local administrator rights
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    $ExitCode = 0
}
process {
    if (-not (Test-IsElevated)) {
        Write-Host -Object "[Error] Access Denied. Please run with Administrator privileges."
        exit 1
    }

    # If we're given a file instead of a folder, we'll check if it matches anyways.
    $PathsToSearch | ForEach-Object {
        if (-not (Get-Item $_).PSIsContainer) {
            Write-Warning "The search path you gave is actually a file not a folder. Checking the hash of the file..."
        }
    }
    
    $HashJobs = New-Object System.Collections.Generic.List[object]
    $MatchingFiles = New-Object System.Collections.Generic.List[object]
    $CustomFieldValue = New-Object System.Collections.Generic.List[string]

    # We'll use a PowerShell job so that we can timeout appropriately.
    $PathsToSearch | ForEach-Object {
        $HashJobs.Add(
            (
                Start-Job -ScriptBlock {
                    param($SearchPath, $FileType, $Algorithm, $Hash)
                    $Files = Get-ChildItem -Path $SearchPath -Filter "*$FileType" -File -Recurse
                    $Files | ForEach-Object {
                        $CurrentHash = Get-FileHash -Path $_.FullName -Algorithm $Algorithm
                        if ($CurrentHash.Hash -match $Hash) { $_.FullName }
                    }
                } -ArgumentList $_, $FileType, $Algorithm, $Hash
            )
        )
    }

    $TimeoutInSeconds = $Timeout * 60
    $StartTime = Get-Date

    # Wait for all jobs to complete or timeout
    foreach ($HashJob in $HashJobs) {
        # Calculate the remaining time
        $TimeElapsed = (Get-Date) - $StartTime
        $RemainingTime = $TimeoutInSeconds - $TimeElapsed.TotalSeconds
    
        # If there is no remaining time, break the loop
        if ($RemainingTime -le 0) {
            break
        }
    
        # Wait for the current job with the remaining time as the timeout
        $HashJob | Wait-Job -Timeout $RemainingTime | Out-Null
    }

    # If we failed to complete the job, we'll output a warning.
    $IncompleteJobs = $HashJobs | Get-Job | Where-Object { $_.State -eq "Running" }
    if ($IncompleteJobs) {
        Write-Host "[Error] The timeout period of $Timeout minutes has been reached, but some files still require a hash check!"
        $CustomFieldValue.Add("[Error] The timeout period of $Timeout minutes has been reached, but some files still require a hash check!")
        $ExitCode = 1
    }

    # Receive the data from the job.
    $HashJobs | Receive-Job -ErrorAction SilentlyContinue -ErrorVariable JobErrors | ForEach-Object {
        $MatchingFiles.Add(
            [PSCustomObject]@{
                "File Name" = $(Split-Path $_ -Leaf)
                Path        = $_
            }
        )
    }

    # If we have any matching files, we'll output them here.
    if ($MatchingFiles) {
        Write-Warning -Message "File with $Algorithm hash of $Hash found!"
        $MatchingFiles | Format-Table -AutoSize | Out-String | Write-Host
        $MatchingFiles | Select-Object -ExpandProperty Path | ForEach-Object { $CustomFieldValue.Add($_) }
    }
    else {
        Write-Host -Object "No files found with $Hash."
    }

    # If we received any failures or errors, we'll output that here.
    $FailedJobs = $HashJobs | Get-Job | Where-Object { $_.State -ne "Completed" -and $_.State -ne "Running" }
    if ($FailedJobs -or $JobErrors) {
        Write-Host ""
        Write-Host "[Error] Failed to get the hash of certain files due to an error."
        $CustomFieldValue.Add(" ")
        $CustomFieldValue.Add("[Error] Failed to get the hash of certain files due to an error.")
        if ($JobErrors) {
            Write-Host ""
            $JobErrors | ForEach-Object { Write-Host "[Error] $($_.Exception.Message)" }
            $CustomFieldValue.Add(" ")
            $JobErrors | ForEach-Object { $CustomFieldValue.Add("[Error] $($_.Exception.Message)") }
        }
        $ExitCode = 1
    }

    $HashJobs | Remove-Job -Force

    # If we're given a custom field, we'll attempt to save the results to it.
    if ($CustomField) {
        try {
            Write-Host "Attempting to set Custom Field '$CustomField'."
            Set-NinjaProperty -Name $CustomField -Value ($CustomFieldValue | Out-String)
            Write-Host "Successfully set Custom Field '$CustomField'!"
        }
        catch {
            if (-not $_.Exception.Message) {
                Write-Host "[Error] $($_.Message)"
            }
            else {
                Write-Host "[Error] $($_.Exception.Message)"
            }
            $ExitCode = 1
        }
        
    }

    exit $ExitCode
}
end {
    
    
    
}

 

Accedi a oltre 700 script nel Dojo NinjaOne

Ottieni l’accesso

Analisi dettagliata

Lo script per la verifica degli hash inizia con informazioni sui metadati, tra cui una sinossi, una descrizione e un esempio di utilizzo. Imposta i parametri che l’utente può specificare, come il valore di hash, il percorso di ricerca, il tipo di file, l’algoritmo di hashing, il periodo di timeout e un campo personalizzato opzionale per i risultati di output.

Impostazione dei parametri

  • Hash: Il valore hash specifico da cercare.
  • Percorso di ricerca: La directory da cui iniziare la ricerca, per impostazione predefinita è C:\Windows.
  • Tipo di file: L’estensione del file da filtrare.
  • Timeout: Il tempo massimo di ricerca, predefinito a 15 minuti.
  • Algoritmo: L’algoritmo di hashing, di default MD5.
  • Campo personalizzato: Un campo opzionale per memorizzare i risultati.

Lo script per la verifica degli hash regola dinamicamente questi parametri in base alle variabili ambientali, se queste sono impostate.

Convalida del percorso e del tipo di file

Lo script per la verifica degli hash convalida i percorsi di ricerca, assicurandosi che esistano e siano formattati correttamente. Aggiunge una backslash alle lettere delle unità, se mancante, e controlla se il percorso fornito è un file anziché una cartella, emettendo avvisi e regolandosi di conseguenza.

Gestione del processo per il calcolo degli hash

Per gestire calcoli di hash potenzialmente lunghi, lo script utilizza i processi di PowerShell. Avvia un processo per ogni percorso di ricerca, cercando ricorsivamente i file con l’estensione specificata e calcolando i loro valori hash. I risultati vengono raccolti e confrontati con il valore hash fornito.

Timeout e gestione degli errori

Lo script per la verifica degli hash include un meccanismo di timeout per interrompere la ricerca dopo un periodo specificato, evitando che venga eseguita all’infinito. Raccoglie tutti gli errori riscontrati durante l’esecuzione del processo e fornisce all’utente messaggi di errore dettagliati.

Integrazione con campi personalizzati

Se viene specificato un campo personalizzato, lo script tenta di salvare i risultati in esso utilizzando la funzione Set-NinjaProperty, che gestisce vari tipi di campi personalizzati e assicura che i dati siano formattati correttamente ed entro i limiti di caratteri.

Risultato finale

Lo script per la verifica degli hash visualizza i file corrispondenti, gli eventuali errori riscontrati e tenta di impostare il campo personalizzato con i risultati. Lo script termina uscendo con un codice di stato appropriato in base al successo o al fallimento delle operazioni.

Casi d’uso potenziali

Immagina un professionista IT responsabile di mantenere l’integrità dei file di distribuzione del software su una rete. Utilizzando questo script per la verifica degli hash, può scansionare regolarmente le directory in cui sono memorizzati i pacchetti software, assicurandosi che non siano state apportate modifiche non autorizzate. Per esempio, se l’hash di un file .exe critico cambia, ciò potrebbe indicare una manomissione o un danneggiamento, e richiedere un’indagine immediata.

Confronti

I metodi tradizionali di verifica degli hash e quindi dell’integrità dei file prevedono spesso controlli manuali dell’hash con strumenti come certutil su Windows. Questo script automatizza e semplifica il processo, fornendo una soluzione più efficiente e completa. Inoltre, si integra perfettamente con altri script e strumenti utilizzati dai professionisti IT, e questo aumenta la sua utilità in vari scenari.

Domande frequenti

Come posso specificare più directory per la ricerca?
Utilizza un elenco separato da virgole nel parametro -SearchPath.

Quali algoritmi di hashing sono supportati?
Lo script per la verifica degli hash supporta MD5, SHA1, SHA256, SHA384 e SHA512.

Posso aumentare il timeout oltre i 120 minuti?
No, il timeout massimo consentito è di 120 minuti per motivi di prestazioni e praticità.

Implicazioni

L’uso di questo script per la verifica degli hash aiuta i professionisti IT a garantire l’integrità dei file critici, riducendo il rischio di violazioni della sicurezza causate da file manomessi o corrotti. Automatizzando il processo di verifica degli hash, si risparmia tempo e si fornisce un metodo affidabile per mantenere l’integrità dei dati su reti di grandi dimensioni.

Raccomandazioni

  • Aggiorna e controlla regolarmente lo script per la verifica degli hash per adattarlo a nuovi algoritmi di hashing e tipi di file.
  • Pianifica l’esecuzione dello script per la verifica degli hash a intervalli regolari per monitorare costantemente l’integrità dei file.
  • Utilizza la funzione di campo personalizzato per registrare i risultati in una posizione centrale per facilitarne l’accesso e la revisione.

Considerazioni finali

L’integrazione di script PowerShell come questo per la verifica degli hash nel tuo kit di strumenti IT migliora la capacità di mantenere l’integrità e la sicurezza dei dati. Strumenti come NinjaOne possono semplificare ulteriormente questi processi, offrendo funzionalità avanzate e integrazioni che rendono la gestione dei sistemi IT più efficiente ed efficace. Sfruttando queste tecnologie, i professionisti IT possono proteggere meglio i loro ambienti e garantire l’affidabilità dei loro dati.

Passi successivi

La creazione di un team IT efficiente ed efficace richiede una soluzione centralizzata che funga da principale strumento per la fornitura di servizi. NinjaOne consente ai team IT di monitorare, gestire, proteggere e supportare tutti i dispositivi, ovunque essi si trovino, senza la necessità di una complessa infrastruttura locale.

Per saperne di più su NinjaOne Endpoint Management, fai un tour dal vivo, o inizia la tua prova gratuita della piattaforma NinjaOne.

Categorie:

Ti potrebbe interessare anche

Guarda una demo×
×

Guarda NinjaOne in azione!

Inviando questo modulo, accetto La politica sulla privacy di NinjaOne.

Termini e condizioni NinjaOne

Cliccando sul pulsante “Accetto” qui sotto, dichiari di accettare i seguenti termini legali e le nostre condizioni d’uso:

  • Diritti di proprietà: NinjaOne possiede e continuerà a possedere tutti i diritti, i titoli e gli interessi relativi allo script (compreso il copyright). NinjaOne ti concede una licenza limitata per l’utilizzo dello script in conformità con i presenti termini legali.
  • Limitazione d’uso: Puoi utilizzare lo script solo per legittimi scopi personali o aziendali interni e non puoi condividere lo script con altri soggetti.
  • Divieto di ripubblicazione: In nessun caso ti è consentito ripubblicare lo script in una libreria di script appartenente o sotto il controllo di un altro fornitore di software.
  • Esclusione di garanzia: Lo script viene fornito “così com’è” e “come disponibile”, senza garanzie di alcun tipo. NinjaOne non promette né garantisce che lo script sia privo di difetti o che soddisfi le tue esigenze o aspettative specifiche.
  • Assunzione del rischio: L’uso che farai dello script è da intendersi a tuo rischio. Riconosci che l’utilizzo dello script comporta alcuni rischi intrinseci, che comprendi e sei pronto ad assumerti.
  • Rinuncia e liberatoria: Non riterrai NinjaOne responsabile di eventuali conseguenze negative o indesiderate derivanti dall’uso dello script e rinuncerai a qualsiasi diritto legale o di equità e a qualsiasi rivalsa nei confronti di NinjaOne in relazione all’uso dello script.
  • EULA: Se sei un cliente NinjaOne, l’uso dello script è soggetto al Contratto di licenza con l’utente finale (EULA) applicabile.