{"id":208611,"date":"2024-01-18T14:11:19","date_gmt":"2024-01-18T14:11:19","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/detectar-ataques-de-fuerza-bruta\/"},"modified":"2024-03-04T16:45:16","modified_gmt":"2024-03-04T16:45:16","slug":"detectar-ataques-de-fuerza-bruta","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/es\/script-hub\/detectar-ataques-de-fuerza-bruta\/","title":{"rendered":"Detectar y prevenir ataques de fuerza bruta con PowerShell"},"content":{"rendered":"<p>Aunque no cabe duda de que las ciberamenazas evolucionan continuamente, lo cierto es que la mayor\u00eda de las intrusiones siguen bas\u00e1ndose en t\u00e9cnicas b\u00e1sicas de probada eficacia. \u00bfSi adivinar contrase\u00f1as de uso com\u00fan o explotar contrase\u00f1as utilizadas en varias cuentas puede facilitarte el acceso, qui\u00e9n necesita organizar un ataque de d\u00eda cero?<\/p>\n<p>Los ataques de fuerza bruta siguen siendo una amenaza incre\u00edblemente com\u00fan a la que se enfrentan las organizaciones. Detectar y bloquear estos ataques de fuerza bruta lo antes posible es fundamental, ya que a menudo son precursores de actividades m\u00e1s da\u00f1inas e intentos de acceso malintencionados. Dado que cada minuto cuenta en estas situaciones, establecer pol\u00edticas de bloqueo de cuentas y alertas en tiempo real para los intentos fallidos de inicio de sesi\u00f3n es una medida disuasoria y de alerta temprana important\u00edsima.<\/p>\n<p>Pero, \u00bfqu\u00e9 ocurre con la <strong>detecci\u00f3n de ataques de fuerza bruta<\/strong> en toda una red corporativa, a distancia y gran a escala?<\/p>\n<p>Detectar y prevenir ataques de fuerza bruta en un contexto como este puede suponer un reto, por eso compartimos el siguiente script que los administradores pueden utilizar para automatizar el proceso, <a href=\"https:\/\/www.ninjaone.com\/blog\/find-failed-login-attempts-windows-powershell\/\">supervisando los intentos fallidos de inicio de sesi\u00f3n<\/a> y activando alertas basadas en umbrales personalizables.<\/p>\n<h2>Script para detectar y prevenir los ataques de fuerza bruta<\/h2>\n<p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Condition for helping detect brute force login attempts.\r\n.DESCRIPTION\r\n    Condition for helping detect brute force login attempts.\r\n.EXAMPLE\r\n     -Hours 10\r\n    Number of hours back in time to look through in the event log.\r\n    Default is 1 hour.\r\n.EXAMPLE\r\n    -Attempts 100\r\n    Number of login attempts to trigger at or above this number.\r\n    Default is 8 attempts.\r\n.OUTPUTS\r\n    PSCustomObject[]\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows 10, Windows Server 2016\r\n    Release Notes:\r\n    Initial Release\r\nBy 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.\r\n    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. \r\n    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. \r\n    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. \r\n    Warranty Disclaimer: The script is provided \u201cas is\u201d and \u201cas available\u201d, 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. \r\n    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. \r\n    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. \r\n    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).\r\n#&gt;\r\n\r\n[CmdletBinding()]\r\nparam (\r\n    [Parameter()]\r\n    [int]\r\n    $Hours = 1,\r\n    [Parameter()]\r\n    [int]\r\n    $Attempts = 8\r\n)\r\n\r\nbegin {\r\n    function Test-IsElevated {\r\n        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()\r\n        $p = New-Object System.Security.Principal.WindowsPrincipal($id)\r\n        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)\r\n    }\r\n    function Test-StringEmpty {\r\n        param([string]$Text)\r\n        # Returns true if string is empty, null, or whitespace\r\n        process { [string]::IsNullOrEmpty($Text) -or [string]::IsNullOrWhiteSpace($Text) }\r\n    }\r\n    if (-not $(Test-StringEmpty -Text $env:Hours)) {\r\n        $Hours = $env:Hours\r\n    }\r\n    if (-not $(Test-StringEmpty -Text $env:Attempts)) {\r\n        $Attempts = $env:Attempts\r\n    }\r\n}\r\nprocess {\r\n    if (-not (Test-IsElevated)) {\r\n        Write-Error -Message \"Access Denied. Please run with Administrator privileges.\"\r\n        exit 1\r\n    }\r\n\r\n    if ($(auditpol.exe \/get \/category:* | Where-Object { $_ -like \"*Logon*Success and Failure\" })) {\r\n        Write-Information \"Audit Policy for Logon is set to: Success and Failure\"\r\n    }\r\n    else {\r\n        Write-Error \"Audit Policy for Logon is NOT set to: Success and Failure\"\r\n        exit 1\r\n        # Write-Host \"Setting Logon to: Success and Failure\"\r\n        # auditpol.exe \/set \/subcategory:\"Logon\" \/success:enable \/failure:enable\r\n        # Write-Host \"Future failed login attempts will be captured.\"\r\n    }\r\n\r\n    $StartTime = (Get-Date).AddHours(0 - $Hours)\r\n    $EventId = 4625\r\n\r\n    # Get failed login attempts\r\n    try {\r\n        $Events = Get-WinEvent -FilterHashtable @{LogName = \"Security\"; ID = $EventId; StartTime = $StartTime } -ErrorAction Stop | ForEach-Object {\r\n            $Message = $_.Message -split [System.Environment]::NewLine\r\n            $Account = $($Message | Where-Object { $_ -Like \"*Account Name:*\" }) -split 's+' | Select-Object -Last 1\r\n            [int]$LogonType = $($Message | Where-Object { $_ -Like \"Logon Type:*\" }) -split 's+' | Select-Object -Last 1\r\n            $SourceNetworkAddress = $($Message | Where-Object { $_ -Like \"*Source Network Address:*\" }) -split 's+' | Select-Object -Last 1\r\n            [PSCustomObject]@{\r\n                Account              = $Account\r\n                LogonType            = $LogonType\r\n                SourceNetworkAddress = $SourceNetworkAddress\r\n            }\r\n        } | Where-Object { $_.LogonType -in @(2, 7, 10) }\r\n    }\r\n    catch {\r\n        if ($_.Exception.Message -like \"No events were found that match the specified selection criteria.\") {\r\n            Write-Host \"No failed logins found in the past $Hours hour(s).\"\r\n            exit 0\r\n        }\r\n        else {\r\n            Write-Error $_\r\n            exit 1\r\n        }\r\n    }\r\n\r\n    # Build a list of accounts \r\n    $UsersAccounts = [System.Collections.Generic.List[String]]::new()\r\n    try {\r\n        $ErrorActionPreference = \"Stop\"\r\n        Get-LocalUser | Select-Object -ExpandProperty Name | ForEach-Object { $UsersAccounts.Add($_) }\r\n        $ErrorActionPreference = \"Continue\"\r\n    }\r\n    catch {\r\n        $NetUser = net.exe user\r\n        $(\r\n            $NetUser | Select-Object -Skip 4 | Select-Object -SkipLast 2\r\n            # Join each line with a \",\"\r\n            # Replace and spaces with a \",\"\r\n            # Split everything by \",\"\r\n        ) -join ',' -replace 's+', ',' -split ',' |\r\n            # Sort and remove any duplicates\r\n            Sort-Object -Descending -Unique |\r\n            # Filter out empty strings\r\n            Where-Object { -not [string]::IsNullOrEmpty($_) -and -not [string]::IsNullOrWhiteSpace($_) } |\r\n            ForEach-Object {\r\n                $UsersAccounts.Add($_)\r\n            }\r\n    }\r\n    $Events | Select-Object -ExpandProperty Account | ForEach-Object { $UsersAccounts.Add($_) }\r\n\r\n    $Results = $UsersAccounts | Select-Object -Unique | ForEach-Object {\r\n        $Account = $_\r\n        $AccountEvents = $Events | Where-Object { $_.Account -like $Account }\r\n        $AttemptCount = $AccountEvents.Count\r\n        $SourceNetworkAddress = $AccountEvents | Select-Object -ExpandProperty SourceNetworkAddress -Unique\r\n        if ($AttemptCount -gt 0) {\r\n            [PSCustomObject]@{\r\n                Account              = $Account\r\n                Attempts             = $AttemptCount\r\n                SourceNetworkAddress = $SourceNetworkAddress\r\n            }\r\n        }\r\n    }\r\n\r\n    # Get only the accounts with fail login attempts at or over $Attempts\r\n    $BruteForceAttempts = $Results | Where-Object { $_.Attempts -ge $Attempts }\r\n    if ($BruteForceAttempts) {\r\n        $BruteForceAttempts | Out-String | Write-Host\r\n        exit 1\r\n    }\r\n    $Results | Out-String | Write-Host\r\n    exit 0\r\n}\r\nend {\r\n    $ScriptVariables = @(\r\n        [PSCustomObject]@{\r\n            name           = \"Hours\"\r\n            calculatedName = \"hours\" # Must be lowercase and no spaces\r\n            required       = $false\r\n            defaultValue   = [PSCustomObject]@{ # If not default value, then remove\r\n                type  = \"TEXT\"\r\n                value = \"1\"\r\n            }\r\n            valueType      = \"TEXT\"\r\n            valueList      = $null\r\n            description    = \"Number of hours back in time to look through in the event log.\"\r\n        }\r\n        [PSCustomObject]@{\r\n            name           = \"Attempts\"\r\n            calculatedName = \"attempts\" # Must be lowercase and no spaces\r\n            required       = $false\r\n            defaultValue   = [PSCustomObject]@{ # If not default value, then remove\r\n                type  = \"TEXT\"\r\n                value = \"8\"\r\n            }\r\n            valueType      = \"TEXT\"\r\n            valueList      = $null\r\n            description    = \"Number of login attempts to trigger at or above this number.\"\r\n        }\r\n    )\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<br \/>\n<div class=\"in-context-cta\"><p>Accede a m\u00e1s de 300 scripts en el Dojo de NinjaOne<\/p>\n<p><a href=\"https:\/\/www.ninjaone.com\/es\/prueba-gratuita-formulario\/\">Obt\u00e9n acceso<\/a><\/p>\n<\/div><\/p>\n<h2>Comprender y utilizar el script para detectar y prevenir los ataques de fuerza bruta<\/h2>\n<p>Nuestro script para detectar y prevenir los ataques de fuerza bruta se basa en dos par\u00e1metros principales: `Horas` e `Intentos`. El par\u00e1metro `Horas` define el periodo a revisar en el registro de eventos (por defecto 1 hora). El par\u00e1metro `Intentos` establece el umbral de intentos de inicio de sesi\u00f3n antes de activar una alerta (por defecto se establece en 8 intentos).<\/p>\n<h3>Para instalar y ejecutar el script contra los ataques de fuerza bruta, sigue estos pasos:<\/h3>\n<ol>\n<li>Abre PowerShell con privilegios de administrador.<\/li>\n<li>Copia el script en tu entorno PowerShell.<\/li>\n<li>Personaliza los par\u00e1metros \u00abHoras\u00bb e \u00abIntentos\u00bb seg\u00fan sea necesario.<\/li>\n<li>Ejecuta el script.<\/li>\n<\/ol>\n<p>A continuaci\u00f3n, el script para detectar y prevenir los ataques de fuerza bruta evaluar\u00e1 los registros de eventos en funci\u00f3n de los par\u00e1metros proporcionados. Si el n\u00famero de intentos fallidos de inicio de sesi\u00f3n supera el umbral dentro del plazo especificado, te alertar\u00e1 de un posible ataque de fuerza bruta.<\/p>\n<p>Imag\u00ednate que quieres supervisar los intentos de inicio de sesi\u00f3n durante las \u00faltimas tres horas y te gustar\u00eda recibir una alerta si hay m\u00e1s de 15 intentos fallidos. Con NinjaOne, tienes la flexibilidad de personalizar tu enfoque de seguridad mediante la ejecuci\u00f3n del script con par\u00e1metros a medida como \u00abHoras 3\u00bb, \u00abIntentos 15\u00bb. Esta funci\u00f3n te permite adaptarte a las necesidades de seguridad y a los perfiles de riesgo espec\u00edficos de tu organizaci\u00f3n.<\/p>\n<h2>Medidas de seguridad adicionales<\/h2>\n<p>La detecci\u00f3n de ataques de fuerza bruta es s\u00f3lo un componente de una estrategia global de ciberseguridad. Otras medidas fundamentales son:<\/p>\n<ul>\n<li><strong>Contrase\u00f1as seguras:<\/strong> anima a los usuarios a crear contrase\u00f1as robustas y \u00fanicas, idealmente una mezcla de letras, n\u00fameros y s\u00edmbolos. Los gestores de contrase\u00f1as pueden facilitar la <a href=\"https:\/\/www.ninjaone.com\/blog\/secure-msp-credentials-password-management\/\">gesti\u00f3n de contrase\u00f1as complejas<\/a>.<\/li>\n<li><strong>Autenticaci\u00f3n multifactor (MFA):<\/strong> la MFA proporciona una capa adicional de seguridad, exigiendo a los usuarios que verifiquen su identidad utilizando dos o m\u00e1s mecanismos (por ejemplo, algo que saben, algo que tienen o algo que son).<\/li>\n<li><strong>Actualizaciones de software:<\/strong> la actualizaci\u00f3n peri\u00f3dica del software es vital. Las actualizaciones suelen incluir <a href=\"https:\/\/www.ninjaone.com\/es\/gestion-de-parches\/\">parches para vulnerabilidades de seguridad<\/a> que, si no se solucionan, podr\u00edan abrir una puerta a los ciberataques.<\/li>\n<li><strong>Formaci\u00f3n de los empleados<\/strong>: establecer un programa de formaci\u00f3n para la concienciaci\u00f3n sobre la seguridad ayuda a educar a los empleados sobre las ciberamenazas y el papel que desempe\u00f1an en el mantenimiento de la seguridad. El factor humano suele ser el eslab\u00f3n m\u00e1s d\u00e9bil de la ciberseguridad, y unos empleados bien informados pueden reforzar considerablemente sus defensas.<\/li>\n<\/ul>\n<h2>Reflexiones finales<\/h2>\n<p>Una detecci\u00f3n eficaz de ataques de fuerza bruta es fundamental en el panorama digital actual y nuestro script PowerShell ofrece una soluci\u00f3n potente y personalizable. Sin embargo, es esencial recordar que forma parte de una estrategia de ciberseguridad m\u00e1s amplia. Combinando la detecci\u00f3n en tiempo real con contrase\u00f1as seguras, MFA, actualizaciones de software y formaci\u00f3n de los empleados, puedes crear un protocolo de seguridad completo para proteger tus activos digitales.<\/p>\n<p>NinjaOne es una herramienta completa que refuerza significativamente tu capacidad para detectar y contrarrestar los ataques de fuerza bruta. Con <a href=\"https:\/\/www.ninjaone.com\/es\/rmm\/seguridad-endpoint\/\">un control total sobre la seguridad de los endpoints<\/a>, puedes gestionar aplicaciones, editar registros de forma remota e implantar scripts para mejorar la seguridad. Los controles de acceso basados en funciones garantizan que tus t\u00e9cnicos s\u00f3lo tengan los niveles de acceso necesarios, lo que reduce los posibles puntos de infracci\u00f3n. La plataforma tambi\u00e9n ofrece herramientas de gesti\u00f3n del cifrado de unidades y la posibilidad de instalar y gestionar autom\u00e1ticamente la protecci\u00f3n de los endpoints, lo que permite un control granular de las operaciones antivirus.<\/p>\n<p>Adem\u00e1s, la <a href=\"https:\/\/www.ninjaone.com\/es\/rmm\/gestor-de-contrasenas\/\">funci\u00f3n de intercambio de credenciales de NinjaOne protege las credenciales<\/a>, una l\u00ednea de defensa fundamental contra los ataques de fuerza bruta. Tambi\u00e9n permite identificar y eliminar los endpoints no autorizados, lo que a\u00f1ade una capa adicional de protecci\u00f3n. No esperes a que se produzca una infracci\u00f3n. <a href=\"https:\/\/www.ninjaone.com\/es\/prueba-gratuita-formulario\">Comienza tu viaje hacia una mayor seguridad<\/a> hoy mismo con NinjaOne.<\/p>\n","protected":false},"author":35,"featured_media":206805,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_acf_changed":false,"_relevanssi_hide_post":"","_relevanssi_hide_content":"","_relevanssi_pin_for_all":"","_relevanssi_pin_keywords":"","_relevanssi_unpin_keywords":"","_relevanssi_related_keywords":"","_relevanssi_related_include_ids":"","_relevanssi_related_exclude_ids":"","_relevanssi_related_no_append":"","_relevanssi_related_not_related":"","_relevanssi_related_posts":"","_relevanssi_noindex_reason":"","_lmt_disableupdate":"no","_lmt_disable":""},"operating_system":[4212],"use_cases":[4259],"class_list":["post-208611","script_hub","type-script_hub","status-publish","has-post-thumbnail","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub\/208611","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/comments?post=208611"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media\/206805"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media?parent=208611"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/operating_system?post=208611"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/use_cases?post=208611"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}