con Seguridad Avanzada
Windows Firewall with Advanced Security (WFwAS) es el firewall integrado en Windows desde Vista/Server 2008. Mucho más potente que su nombre sugiere: soporta reglas por aplicación, usuario, servicio, interfaz, protocolo y puerto, con integración nativa con IPsec y Active Directory.
Lo que puede hacer WFwAS
Formas de Acceder
# GUI completa (con reglas avanzadas) wf.msc # Panel de control básico firewall.cpl # Desde PowerShell — ver estado del firewall Get-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundAction, DefaultOutboundAction Name Enabled DefaultInboundAction DefaultOutboundAction ---- ------- -------------------- --------------------- Domain True Block Allow Private True Block Allow Public True Block Allow # Desde netsh netsh advfirewall show allprofiles
WFwAS aplica automáticamente el perfil correcto según la red detectada. Cada perfil tiene su propio conjunto de reglas e independencia total.
# Ver configuración detallada de todos los perfiles Get-NetFirewallProfile | Format-List # Configurar perfil Público como más restrictivo Set-NetFirewallProfile -Profile Public ` -Enabled True ` -DefaultInboundAction Block ` -DefaultOutboundAction Block ` -AllowInboundRules False ` -NotifyOnListen True ` -LogAllowed False ` -LogBlocked True ` -LogFileName "C:\Windows\System32\LogFiles\Firewall\pfirewall.log" # Activar el firewall en todos los perfiles Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True # Ver qué perfil está activo en cada interfaz de red Get-NetConnectionProfile | Select-Object InterfaceAlias, NetworkCategory, IPv4Connectivity InterfaceAlias NetworkCategory IPv4Connectivity -------------- --------------- ---------------- Ethernet DomainAuthenticated Internet ← Perfil Dominio activo Wi-Fi Public Internet ← Perfil Público activo # Cambiar categoría de red (con cuidado — requiere permisos de admin) Set-NetConnectionProfile -InterfaceAlias "Wi-Fi" -NetworkCategory Private
Entender en qué orden evalúa WFwAS las reglas es crítico para diagnóstico y diseño de políticas. Las reglas se evalúan por prioridad y la primera coincidencia gana.
Orden de Evaluación de Reglas
Prioridad de Reglas GPO vs Local
| Origen | Prioridad | Cuándo se aplica |
|---|---|---|
| Reglas GPO (Dominio) | Más alta | Siempre que el equipo esté en dominio. No pueden ser sobrescritas localmente. |
| Reglas locales (wf.msc) | Media | Se aplican si no hay GPO que las contradiga. |
| Reglas de aplicación | Baja | Generadas automáticamente cuando una aplicación solicita acceso. |
La consola wf.msc es la forma más visual de crear y gestionar reglas. Ideal para entender todos los parámetros disponibles antes de automatizar con PowerShell.
Anatomía de una Regla de Firewall
192.168.0.0/16
Parámetros Disponibles en una Regla
| Pestaña | Parámetros | Descripción |
|---|---|---|
| General | Nombre, descripción, acción | Permitir, Bloquear, Permitir si seguro (IPsec) |
| Programas y servicios | Ruta del ejecutable, servicio | Limitar la regla a una aplicación o servicio específico |
| Protocolos y puertos | TCP/UDP/ICMP, puertos | Puerto local, remoto, tipo ICMP |
| Ámbito | IP local, IP remota | Rangos CIDR, subredes, listas de IPs |
| Avanzado | Perfil, tipo de interfaz, borde | Aplicar solo a Wi-Fi, Ethernet o ambas |
| Usuarios | Cuenta de usuario, grupo AD | Aplicar la regla solo a usuarios específicos |
Crear una Regla desde la GUI paso a paso
wf.msc → Panel izquierdo → "Reglas de entrada" o "Reglas de salida" → Acción → Nueva regla. Elegir el tipo: Puerto, Programa, Predefinida o Personalizada.netsh es la forma clásica de gestionar el firewall desde la línea de comandos. Disponible en todas las versiones de Windows, sin necesidad de PowerShell.
## VER ESTADO Y REGLAS # Estado de todos los perfiles netsh advfirewall show allprofiles # Listar todas las reglas netsh advfirewall firewall show rule name=all # Listar reglas de entrada habilitadas netsh advfirewall firewall show rule name=all dir=in enable=yes # Buscar regla por nombre netsh advfirewall firewall show rule name="Remote Desktop" ## CREAR REGLAS # Permitir puerto TCP 8080 entrante netsh advfirewall firewall add rule ^ name="Servidor App 8080" ^ dir=in action=allow protocol=TCP localport=8080 ^ profile=domain,private enable=yes # Permitir programa específico netsh advfirewall firewall add rule ^ name="Servidor Python" ^ dir=in action=allow protocol=TCP ^ program="C:\Python311\python.exe" ^ enable=yes # Bloquear IP de origen específica netsh advfirewall firewall add rule ^ name="Bloquear IP sospechosa" ^ dir=in action=block ^ remoteip=192.168.100.50 ^ enable=yes # Bloquear todo el tráfico saliente UDP netsh advfirewall firewall add rule ^ name="Bloquear UDP saliente" ^ dir=out action=block protocol=UDP ^ profile=public enable=yes ## MODIFICAR REGLAS netsh advfirewall firewall set rule name="Servidor App 8080" new action=block netsh advfirewall firewall set rule name="Servidor App 8080" new enable=no ## ELIMINAR REGLAS netsh advfirewall firewall delete rule name="Servidor App 8080" ## CONFIGURAR PERFILES netsh advfirewall set publicprofile firewallpolicy blockinbound,blockoutbound netsh advfirewall set domainprofile firewallpolicy blockinbound,allowoutbound ## EXPORTAR E IMPORTAR CONFIGURACIÓN netsh advfirewall export "C:\backup\firewall_backup.wfw" netsh advfirewall import "C:\backup\firewall_backup.wfw" ## RESETEAR A CONFIGURACIÓN PREDETERMINADA netsh advfirewall reset
El módulo NetSecurity de PowerShell ofrece los cmdlets más potentes y expresivos para gestionar WFwAS. Es la forma recomendada para scripting y automatización moderna.
## MÓDULO NETSECURITY — CMDLETS PRINCIPALES Get-Command -Module NetSecurity | Select-Object Name Get-NetFirewallRule New-NetFirewallRule Set-NetFirewallRule Remove-NetFirewallRule Enable-NetFirewallRule Disable-NetFirewallRule Get-NetFirewallProfile Set-NetFirewallProfile Get-NetFirewallPortFilter Get-NetFirewallAddressFilter Get-NetFirewallApplicationFilter ## VER REGLAS # Listar todas las reglas habilitadas Get-NetFirewallRule -Enabled True | Select-Object DisplayName, Direction, Action, Profile # Buscar reglas por puerto — combinando cmdlets Get-NetFirewallRule | Where-Object {$_.Direction -eq "Inbound" -and $_.Action -eq "Allow"} | Get-NetFirewallPortFilter | Where-Object {$_.LocalPort -eq "3389"} | ForEach-Object { Get-NetFirewallRule -AssociatedNetFirewallPortFilter $_ } | Select-Object DisplayName, Enabled, Profile ## CREAR REGLAS # Regla de entrada básica — puerto TCP New-NetFirewallRule -DisplayName "Servidor Web HTTP" ` -Direction Inbound ` -Action Allow ` -Protocol TCP ` -LocalPort 80 ` -Profile Domain,Private ` -Enabled True ` -Description "Permite tráfico HTTP al servidor web interno" # Regla para aplicación específica New-NetFirewallRule -DisplayName "Servidor Python Flask" ` -Direction Inbound ` -Action Allow ` -Protocol TCP ` -LocalPort 5000 ` -Program "C:\Python311\python.exe" ` -Profile Domain ` -Enabled True # Regla con IP remota específica (solo permite desde intranet) New-NetFirewallRule -DisplayName "SSH solo desde LAN" ` -Direction Inbound ` -Action Allow ` -Protocol TCP ` -LocalPort 22 ` -RemoteAddress 10.0.0.0/8,192.168.0.0/16,172.16.0.0/12 ` -Profile Domain,Private ` -Enabled True # Regla de SALIDA — bloquear puerto específico New-NetFirewallRule -DisplayName "Bloquear Telnet saliente" ` -Direction Outbound ` -Action Block ` -Protocol TCP ` -RemotePort 23 ` -Profile Any ` -Enabled True ## MODIFICAR, HABILITAR Y DESHABILITAR Set-NetFirewallRule -DisplayName "Servidor Web HTTP" -Action Block Disable-NetFirewallRule -DisplayName "Servidor Web HTTP" Enable-NetFirewallRule -DisplayName "Servidor Web HTTP" ## ELIMINAR REGLAS Remove-NetFirewallRule -DisplayName "Servidor Web HTTP" Remove-NetFirewallRule -DisplayGroup "Compartir archivos e impresoras"
Las Group Policy Objects permiten desplegar reglas de firewall a todos los equipos del dominio desde un único punto. Es la forma estándar de gestionar el firewall en entornos empresariales.
# Requisito: módulo GroupPolicy instalado en el DC Import-Module GroupPolicy # Crear nueva GPO de firewall New-GPO -Name "Firewall-Servers-Policy" -Domain "corp.local" # Vinculada a una OU específica New-GPLink -Name "Firewall-Servers-Policy" -Target "OU=Servers,DC=corp,DC=local" # Modificar GPO — ruta en GPMC: # Configuración equipo → Configuración Windows → Configuración seguridad # → Firewall de Windows con seguridad avanzada # Forzar actualización de GPO en todos los equipos del dominio Invoke-GPUpdate -Computer "CORP-WEB01" -Force # Ver resultado de GPO aplicada en un equipo Invoke-Command -ComputerName CORP-WEB01 { Get-NetFirewallRule | Where-Object {$_.PolicyStoreSourceType -eq "GroupPolicy"} } # Script: desplegar regla de firewall a múltiples equipos via PS Remoting $servers = @("SRV01", "SRV02", "SRV03", "WEB01") Invoke-Command -ComputerName $servers -ScriptBlock { New-NetFirewallRule -DisplayName "Monitoring Agent" ` -Direction Inbound -Action Allow ` -Protocol TCP -LocalPort 9182 ` -RemoteAddress 10.0.50.0/24 ` -Profile Domain -Enabled True Write-Host "[+] Regla aplicada en $env:COMPUTERNAME" }
gpresult /h report.html muestra qué GPOs están aplicadas.Las reglas de entrada controlan qué conexiones pueden iniciarse desde el exterior hacia el equipo. Son las más críticas para la seguridad: una regla de entrada permisiva puede abrir un vector de ataque.
Reglas de Entrada Esenciales por Rol
## SERVIDOR WEB (IIS / Apache) New-NetFirewallRule -DisplayName "HTTP Inbound" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 80 -Profile Domain,Private -Enabled True New-NetFirewallRule -DisplayName "HTTPS Inbound" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 443 -Profile Domain,Private -Enabled True ## SERVIDOR SQL (acceso solo desde red interna) New-NetFirewallRule -DisplayName "SQL Server" ` -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433 ` -RemoteAddress 10.0.0.0/8 ` -Profile Domain -Enabled True ## RDP — Solo desde subredes de gestión New-NetFirewallRule -DisplayName "RDP Admin Only" ` -Direction Inbound -Action Allow -Protocol TCP -LocalPort 3389 ` -RemoteAddress 10.0.50.0/24 ` -Profile Domain -Enabled True ## PING / ICMP — permitir solo en red interna New-NetFirewallRule -DisplayName "ICMP Echo interno" ` -Direction Inbound -Action Allow ` -Protocol ICMPv4 -IcmpType 8 ` -RemoteAddress 10.0.0.0/8,192.168.0.0/16 ` -Profile Domain,Private -Enabled True ## WinRM — Gestión remota PS Enable-PSRemoting -Force # Limitar a subredes de gestión Set-NetFirewallRule -DisplayName "Windows Remote Management (HTTP-In)" ` -RemoteAddress 10.0.50.0/24 ## Ver qué puertos están actualmente escuchando Get-NetTCPConnection -State Listen | Select-Object LocalAddress, LocalPort | Sort-Object LocalPort | Format-Table
Las reglas de salida son frecuentemente ignoradas, pero son críticas para defensa en profundidad. Controlar qué puede salir de un sistema limita el daño en caso de compromiso: un proceso malicioso no puede llamar a casa si el puerto está bloqueado.
## ESTRATEGIA: Bloquear todo saliente por defecto, luego permitir lo necesario # Paso 1: Cambiar la política predeterminada de salida a Bloquear Set-NetFirewallProfile -Profile Domain,Private,Public ` -DefaultOutboundAction Block # Paso 2: Permitir solo lo necesario # DNS (consultas) New-NetFirewallRule -DisplayName "DNS saliente" -Direction Outbound -Action Allow -Protocol UDP -RemotePort 53 -Enabled True # HTTP y HTTPS (actualizaciones, APIs) New-NetFirewallRule -DisplayName "HTTP saliente" -Direction Outbound -Action Allow -Protocol TCP -RemotePort 80 -Enabled True New-NetFirewallRule -DisplayName "HTTPS saliente" -Direction Outbound -Action Allow -Protocol TCP -RemotePort 443 -Enabled True # NTP (sincronización horaria) New-NetFirewallRule -DisplayName "NTP saliente" -Direction Outbound -Action Allow -Protocol UDP -RemotePort 123 -Enabled True # SMTP (si el servidor envía correos) New-NetFirewallRule -DisplayName "SMTP saliente" -Direction Outbound -Action Allow -Protocol TCP -RemotePort 587 -Enabled True # Comunicación con DC (Kerberos, LDAP, etc.) New-NetFirewallRule -DisplayName "AD saliente" ` -Direction Outbound -Action Allow -Protocol TCP ` -RemotePort 88,389,445,636,3268,3269 ` -RemoteAddress 10.0.0.5,10.0.0.6 ` -Enabled True ## BLOQUEAR PUERTOS PELIGROSOS — aunque la política sea "Permitir" # Bloquear conexiones salientes a puertos típicos de C2 New-NetFirewallRule -DisplayName "Bloquear IRC (C2)" -Direction Outbound -Action Block -Protocol TCP -RemotePort 6667,6668,6669 -Enabled True New-NetFirewallRule -DisplayName "Bloquear Telnet saliente" -Direction Outbound -Action Block -Protocol TCP -RemotePort 23 -Enabled True ## Permitir solo a ciertos programas acceso a Internet New-NetFirewallRule -DisplayName "Chrome HTTPS" ` -Direction Outbound -Action Allow -Protocol TCP -RemotePort 443 ` -Program "C:\Program Files\Google\Chrome\Application\chrome.exe" ` -Enabled True
Las reglas de seguridad de conexión van más allá del filtrado de puertos: cifran y autentican el tráfico entre equipos usando IPsec. Útiles en entornos de alta seguridad.
# Requerir autenticación entre servidores de la misma zona New-NetIPsecRule -DisplayName "IPsec entre servidores" ` -InboundSecurity Require ` -OutboundSecurity Request ` -LocalAddress 10.0.10.0/24 ` -RemoteAddress 10.0.10.0/24 # Requerir cifrado de tráfico sensible (BD → Aplicación) New-NetIPsecRule -DisplayName "Cifrado BD-APP" ` -InboundSecurity Require ` -OutboundSecurity Require ` -LocalAddress 10.0.10.20 ` # Servidor BD -RemoteAddress 10.0.10.10 # Servidor App # Ver reglas de seguridad activas Get-NetIPsecRule | Select-Object DisplayName, Enabled, InboundSecurity, OutboundSecurity
El registro del firewall es esencial para detectar intentos de acceso, diagnosticar problemas de conectividad e investigar incidentes. WFwAS tiene logging configurable por perfil.
## ACTIVAR LOGGING — PowerShell Set-NetFirewallProfile -Profile Domain,Private,Public ` -LogFileName "%systemroot%\system32\LogFiles\Firewall\pfirewall.log" ` -LogMaxSizeKilobytes 32768 ` # 32 MB -LogBlocked True ` -LogAllowed True ## Equivalente con netsh netsh advfirewall set allprofiles logging filename %systemroot%\system32\LogFiles\Firewall\pfirewall.log netsh advfirewall set allprofiles logging maxfilesize 32768 netsh advfirewall set allprofiles logging droppedconnections enable netsh advfirewall set allprofiles logging allowedconnections enable ## FORMATO DEL LOG type C:\Windows\System32\LogFiles\Firewall\pfirewall.log #Version: 1.5 #Software: Microsoft Windows Firewall #Fields: date time action protocol src-ip dst-ip src-port dst-port ... 2024-01-15 09:15:32 DROP TCP 203.0.113.50 10.0.10.20 54321 3389 ... ← intento RDP bloqueado 2024-01-15 09:15:45 ALLOW TCP 10.0.50.5 10.0.10.20 51234 3389 ... ← RDP permitido desde admin ## PARSEAR EL LOG CON POWERSHELL $log = Get-Content "C:\Windows\System32\LogFiles\Firewall\pfirewall.log" | Where-Object {$_ -notmatch "^#"} | ConvertFrom-Csv -Delimiter " " -Header date,time,action,protocol,src_ip,dst_ip,src_port,dst_port,size,tcpflags,tcpsyn,tcpack,tcpwin,icmptype,icmpcode,info,path # Ver intentos de conexión bloqueados $log | Where-Object {$_.action -eq "DROP"} | Group-Object src_ip | Sort-Object Count -Descending | Select-Object -First 10 Name, Count Name Count ---- ----- 203.0.113.50 1847 ← posible escaneo o ataque 185.220.101.2 432 1.2.3.4 89 ## VER EVENTOS EN EL VISOR DE EVENTOS (método más detallado) Get-WinEvent -LogName "Security" | Where-Object { $_.Id -in 5156, 5157, 5158 # Conexión permitida/bloqueada } | Select-Object TimeCreated, Id, Message | Format-List # 5156: Conexión permitida # 5157: Conexión bloqueada # 5158: Puerto vinculado
Configuración de firewall segura para un equipo Windows de usuario final o servidor: bloquear todo lo no necesario y mantener solo los servicios requeridos.
## ================================================================ ## GhostAcademy — Firewall Hardening Script ## Aplicar en PowerShell como Administrador ## ================================================================ # 1. Asegurarse de que el firewall está activo en todos los perfiles Set-NetFirewallProfile -Profile Domain,Private,Public -Enabled True # 2. Política predeterminada: bloquear entrada, permitir salida Set-NetFirewallProfile -Profile Domain,Private,Public ` -DefaultInboundAction Block ` -DefaultOutboundAction Allow # 3. Activar logging de conexiones bloqueadas Set-NetFirewallProfile -Profile Domain,Private,Public ` -LogBlocked True ` -LogMaxSizeKilobytes 16384 # 4. Deshabilitar reglas innecesarias de red de Windows # Compartir archivos e impresoras — solo en red Privada Disable-NetFirewallRule -DisplayGroup "Compartir archivos e impresoras" -Profile Public,Domain # Deshabilitar NetBIOS/LLMNR en Público Disable-NetFirewallRule -DisplayGroup "Resolución de nombres de multidifusión de vínculo local" -Profile Public # 5. Bloquear protocolos legacy peligrosos New-NetFirewallRule -DisplayName "Bloquear SMBv1 entrada" ` -Direction Inbound -Action Block -Protocol TCP -LocalPort 445 ` -Profile Public -Enabled True # 6. Bloquear RDP desde red Pública New-NetFirewallRule -DisplayName "Bloquear RDP publico" ` -Direction Inbound -Action Block -Protocol TCP -LocalPort 3389 ` -Profile Public -Enabled True # 7. Bloquear WinRM desde red Pública New-NetFirewallRule -DisplayName "Bloquear WinRM publico" ` -Direction Inbound -Action Block -Protocol TCP -LocalPort 5985,5986 ` -Profile Public -Enabled True # 8. Verificar resultado Get-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundAction, DefaultOutboundAction, LogBlocked
Configuración de firewall para servidores de producción: exponer solo los puertos necesarios, restringir el acceso de administración a subredes de gestión y activar logging completo.
## Configuración para servidor IIS en DMZ ## MGMT_NET = subred de gestión (10.0.50.0/24) ## LAN = red interna de usuarios (10.0.0.0/8) # Política: todo bloqueado por defecto Set-NetFirewallProfile -Profile Domain,Private,Public ` -DefaultInboundAction Block -DefaultOutboundAction Block # TRÁFICO DE PRODUCCIÓN (para todos) New-NetFirewallRule -DisplayName "HTTP público" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 80 -Profile Any -Enabled True New-NetFirewallRule -DisplayName "HTTPS público" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 443 -Profile Any -Enabled True # GESTIÓN — solo desde subred de administración New-NetFirewallRule -DisplayName "RDP Gestión" ` -Direction Inbound -Action Allow -Protocol TCP -LocalPort 3389 ` -RemoteAddress 10.0.50.0/24 -Profile Domain -Enabled True New-NetFirewallRule -DisplayName "WinRM Gestión" ` -Direction Inbound -Action Allow -Protocol TCP -LocalPort 5985,5986 ` -RemoteAddress 10.0.50.0/24 -Profile Domain -Enabled True # SALIDA necesaria del servidor New-NetFirewallRule -DisplayName "DNS salida" -Direction Outbound -Action Allow -Protocol UDP -RemotePort 53 -Enabled True New-NetFirewallRule -DisplayName "HTTPS salida" -Direction Outbound -Action Allow -Protocol TCP -RemotePort 443 -Enabled True New-NetFirewallRule -DisplayName "SMTP salida" -Direction Outbound -Action Allow -Protocol TCP -RemotePort 587 -Enabled True New-NetFirewallRule -DisplayName "NTP salida" -Direction Outbound -Action Allow -Protocol UDP -RemotePort 123 -Enabled True # SQL Server al servidor de BD interno New-NetFirewallRule -DisplayName "SQL salida" ` -Direction Outbound -Action Allow -Protocol TCP -RemotePort 1433 ` -RemoteAddress 10.0.10.20 -Enabled True # ICMP solo desde gestión New-NetFirewallRule -DisplayName "ICMP Gestión" ` -Direction Inbound -Action Allow -Protocol ICMPv4 -IcmpType 8 ` -RemoteAddress 10.0.50.0/24 -Profile Domain -Enabled True # Logging completo Set-NetFirewallProfile -Profile Any -LogBlocked True -LogAllowed True -LogMaxSizeKilobytes 65536
En entornos de dominio, el firewall debe permitir los protocolos necesarios para que AD funcione correctamente, pero restringir el acceso lateral entre equipos que no necesitan comunicarse.
## PUERTOS REQUERIDOS PARA ACTIVE DIRECTORY # Aplicar en los Domain Controllers # Kerberos New-NetFirewallRule -DisplayName "Kerberos TCP" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 88 -RemoteAddress 10.0.0.0/8 -Profile Domain -Enabled True New-NetFirewallRule -DisplayName "Kerberos UDP" -Direction Inbound -Action Allow -Protocol UDP -LocalPort 88 -RemoteAddress 10.0.0.0/8 -Profile Domain -Enabled True # LDAP y LDAPS New-NetFirewallRule -DisplayName "LDAP" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 389 -RemoteAddress 10.0.0.0/8 -Profile Domain -Enabled True New-NetFirewallRule -DisplayName "LDAPS" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 636 -RemoteAddress 10.0.0.0/8 -Profile Domain -Enabled True New-NetFirewallRule -DisplayName "Global Catalog"-Direction Inbound -Action Allow -Protocol TCP -LocalPort 3268,3269 -RemoteAddress 10.0.0.0/8 -Profile Domain -Enabled True # DNS New-NetFirewallRule -DisplayName "DNS TCP" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 53 -RemoteAddress 10.0.0.0/8 -Profile Domain -Enabled True New-NetFirewallRule -DisplayName "DNS UDP" -Direction Inbound -Action Allow -Protocol UDP -LocalPort 53 -RemoteAddress 10.0.0.0/8 -Profile Domain -Enabled True # SMB (para SYSVOL/NETLOGON) New-NetFirewallRule -DisplayName "SMB DC" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 445 -RemoteAddress 10.0.0.0/8 -Profile Domain -Enabled True # RPC para replicación New-NetFirewallRule -DisplayName "RPC Endpoint Mapper" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 135 -RemoteAddress 10.0.0.0/8 -Profile Domain -Enabled True New-NetFirewallRule -DisplayName "RPC Dynamic" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 49152-65535 -RemoteAddress 10.0.0.0/8 -Profile Domain -Enabled True ## SEGMENTACIÓN LATERAL — Bloquear SMB entre workstations # Previene el movimiento lateral via PsExec, WMI, etc. New-NetFirewallRule -DisplayName "Bloquear SMB lateral" ` -Direction Inbound -Action Block -Protocol TCP -LocalPort 445 ` -RemoteAddress 10.0.100.0/24 ` # Subred de workstations -Profile Domain -Enabled True
Cómo evaluar la configuración del Firewall de Windows durante una auditoría: verificar que las políticas son correctas, identificar reglas permisivas y comprobar que el logging está activo.
## CHECKS DE AUDITORÍA — ejecutar en el sistema evaluado # 1. ¿Está el firewall activo en todos los perfiles? Get-NetFirewallProfile | Select-Object Name, Enabled Domain True ← correcto Private True ← correcto Public True ← correcto # 2. ¿Política predeterminada de entrada? Get-NetFirewallProfile | Select-Object Name, DefaultInboundAction Domain Block ← correcto Private Block ← correcto Public Block ← correcto # 3. ¿Está el logging activado? Get-NetFirewallProfile | Select-Object Name, LogBlocked, LogAllowed # 4. Reglas de entrada permisivas — buscar "Any" en remoteAddress Get-NetFirewallRule -Direction Inbound -Action Allow -Enabled True | ForEach-Object { $addr = ($_ | Get-NetFirewallAddressFilter).RemoteAddress $port = ($_ | Get-NetFirewallPortFilter).LocalPort if ($addr -eq "Any") { [PSCustomObject]@{ Nombre = $_.DisplayName Puerto = $port Perfil = $_.Profile Programa= ($_ | Get-NetFirewallApplicationFilter).Program } } } | Format-Table -AutoSize Nombre Puerto Perfil Programa ------ ------ ------ -------- HTTP público 80 Any Any ← normal para web server HTTPS público 443 Any Any ← normal WinRM HTTP 5985 Any Any ← RIESGO si no está limitado Remote Desktop 3389 Domain,Private Any ← revisar si necesario # 5. ¿Alguna regla permite "Any" protocolo con "Any" puerto? Get-NetFirewallRule -Direction Inbound -Action Allow -Enabled True | Get-NetFirewallPortFilter | Where-Object {$_.LocalPort -eq "Any" -and $_.Protocol -eq "Any"} | ForEach-Object { Get-NetFirewallRule -AssociatedNetFirewallPortFilter $_ } | Select-Object DisplayName, Profile # 6. Reglas creadas por aplicaciones (pueden ser innecesarias) Get-NetFirewallRule -Direction Inbound -Action Allow -Enabled True | Where-Object {$_.Owner -ne $null -or $_.PolicyStoreSourceType -eq "Local"} | Select-Object DisplayName, Profile, PolicyStoreSourceType | Sort-Object DisplayName # 7. Exportar configuración completa para análisis externo netsh advfirewall export "C:\audit\firewall_config.wfw" Get-NetFirewallRule -Direction Inbound -Action Allow | Export-Csv "C:\audit\inbound_allow.csv"
Crear, verificar y eliminar reglas de firewall usando los tres métodos disponibles: GUI, netsh y PowerShell. Comprender cómo cada cambio se refleja en los demás.
Requisito: Windows 10/11 o Windows Server. Ejecutar PowerShell como Administrador. Usaremos un servidor HTTP de Python como servicio de prueba.
## PREPARACIÓN: levantar un servidor HTTP de prueba Start-Process -NoNewWindow python3 -ArgumentList "-m http.server 8888" ## PASO 1: Intentar acceder (fallará — puerto no permitido) Invoke-WebRequest http://localhost:8888 -UseBasicParsing Invoke-WebRequest : Unable to connect to the remote server ← bloqueado ## PASO 2: Crear regla para permitir el puerto 8888 New-NetFirewallRule -DisplayName "Lab Test Server 8888" ` -Direction Inbound -Action Allow ` -Protocol TCP -LocalPort 8888 ` -Profile Domain,Private -Enabled True Name : {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} DisplayName : Lab Test Server 8888 Enabled : True Action : Allow ## PASO 3: Verificar que ahora funciona Invoke-WebRequest http://localhost:8888 -UseBasicParsing | Select-Object StatusCode StatusCode: 200 ← funcionando ## PASO 4: Verificar la regla existe Get-NetFirewallRule -DisplayName "Lab Test Server 8888" | Format-List ## PASO 5: Lo mismo con netsh netsh advfirewall firewall show rule name="Lab Test Server 8888" ## PASO 6: Deshabilitar la regla (no eliminar) Disable-NetFirewallRule -DisplayName "Lab Test Server 8888" Invoke-WebRequest http://localhost:8888 -UseBasicParsing Error: Unable to connect ← bloqueado de nuevo ## PASO 7: Limpiar Remove-NetFirewallRule -DisplayName "Lab Test Server 8888" Stop-Process -Name python3 -Force
Aplicar una política de hardening completa a un sistema Windows: bloquear tráfico innecesario, restringir el acceso de administración y verificar el resultado.
Evaluar el estado inicial del firewall, aplicar el script de hardening y verificar que la postura de seguridad ha mejorado. Comparar antes y después.
## FASE 1: AUDITORÍA DEL ESTADO INICIAL Write-Host "=== ESTADO INICIAL ===" $initial = Get-NetFirewallRule -Direction Inbound -Action Allow -Enabled True | Measure-Object | Select-Object -ExpandProperty Count Write-Host "Reglas permisivas de entrada: $initial" Get-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundAction, LogBlocked ## FASE 2: APLICAR HARDENING # Activar firewall y política restrictiva Set-NetFirewallProfile -Profile Domain,Private,Public -Enabled True -DefaultInboundAction Block # Activar logging Set-NetFirewallProfile -Profile Any -LogBlocked True -LogMaxSizeKilobytes 32768 # Deshabilitar reglas de perfil Público que no necesitamos Get-NetFirewallRule -Profile Public -Action Allow -Direction Inbound | Disable-NetFirewallRule # Bloquear RDP en Público New-NetFirewallRule -DisplayName "Bloquear RDP Publico" ` -Direction Inbound -Action Block -Protocol TCP -LocalPort 3389 ` -Profile Public -Enabled True # Bloquear SMB en Público New-NetFirewallRule -DisplayName "Bloquear SMB Publico" ` -Direction Inbound -Action Block -Protocol TCP -LocalPort 445 ` -Profile Public -Enabled True ## FASE 3: VERIFICAR RESULTADO Write-Host "=== ESTADO TRAS HARDENING ===" Get-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundAction, LogBlocked $after = Get-NetFirewallRule -Direction Inbound -Action Allow -Enabled True -Profile Public | Measure-Object | Select-Object -ExpandProperty Count Write-Host "Reglas permisivas en Público: $after (eran $initial)" ## FASE 4: EXPORTAR CONFIGURACIÓN FINAL netsh advfirewall export "C:\hardening_result.wfw" Write-Host "[+] Configuración exportada para documentación"
Activar logging completo, generar tráfico de prueba y analizar el log del firewall para identificar patrones, intentos de conexión y anomalías.
## PASO 1: Activar logging completo Set-NetFirewallProfile -Profile Any ` -LogBlocked True ` -LogAllowed True ` -LogFileName "C:\FW_Lab.log" ` -LogMaxSizeKilobytes 10240 ## PASO 2: Generar tráfico de prueba (bloqueado) # Intentar conexión a puerto no permitido Test-NetConnection -ComputerName 127.0.0.1 -Port 8080 Test-NetConnection -ComputerName 127.0.0.1 -Port 22 ## PASO 3: Ver el log en tiempo real Get-Content "C:\FW_Lab.log" -Wait | Where-Object {$_ -match "DROP"} 2024-01-15 10:00:05 DROP TCP 127.0.0.1 127.0.0.1 55234 8080 ... 2024-01-15 10:00:06 DROP TCP 127.0.0.1 127.0.0.1 55235 22 ... ## PASO 4: Análisis del log — top IPs bloqueadas $log = Get-Content "C:\FW_Lab.log" | Where-Object {$_ -notmatch "^#" -and $_ -match "DROP"} | ForEach-Object { $parts = $_ -split " " [PSCustomObject]@{ Time = "$($parts[0]) $($parts[1])" SrcIP = $parts[4] DstPort = $parts[7] } } $log | Group-Object SrcIP | Sort-Object Count -Descending | Select-Object Name, Count ## PASO 5: Alertar si un puerto crítico recibe muchos intentos $rdp_attempts = $log | Where-Object {$_.DstPort -eq "3389"} | Measure-Object if ($rdp_attempts.Count -gt 10) { Write-Warning "ALERTA: $($rdp_attempts.Count) intentos de conexión RDP detectados" }
Diagnóstico de problemas de conectividad relacionados con el firewall. La metodología correcta para determinar si el firewall es el responsable de un problema de red.
## 1. ¿Está el firewall bloqueando una conexión específica? # Probar si el puerto está escuchando localmente Test-NetConnection -ComputerName localhost -Port 8080 TcpTestSucceeded: True ← el servicio escucha TcpTestSucceeded: False ← el servicio NO escucha (no es el FW el problema) # Ver si hay una regla que permita el puerto Get-NetFirewallRule -Direction Inbound -Action Allow -Enabled True | Get-NetFirewallPortFilter | Where-Object {$_.LocalPort -eq "8080" -or $_.LocalPort -eq "Any"} # Deshabilitar temporalmente el FW para confirmar que es el culpable Set-NetFirewallProfile -Profile Domain -Enabled False Test-NetConnection -ComputerName localhost -Port 8080 Set-NetFirewallProfile -Profile Domain -Enabled True # SIEMPRE volver a activar ## 2. ¿Qué perfil está activo en qué interfaz? Get-NetConnectionProfile | Select-Object InterfaceAlias, NetworkCategory ## 3. ¿Está la regla aplicándose al perfil correcto? Get-NetFirewallRule -DisplayName "Mi Regla" | Select-Object Profile Profile : Domain ← Si la red activa es Public, la regla Domain no aplica! ## 4. Ver qué reglas aplican a un puerto específico Get-NetFirewallRule | Where-Object {$_.Direction -eq "Inbound" -and $_.Enabled -eq "True"} | ForEach-Object { $ports = ($_ | Get-NetFirewallPortFilter).LocalPort if ($ports -eq "3389" -or $ports -eq "Any") { [PSCustomObject]@{Regla=$_.DisplayName; Accion=$_.Action; Puerto=$ports; Perfil=$_.Profile} } } | Sort-Object Accion ## 5. Verificar si hay GPO sobreescribiendo reglas locales gpresult /h C:\gp_report.html /f && Start-Process C:\gp_report.html rsop.msc # Resultant Set of Policy ## 6. Log de eventos — ver qué bloqueó una conexión Get-WinEvent -LogName Security -FilterXPath "*[System[(EventID=5157)]]" -MaxEvents 20 | Select-Object TimeCreated, @{N="Proceso";E={$_.Properties[1].Value}}, @{N="Puerto";E={$_.Properties[9].Value}} | Format-Table
Cheatsheet de comandos PowerShell y netsh para gestión diaria del Firewall de Windows.
Estado y Perfiles
- Ver estado:
Get-NetFirewallProfile | Select Name, Enabled, DefaultInboundAction - Activar en todos:
Set-NetFirewallProfile -Profile Domain,Private,Public -Enabled True - Bloquear entrada por defecto:
Set-NetFirewallProfile -Profile Any -DefaultInboundAction Block - Ver perfil activo en cada interfaz:
Get-NetConnectionProfile - Exportar config:
netsh advfirewall export "backup.wfw" - Importar config:
netsh advfirewall import "backup.wfw"
Crear Reglas
- Permitir puerto entrada:
New-NetFirewallRule -DisplayName "X" -Direction Inbound -Action Allow -Protocol TCP -LocalPort PORT -Enabled True - Bloquear puerto salida:
New-NetFirewallRule -DisplayName "X" -Direction Outbound -Action Block -Protocol TCP -RemotePort PORT -Enabled True - Por programa: añadir
-Program "C:\ruta\programa.exe" - Por IP remota: añadir
-RemoteAddress 10.0.0.0/8 - Por perfil: añadir
-Profile Domain,Private - Equivalente netsh:
netsh advfirewall firewall add rule name="X" dir=in action=allow protocol=TCP localport=PORT enable=yes
Ver y Gestionar Reglas
- Listar reglas activas:
Get-NetFirewallRule -Enabled True | Select DisplayName, Direction, Action - Buscar por puerto:
Get-NetFirewallRule | Get-NetFirewallPortFilter | Where {$_.LocalPort -eq "3389"} - Deshabilitar:
Disable-NetFirewallRule -DisplayName "Nombre" - Habilitar:
Enable-NetFirewallRule -DisplayName "Nombre" - Eliminar:
Remove-NetFirewallRule -DisplayName "Nombre" - Exportar a CSV:
Get-NetFirewallRule -Direction Inbound -Action Allow | Export-Csv "rules.csv"
Logging
- Activar log de bloqueados:
Set-NetFirewallProfile -Profile Any -LogBlocked True - Ver log en tiempo real:
Get-Content "C:\Windows\System32\LogFiles\Firewall\pfirewall.log" -Wait - Eventos en Visor: ID 5156 (permitido), 5157 (bloqueado)
- Parsear log:
Import-Csv pfirewall.log -Delimiter " " -Header date,time,action,protocol,src_ip,dst_ip,src_port,dst_port
Puertos de Referencia
| Servicio | Puerto | Protocolo | Dirección típica |
|---|---|---|---|
| RDP | 3389 | TCP | Entrada |
| WinRM HTTP | 5985 | TCP | Entrada |
| WinRM HTTPS | 5986 | TCP | Entrada |
| SMB | 445 | TCP | Entrada |
| Kerberos | 88 | TCP/UDP | Entrada (DC) |
| LDAP | 389 | TCP/UDP | Entrada (DC) |
| LDAPS | 636 | TCP | Entrada (DC) |
| DNS | 53 | TCP/UDP | Salida |
| HTTP | 80 | TCP | Entrada / Salida |
| HTTPS | 443 | TCP | Entrada / Salida |
| SMTP | 587 | TCP | Salida |
| NTP | 123 | UDP | Salida |