Guarda una demo×
×

Guarda NinjaOne in azione!

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

Rilevare e prevenire gli attacchi Brute Force con PowerShell

Sebbene le minacce informatiche siano in continua evoluzione, la maggior parte delle intrusioni si basa ancora su tecniche di base collaudate. Se indovinare le password comunemente usate o sfruttare le password utilizzate per più account può darti facile accesso, chi ha bisogno di bruciare uno zero-day?

Gli attacchi brute force continuano ad essere una minaccia incredibilmente comune per le organizzazioni. Rilevare e bloccare gli attacchi brute force il più rapidamente possibile è fondamentale, perché spesso sono i primi indizi di attività più dannose e di tentativi di accesso pericolosi. Poiché in presenza di attacchi brute force ogni minuto è importante, l’impostazione di policy di blocco dell’account e di avvisi in tempo reale per i tentativi di accesso falliti è un deterrente e una misura di allarme estremamente importanti.

Invece che dire del rilevamento degli attacchi brute force su un’intera rete aziendale, da remoto e su larga scala?

Rilevare gli attacchi brute force in un contesto di questo tipo può essere una sfida, ecco perché abbiamo fornito il seguente script che gli amministratori possono utilizzare per automatizzare il processo, monitorando i tentativi di accesso falliti e attivando gli avvisi in base a soglie personalizzabili.

Script per il rilevamento e la prevenzione degli attacchi brute force

#Requires -Version 5.1

<#
.SYNOPSIS
    Condition for helping detect brute force login attempts.
.DESCRIPTION
    Condition for helping detect brute force login attempts.
.EXAMPLE
     -Hours 10
    Number of hours back in time to look through in the event log.
    Default is 1 hour.
.EXAMPLE
    -Attempts 100
    Number of login attempts to trigger at or above this number.
    Default is 8 attempts.
