elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  [APORTE] [PowerShell] Crear reglas de firewall para bloquear tráfico de direcciones IPv4
0 Usuarios y 5 Visitantes están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [APORTE] [PowerShell] Crear reglas de firewall para bloquear tráfico de direcciones IPv4  (Leído 145 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.843



Ver Perfil
[APORTE] [PowerShell] Crear reglas de firewall para bloquear tráfico de direcciones IPv4
« en: Ayer a las 11:22 »

El siguiente script desarrollado en el lenguaje PowerShell sirve para automatizar la creación de reglas del firewall de Windows para bloquear tráfico de direcciones IPv4.

Las direcciones IPv4 pueden estar definidas en el propio script, o en un archivo de texto local.

En la cabecera del script, se puede asignar el valor apropiado para especificar la ruta de un archivo que contenga direcciones IPv4:
Código:
$ipv4ListFile = "$PSScriptRoot\Ipv4.txt"

Ejemplo del contenido del archivo:
Código:
172.64.149.23
192.229.221.95
20.190.177.85
20.73.194.208

O directamente también se pueden establecer las IPv4 a bloquear, en el siguiente array:
Código:
$ipArray = @()











Block IP addresses.ps1
Código
  1. # Script Version 1.1
  2.  
  3. <#
  4. ===========================================================================================
  5. |                                                                                         |
  6. |                                      User Settings                                      |
  7. |                                                                                         |
  8. ===========================================================================================
  9. #>
  10.  
  11. # Note: The file must contain a single IP address per line.
  12. $ipListFile = "$PSScriptRoot\Ipv4.txt"
  13.  
  14. # Additional IP addresses to block:
  15. $ipArray = @()
  16.  
  17. <#
  18. ===========================================================================================
  19. |                                                                                         |
  20. |                                    Functions                                            |
  21. |                                                                                         |
  22. ===========================================================================================
  23. #>
  24.  
  25. function Show-WelcomeScreen {
  26.    Clear-Host
  27.    Write-Host ""
  28.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  29.    Write-Host " +=======================================+"
  30.    Write-Host " |                                       |"
  31.    Write-Host " | This script will add firewall rules   |"
  32.    Write-Host " | to block network traffic for the IP   |"
  33.    Write-Host " | addresses specified in the input file |"
  34.    Write-Host " | and/or defined in this script file.   |"
  35.    Write-Host " |                                       |"
  36.    Write-Host " +=======================================+"
  37.    Write-Host ""
  38.    Write-Host " Input File Path: $ipListFile" -ForegroundColor DarkGray
  39.    Write-Host ""
  40.    Write-Host " IP addresses hardcoded in this script: $($ipArray.Count)" -ForegroundColor DarkGray
  41.    Write-Host ""
  42. }
  43.  
  44. function Confirm-Continue {
  45.    Write-Host " Press 'Y' key to continue or 'N' key to exit."
  46.    Write-Host ""
  47.    Write-Host " -Continue? (Y/N)"
  48.    do {
  49.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  50.        $char = $key.Character.ToString().ToUpper()
  51.        if ($char -ne "Y" -and $char -ne "N") {
  52.            [console]::beep(1500, 500)
  53.        }
  54.    } while ($char -ne "Y" -and $char -ne "N")
  55.    if ($char -eq "N") {Exit(1)} else {Clear-Host}
  56. }
  57.  
  58. function Show-GoodbyeScreen {
  59.    Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  60.    Write-Host ""
  61.    Write-Host "Press any key to exit..."
  62.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  63. }
  64.  
  65. function Add-FirewallRules {
  66.    param (
  67.        [string]$ipListFile,
  68.        [System.Collections.ArrayList]$ipArray
  69.    )
  70.  
  71.    if (Test-Path $ipListFile) {
  72.        Write-Host "Fetching IP addresses from input file..." -ForegroundColor DarkGray
  73.        Write-Host ""
  74.        $ipArray += Get-Content -Path $ipListFile | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
  75.    }
  76.  
  77.    # Natural Sorting C# Snippet
  78.    Add-Type -TypeDefinition '
  79.        using System;
  80.        using System.Collections;
  81.        using System.Collections.Generic;
  82.        using System.Runtime.InteropServices;
  83.        namespace StringComparers {
  84.            public static class NativeMethods {
  85.                [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
  86.                public static extern int StrCmpLogicalW(string psz1, string psz2);
  87.                public static System.Collections.ArrayList Sort(System.Collections.ArrayList foo) {
  88.                    foo.Sort(new NaturalSortComparer());
  89.                    return foo;
  90.                }
  91.            }
  92.            public class NaturalSortComparer : IComparer {
  93.                public int Compare(object x, object y) {
  94.                    return NativeMethods.StrCmpLogicalW(x.ToString(), y.ToString());
  95.                }
  96.            }
  97.        }'
  98.  
  99.    # Sort items and remove duplicated items.
  100.    $ipArray = $ipArray | Select-Object -Unique
  101.    $naturalSortComparer = New-Object StringComparers.NaturalSortComparer
  102.    $ipArray.Sort($naturalSortComparer)
  103.  
  104.    if ($ipArray.Count -eq 0) {
  105.        Write-Warning "There are no IP addresses to process."
  106.        return
  107.    }
  108.  
  109.    $ruleGroupName = "$env:COMPUTERNAME IP Blocks"
  110.    $currentItemIndex = 0
  111.    $totalItemCount   = $ipArray.Count
  112.  
  113.    foreach ($ip in $ipArray) {
  114.        $currentItemIndex +=1
  115.        Write-Host "[$currentItemIndex of $totalItemCount] IP address: $ip"
  116.  
  117.        $ruleNameInbound = "IP Block (Inbound) ($ip)"
  118.        Write-Host "Adding firewall rule to block inbound traffic..." -ForegroundColor DarkGray
  119.        Get-NetFirewallRule -DisplayName "$ruleNameInbound" -ErrorAction SilentlyContinue | Remove-NetFirewallRule
  120.        [CimInstance]$ruleInbound =
  121.            New-NetFirewallRule `
  122.                -DisplayName "$ruleNameInbound" `
  123.                -Description "This rule disables incoming traffic for address: $ip" `
  124.                -Group "$ruleGroupName" `
  125.                -Direction "Inbound" `
  126.                -Action "Block" `
  127.                -RemoteAddress "$ip" `
  128.                -Profile "Any" `
  129.                -Enabled "True" `
  130.                -LocalAddress "Any" `
  131.                -InterfaceType "Any"
  132.  
  133.        $ruleNameOutbound = "IP Block (Outbound) ($ip)"
  134.        Write-Host "Adding firewall rule to block outbound traffic..." -ForegroundColor DarkGray
  135.        Get-NetFirewallRule -DisplayName "$ruleNameOutbound" -ErrorAction SilentlyContinue | Remove-NetFirewallRule
  136.        [CimInstance]$ruleOutbound =
  137.            New-NetFirewallRule `
  138.                -DisplayName "$ruleNameOutbound" `
  139.                -Description "This rule disables outgoing traffic for address: $ip" `
  140.                -Group "$ruleGroupName" `
  141.                -Direction "Outbound" `
  142.                -Action "Block" `
  143.                -RemoteAddress "$ip" `
  144.                -Profile "Any" `
  145.                -Enabled "True" `
  146.                -LocalAddress "Any" `
  147.                -InterfaceType "Any"
  148.  
  149.        Write-Host ""
  150.    }
  151. }
  152.  
  153. <#
  154. ===========================================================================================
  155. |                                                                                         |
  156. |                                         Main                                            |
  157. |                                                                                         |
  158. ===========================================================================================
  159. #>
  160.  
  161. [System.Console]::Title = "Block IP addresses - by Elektro"
  162. [CultureInfo]::CurrentUICulture = "en-US"
  163.  
  164. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  165.  
  166. Show-WelcomeScreen
  167. Confirm-Continue
  168. Add-FirewallRules -ipListFile $ipListFile -ipArray $ipArray
  169. Show-GoodbyeScreen
  170. Exit(0)



Notas:

 - Probado en Windows 10 (PowerShell 5.1.19041.1682). Debería funcionar igual en Windows 11.

EDITADO: Script actualizado. Al final he decidido utilizar el cmdlet New-NetFirewallRule a pesar de los inconvenientes, por que entiendo que así será más compatible y útil para más gente.


« Última modificación: Ayer a las 21:17 por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines