Detecting and Preventing Brute Force Attacks with PowerShell

While cyber threats are certainly continuously evolving, the fact is most intrusions still rely on basic, tried-and-true techniques. Who needs to burn a zero-day if guessing commonly used passwords or exploiting passwords used across multiple accounts can give you easy access?

Brute force attacks continue to be an incredibly common threat that organizations face. Detecting and blocking these attempts as quickly as possible is critical, as they’re often early harbingers of more damaging activities and malicious access attempts to come. Because every minute counts in these situations, setting up account lockout policies and real-time alerting for failed login attempts is an extremely important early deterrent and warning measure.

But what about detecting brute force attacks remotely and at scale across an entire corporate network?

Because that can be a challenge, we’ve provided the following script that admins can use to automate the process, monitoring for failed login attempts and triggering alerts based on customizable thresholds.

Brute Force Attack Detection and Prevention Script

#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."
        }
    )
}

 


Access over 300+ scripts in the NinjaOne Dojo

Get Access

Understanding and Using the Script

Our script hinges on two primary parameters: `-Hours` and `-Attempts`. The `-Hours` parameter dictates the period to review in the event log (defaulting to 1 hour). The `-Attempts` parameter sets the threshold for login attempts before triggering an alert (default set to 8 attempts).

To install and run the script, follow these steps:

  1. Open PowerShell with Administrator privileges.
  2. Copy the script into your PowerShell environment.
  3. Customize the `-Hours` and `-Attempts` parameters as needed.
  4. Run the script.

The script will then evaluate the event logs based on the parameters provided. If the number of failed login attempts surpasses the threshold within the specified timeframe, it will alert you to a potential brute force attack.

Consider an example where you want to monitor login attempts over the last three hours and want an alert if there are more than 15 failed attempts. With NinjaOne, you have the flexibility to customize your security approach by running the script with tailored parameters like -Hours 3 -Attempts 15. This feature enables you to adapt to the unique security needs and risk profiles of your organization.

Additional Security Measures

Brute force attack detection is just one component of a holistic cybersecurity strategy. Other crucial measures include:

  • Strong passwords: Encourage users to create robust, unique passwords—ideally a mix of letters, numbers, and symbols. Password managers can facilitate the management of complex passwords.
  • Multi-factor authentication (MFA): MFA provides an additional layer of security, requiring users to verify their identity using two or more mechanisms (e.g., something they know, something they have, or something they are).
  • Software updates: Regularly updating software is vital. Updates often include patches for security vulnerabilities, which, if left unaddressed, could provide an open door for cyber-attacks.
  • Employee training: Establishing a security awareness training program helps educate employees about cyber threats and the role they play in maintaining security. The human factor is often the weakest link in cybersecurity, and well-informed employees can significantly bolster your defenses.

Final Thoughts

Effective brute force detection is crucial in the current digital landscape, and our PowerShell script offers a potent, customizable solution. However, it’s essential to remember that it forms part of a broader cybersecurity strategy. By combining real-time detection with strong passwords, MFA, software updates, and employee training, you can create a comprehensive security protocol to protect your digital assets.

NinjaOne is a comprehensive tool that significantly bolsters your ability to detect and counteract brute force attacks. With complete control over endpoint security, you can manage applications, remotely edit registries, and deploy scripts to enhance security. Role-Based Access Controls ensure your technicians only have the necessary levels of access, reducing potential breach points. The platform also offers drive encryption management tools and the ability to automatically install and manage endpoint protection, giving you granular control over antivirus operations.

Moreover, NinjaOne’s credential exchange feature safeguards credentials, a critical line of defense against brute force attacks. It also allows for the identification and removal of rogue endpoints, adding an extra layer of protection. Don’t wait for a breach to happen. Start your journey to enhanced security today with NinjaOne.

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

×

See NinjaOne in action!

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

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).