.OUTPUTS
    PSCustomObject[]
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes:
    Initial Release
    (c) 2023 NinjaOne
    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()]
    [int]
    $Hours = 1,
    [Parameter()]
    [int]
    $Attempts = 8
)

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)
    }
    function Test-StringEmpty {
        param([string]$Text)
        # Returns true if string is empty, null, or whitespace
        process { [string]::IsNullOrEmpty($Text) -or [string]::IsNullOrWhiteSpace($Text) }
    }
    if (-not $(Test-StringEmpty -Text $env:Hours)) {
        $Hours = $env:Hours
    }
    if (-not $(Test-StringEmpty -Text $env:Attempts)) {
        $Attempts = $env:Attempts
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }

    if ($(auditpol.exe /get /category:* | Where-Object { $_ -like "*Logon*Success and Failure" })) {
        Write-Information "Audit Policy for Logon is set to: Success and Failure"
    }
    else {
        Write-Error "Audit Policy for Logon is NOT set to: Success and Failure"
        exit 1
        # Write-Host "Setting Logon to: Success and Failure"
        # auditpol.exe /set /subcategory:"Logon" /success:enable /failure:enable
        # Write-Host "Future failed login attempts will be captured."
    }

    $StartTime = (Get-Date).AddHours(0 - $Hours)
    $EventId = 4625

    # Get failed login attempts
    try {
        $Events = Get-WinEvent -FilterHashtable @{LogName = "Security"; ID = $EventId; StartTime = $StartTime } -ErrorAction Stop | ForEach-Object {
            $Message = $_.Message -split [System.Environment]::NewLine
            $Account = $($Message | Where-Object { $_ -Like "*Account Name:*" }) -split 's+' | Select-Object -Last 1
            [int]$LogonType = $($Message | Where-Object { $_ -Like "Logon Type:*" }) -split 's+' | Select-Object -Last 1
            $SourceNetworkAddress = $($Message | Where-Object { $_ -Like "*Source Network Address:*" }) -split 's+' | Select-Object -Last 1
            [PSCustomObject]@{
                Account              = $Account
                LogonType            = $LogonType
                SourceNetworkAddress = $SourceNetworkAddress
            }
        } | Where-Object { $_.LogonType -in @(2, 7, 10) }
    }
    catch {
        if ($_.Exception.Message -like "No events were found that match the specified selection criteria.") {
            Write-Host "No failed logins found in the past $Hours hour(s)."
            exit 0
        }
        else {
            Write-Error $_
            exit 1
        }
    }

    # Build a list of accounts 
    $UsersAccounts = [System.Collections.Generic.List[String]]::new()
    try {
        $ErrorActionPreference = "Stop"
        Get-LocalUser | Select-Object -ExpandProperty Name | ForEach-Object { $UsersAccounts.Add($_) }
        $ErrorActionPreference = "Continue"
    }
    catch {
        $NetUser = net.exe user
        $(
            $NetUser | Select-Object -Skip 4 | Select-Object -SkipLast 2
            # Join each line with a ","
            # Replace and spaces with a ","
            # Split everything by ","
        ) -join ',' -replace 's+', ',' -split ',' |
            # Sort and remove any duplicates
            Sort-Object -Descending -Unique |
            # Filter out empty strings
            Where-Object { -not [string]::IsNullOrEmpty($_) -and -not [string]::IsNullOrWhiteSpace($_) } |
            ForEach-Object {
                $UsersAccounts.Add($_)
            }
    }
    $Events | Select-Object -ExpandProperty Account | ForEach-Object { $UsersAccounts.Add($_) }

    $Results = $UsersAccounts | Select-Object -Unique | ForEach-Object {
        $Account = $_
        $AccountEvents = $Events | Where-Object { $_.Account -like $Account }
        $AttemptCount = $AccountEvents.Count
        $SourceNetworkAddress = $AccountEvents | Select-Object -ExpandProperty SourceNetworkAddress -Unique
        if ($AttemptCount -gt 0) {
            [PSCustomObject]@{
                Account              = $Account
                Attempts             = $AttemptCount
                SourceNetworkAddress = $SourceNetworkAddress
            }
        }
    }

    # Get only the accounts with fail login attempts at or over $Attempts
    $BruteForceAttempts = $Results | Where-Object { $_.Attempts -ge $Attempts }
    if ($BruteForceAttempts) {
        $BruteForceAttempts | Out-String | Write-Host
        exit 1
    }
    $Results | Out-String | Write-Host
    exit 0
}
end {
    $ScriptVariables = @(
        [PSCustomObject]@{
            name           = "Hours"
            calculatedName = "hours" # Must be lowercase and no spaces
            required       = $false
            defaultValue   = [PSCustomObject]@{ # If not default value, then remove
                type  = "TEXT"
                value = "1"
            }
            valueType      = "TEXT"
            valueList      = $null
            description    = "Number of hours back in time to look through in the event log."
        }
        [PSCustomObject]@{
            name           = "Attempts"
            calculatedName = "attempts" # Must be lowercase and no spaces
            required       = $false
            defaultValue   = [PSCustomObject]@{ # If not default value, then remove
                type  = "TEXT"
                value = "8"
            }
            valueType      = "TEXT"
            valueList      = $null
            description    = "Number of login attempts to trigger at or above this number."
        }
    )
}

|

#Requires -Version 5.1

<#
.SYNOPSIS
    Condition for helping detect brute force login attempts.
.DESCRIPTION
    Condition for helping detect brute force login attempts.
.EXAMPLE
     -Hours 10
    Number of hours back in time to look through in the event log.
    Default is 1 hour.
.EXAMPLE
    -Attempts 100
    Number of login attempts to trigger at or above this number.
    Default is 8 attempts.
.OUTPUTS
    PSCustomObject[]
.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 (
    [Parameter()]
    [int]
    $Hours = 1,
    [Parameter()]
    [int]
    $Attempts = 8
)

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)
    }
    function Test-StringEmpty {
        param([string]$Text)
        # Returns true if string is empty, null, or whitespace
        process { [string]::IsNullOrEmpty($Text) -or [string]::IsNullOrWhiteSpace($Text) }
    }
    if (-not $(Test-StringEmpty -Text $env:Hours)) {
        $Hours = $env:Hours
    }
    if (-not $(Test-StringEmpty -Text $env:Attempts)) {
        $Attempts = $env:Attempts
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }

    if ($(auditpol.exe /get /category:* | Where-Object { $_ -like "*Logon*Success and Failure" })) {
        Write-Information "Audit Policy for Logon is set to: Success and Failure"
    }
    else {
        Write-Error "Audit Policy for Logon is NOT set to: Success and Failure"
        exit 1
        # Write-Host "Setting Logon to: Success and Failure"
        # auditpol.exe /set /subcategory:"Logon" /success:enable /failure:enable
        # Write-Host "Future failed login attempts will be captured."
    }

    $StartTime = (Get-Date).AddHours(0 - $Hours)
    $EventId = 4625

    # Get failed login attempts
    try {
        $Events = Get-WinEvent -FilterHashtable @{LogName = "Security"; ID = $EventId; StartTime = $StartTime } -ErrorAction Stop | ForEach-Object {
            $Message = $_.Message -split [System.Environment]::NewLine
            $Account = $($Message | Where-Object { $_ -Like "*Account Name:*" }) -split 's+' | Select-Object -Last 1
            [int]$LogonType = $($Message | Where-Object { $_ -Like "Logon Type:*" }) -split 's+' | Select-Object -Last 1
            $SourceNetworkAddress = $($Message | Where-Object { $_ -Like "*Source Network Address:*" }) -split 's+' | Select-Object -Last 1
            [PSCustomObject]@{
                Account              = $Account
                LogonType            = $LogonType
                SourceNetworkAddress = $SourceNetworkAddress
            }
        } | Where-Object { $_.LogonType -in @(2, 7, 10) }
    }
    catch {
        if ($_.Exception.Message -like "No events were found that match the specified selection criteria.") {
            Write-Host "No failed logins found in the past $Hours hour(s)."
            exit 0
        }
        else {
            Write-Error $_
            exit 1
        }
    }

    # Build a list of accounts 
    $UsersAccounts = [System.Collections.Generic.List[String]]::new()
    try {
        $ErrorActionPreference = "Stop"
        Get-LocalUser | Select-Object -ExpandProperty Name | ForEach-Object { $UsersAccounts.Add($_) }
        $ErrorActionPreference = "Continue"
    }
    catch {
        $NetUser = net.exe user
        $(
            $NetUser | Select-Object -Skip 4 | Select-Object -SkipLast 2
            # Join each line with a ","
            # Replace and spaces with a ","
            # Split everything by ","
        ) -join ',' -replace 's+', ',' -split ',' |
            # Sort and remove any duplicates
            Sort-Object -Descending -Unique |
            # Filter out empty strings
            Where-Object { -not [string]::IsNullOrEmpty($_) -and -not [string]::IsNullOrWhiteSpace($_) } |
            ForEach-Object {
                $UsersAccounts.Add($_)
            }
    }
    $Events | Select-Object -ExpandProperty Account | ForEach-Object { $UsersAccounts.Add($_) }

    $Results = $UsersAccounts | Select-Object -Unique | ForEach-Object {
        $Account = $_
        $AccountEvents = $Events | Where-Object { $_.Account -like $Account }
        $AttemptCount = $AccountEvents.Count
        $SourceNetworkAddress = $AccountEvents | Select-Object -ExpandProperty SourceNetworkAddress -Unique
        if ($AttemptCount -gt 0) {
            [PSCustomObject]@{
                Account              = $Account
                Attempts             = $AttemptCount
                SourceNetworkAddress = $SourceNetworkAddress
            }
        }
    }

    # Get only the accounts with fail login attempts at or over $Attempts
    $BruteForceAttempts = $Results | Where-Object { $_.Attempts -ge $Attempts }
    if ($BruteForceAttempts) {
        $BruteForceAttempts | Out-String | Write-Host
        exit 1
    }
    $Results | Out-String | Write-Host
    exit 0
}
end {
    $ScriptVariables = @(
        [PSCustomObject]@{
            name           = "Hours"
            calculatedName = "hours" # Must be lowercase and no spaces
            required       = $false
            defaultValue   = [PSCustomObject]@{ # If not default value, then remove
                type  = "TEXT"
                value = "1"
            }
            valueType      = "TEXT"
            valueList      = $null
            description    = "Number of hours back in time to look through in the event log."
        }
        [PSCustomObject]@{
            name           = "Attempts"
            calculatedName = "attempts" # Must be lowercase and no spaces
            required       = $false
            defaultValue   = [PSCustomObject]@{ # If not default value, then remove
                type  = "TEXT"
                value = "8"
            }
            valueType      = "TEXT"
            valueList      = $null
            description    = "Number of login attempts to trigger at or above this number."
        }
    )
}

 


Accedi a oltre 700 script nel Dojo di NinjaOne Ottieni l’accesso

Comprendere e utilizzare lo script

Il nostro script per rilevare e prevenire gli attacchi brute force si basa su due parametri principali: ‘Ore’ e ‘Tentativi’. Il parametro ‘Ore’ definisce il periodo da esaminare nel registro eventi (per impostazione predefinita è 1 ora). Il parametro ‘Tentativi’ imposta la soglia di tentativi di accesso prima di attivare un avviso (impostazione predefinita: 8 tentativi).

Per installare ed eseguire lo script, procedi come segue:

  1. Accedi a PowerShell con privilegi di amministratore.
  2. Copia lo script per rilevare gli attacchi brute force nell’ambiente PowerShell.
  3. Personalizza i parametri ‘Ore’ e ‘Tentativi’ come desiderato.
  4. Esegui lo script per rilevare gli attacchi brute force.

Lo script per rilevare gli attacchi brute force valuterà quindi i registri eventi in base ai parametri forniti. Se il numero di tentativi di accesso falliti supera la soglia entro l’intervallo di tempo specificato, viene segnalata la possibilità che ci siano attacchi brute force in corso. 

Considera un esempio in cui desideri monitorare i tentativi di accesso nelle ultime tre ore e intendi ricevere un avviso se si verificano più di 15 tentativi falliti. Con NinjaOne, hai la possibilità di personalizzare il tuo approccio alla sicurezza eseguendo lo script per rilevare attacchi brute force con parametri personalizzati come: Ore 3, Tentativi 15. Tale funzionalità consente di adattarsi alle esigenze di sicurezza e ai profili di rischio unici della propria organizzazione.

Misure di sicurezza aggiuntive

Il rilevamento degli attacchi brute force è solo un componente di una strategia olistica di cybersecurity. Altre misure fondamentali sono: 

  1. Password complesse: Incoraggia gli utenti a creare password complesse e uniche, possibilmente un mix di lettere, numeri e simboli. I gestori di password possono facilitare la gestione di password complesse.
  1. Autenticazione a più fattori (MFA): L’MFA fornisce un ulteriore livello di sicurezza, richiedendo agli utenti di verificare la propria identità utilizzando due o più meccanismi (ad esempio, qualcosa che conoscono, qualcosa che hanno o qualcosa che sono).
  1. Aggiornamenti software: L’aggiornamento regolare del software è vitale. Gli aggiornamenti spesso includono patch per le vulnerabilità di sicurezza che, se non risolte, potrebbero aprire una porta agli attacchi informatici.
  1. Formazione dei dipendenti: Stabilire un programma di formazione sulla consapevolezza della sicurezza aiuta a educare i dipendenti sulle minacce informatiche e sul ruolo che svolgono nel mantenimento della sicurezza. Il fattore umano è spesso l’anello più debole della cybersecurity ed i dipendenti ben informati possono rafforzare notevolmente le tue difese.

Considerazioni finali

Un efficace rilevamento di attacchi brute force è fondamentale nell’attuale panorama digitale ed il nostro script PowerShell offre una soluzione potente e personalizzabile. Tuttavia, è essenziale ricordare che rilevare e prevenire gli attacchi brute force è solo un aspetto di una strategia di cybersecurity che deve essere più ampia. Combinando il rilevamento in tempo reale con password complesse, MFA, aggiornamenti software e formazione dei dipendenti, è possibile creare un protocollo di sicurezza completo per proteggere le proprie risorse digitali. 

NinjaOne è uno strumento completo che rafforza in modo significativo la capacità di rilevare e contrastare gli attacchi brute force. Avendo controllo completo sulla sicurezza degli endpoint è possibile gestire le applicazioni, modificare da remoto i registri e distribuire script per migliorare la sicurezza. I controlli di accesso basati sui ruoli assicurano che i tecnici abbiano solo i livelli di accesso necessari, riducendo i potenziali punti di violazione. La piattaforma offre anche strumenti di gestione della crittografia delle unità e la possibilità di installare e gestire automaticamente la protezione degli endpoint, offrendo un controllo granulare sulle operazioni antivirus. 

Inoltre, la funzione di scambio di credenziali di NinjaOne salvaguarda le credenziali ,una linea di difesa importante contro gli attacchi brute force. Al contempo, consente di identificare e rimuovere gli endpoint non autorizzati, aggiungendo un ulteriore livello di protezione. Non aspettare che si verifichi una violazione. Inizia il tuo viaggio verso una maggiore sicurezza oggi stesso con NinjaOne. 

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.

Ti potrebbe interessare anche

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.