GhostAcademy
GhostAcademy
Firewall de Windows — Guía Completa
Manual Completo
Firewall de Windows
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.

★ Por qué importa dominarloWFwAS es la primera línea de defensa en cualquier sistema Windows. Entenderlo es indispensable tanto para administradores de sistemas (configurar correctamente la postura de seguridad) como para auditores (evaluar si la configuración es adecuada y detectar reglas permisivas que amplían la superficie de ataque).

Lo que puede hacer WFwAS

🚦
Filtrado de Tráfico
Permite o bloquea tráfico por puerto, protocolo, IP origen/destino, aplicación, servicio y usuario.
TCP/UDP/ICMP
🔐
IPsec Integrado
Reglas de seguridad de conexión que cifran y autentican tráfico entre equipos sin VPN externa.
Encriptación nativa
📋
3 Perfiles
Perfiles Dominio, Privado y Público con configuraciones completamente independientes.
Por contexto
🏛
GPO Central
Desplegar reglas a cientos de equipos mediante Group Policy Objects en Active Directory.
Enterprise
📝
Logging Detallado
Registro de conexiones permitidas y bloqueadas con IP, puerto, protocolo y timestamp.
Auditoría
🖥
Tres interfaces
GUI (wf.msc), PowerShell (NetFirewall*) y netsh para cualquier nivel de automatización.
Flexible

Formas de Acceder

PowerShell / CMD — Abrir WFwAS
# 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
Fundamentos — 01
📋 Perfiles: Dominio, Privado y Público

WFwAS aplica automáticamente el perfil correcto según la red detectada. Cada perfil tiene su propio conjunto de reglas e independencia total.

🏛
Perfil Dominio
Se activa cuando el equipo detecta que está conectado a una red de dominio AD. Suele ser el perfil más permisivo internamente.
Red corporativa
🏠
Perfil Privado
Redes de confianza marcadas como "privadas" por el usuario: casa, oficina pequeña. Permite compartir archivos e impresoras.
Red de confianza
☕
Perfil Público
Redes desconocidas: cafeterías, aeropuertos, hoteles. Debe ser el más restrictivo. Bloquea todo el tráfico entrante por defecto.
Red no confiable
PowerShell — Gestionar perfiles
# 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
Fundamentos — 02
🏗 Arquitectura y Flujo de Tráfico

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

1
Reglas de seguridad de conexión (IPsec)
Primero se evalúa si la conexión requiere autenticación o cifrado IPsec. Si la política lo exige y no se cumple, el tráfico se descarta antes de llegar a las reglas de firewall.
2
Reglas de firewall — Bloqueo explícito
Las reglas con acción "Bloquear" tienen prioridad sobre las de "Permitir". Si hay una regla de bloqueo que coincide, el tráfico se descarta independientemente de que haya una regla de permitir.
3
Reglas de firewall — Permitir explícito
Si hay una regla de "Permitir" que coincide y no hay bloqueo explícito, el tráfico se permite.
4
Acción predeterminada del perfil
Si ninguna regla coincide, se aplica la acción predeterminada del perfil activo: normalmente "Bloquear" para tráfico entrante y "Permitir" para saliente.

Prioridad de Reglas GPO vs Local

OrigenPrioridadCuándo se aplica
Reglas GPO (Dominio)Más altaSiempre que el equipo esté en dominio. No pueden ser sobrescritas localmente.
Reglas locales (wf.msc)MediaSe aplican si no hay GPO que las contradiga.
Reglas de aplicaciónBajaGeneradas automáticamente cuando una aplicación solicita acceso.
⚠ Configuración predeterminada de WindowsPor defecto, Windows tiene el firewall activado en los tres perfiles con tráfico entrante bloqueado y tráfico saliente permitido. Muchas organizaciones dejan esta configuración predeterminada, lo que significa que las conexiones de salida no están controladas — un riesgo para exfiltración de datos.
Gestión — 01
🖥 Reglas desde la GUI (wf.msc)

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

PERMITIR Servidor Web — HTTP y HTTPS entrante ENTRADA
Protocolo
TCP
Puerto local
80, 443
Puerto remoto
Cualquiera
IP local
Cualquiera
IP remota
Cualquiera
Programa
C:\inetpub\IIS\w3wp.exe
Perfil
Dominio, Privado
Habilitada
Sí
BLOQUEAR Bloquear acceso RDP desde Internet ENTRADA
Protocolo
TCP
Puerto local
3389
IP remota
Cualquiera excepto
192.168.0.0/16
Perfil
Público
Habilitada
Sí

Parámetros Disponibles en una Regla

PestañaParámetrosDescripción
GeneralNombre, descripción, acciónPermitir, Bloquear, Permitir si seguro (IPsec)
Programas y serviciosRuta del ejecutable, servicioLimitar la regla a una aplicación o servicio específico
Protocolos y puertosTCP/UDP/ICMP, puertosPuerto local, remoto, tipo ICMP
ÁmbitoIP local, IP remotaRangos CIDR, subredes, listas de IPs
AvanzadoPerfil, tipo de interfaz, bordeAplicar solo a Wi-Fi, Ethernet o ambas
UsuariosCuenta de usuario, grupo ADAplicar la regla solo a usuarios específicos

Crear una Regla desde la GUI paso a paso

1
Abrir wf.msc y seleccionar tipo de regla
Ejecutar wf.msc → Panel izquierdo → "Reglas de entrada" o "Reglas de salida" → Acción → Nueva regla. Elegir el tipo: Puerto, Programa, Predefinida o Personalizada.
2
Configurar protocolo y puertos
Si es por Puerto: elegir TCP o UDP y especificar el número de puerto o rango (ej: 8080-8090). Si es Personalizada, se pueden combinar programa + puerto.
3
Definir el ámbito (IPs)
En "Ámbito": especificar las IPs locales y remotas que aplican. Se pueden añadir rangos CIDR, subredes o listas de IPs individuales.
4
Seleccionar acción y perfiles
Acción: Permitir conexión / Bloquear / Permitir si es segura. Perfiles: marcar los que aplican (Dominio/Privado/Público). Dar un nombre descriptivo.
Gestión — 02
⚡ Reglas con netsh advfirewall

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.

CMD — netsh advfirewall: referencia completa
## 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
Gestión — 03
💙 Reglas con PowerShell

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.

PowerShell — Cmdlets NetFirewall: referencia completa
## 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"
Gestión — 04
🏛 Reglas por GPO en Active Directory

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.

PowerShell — Crear y desplegar GPO de firewall
# 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"
}
ℹ Prioridad GPO vs LocalLas reglas de GPO siempre prevalecen sobre las locales. Si una GPO bloquea el puerto 3389 y un admin local crea una regla para permitirlo, la regla local es ignorada. Para troubleshooting: gpresult /h report.html muestra qué GPOs están aplicadas.
Reglas — 01
⬇ Reglas de Entrada

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

PowerShell — Reglas de entrada por rol de servidor
## 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
Reglas — 02
⬆ Reglas de Salida

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.

★ Por qué controlar el tráfico salienteSi un sistema es comprometido, el malware necesita comunicarse con su C2 (Command & Control). Bloquear puertos de salida no habituales — especialmente desde procesos no esperados — es una capa de defensa que muchos SOs ignoran. En servidores de producción, el tráfico saliente debería estar estrictamente controlado.
PowerShell — Política restrictiva de salida
## 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
Reglas — 03
🔐 Reglas de Seguridad de Conexión (IPsec)

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.

PowerShell — Reglas IPsec básicas
# 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
Reglas — 04
📝 Logging y Auditoría

El registro del firewall es esencial para detectar intentos de acceso, diagnosticar problemas de conectividad e investigar incidentes. WFwAS tiene logging configurable por perfil.

PowerShell / CMD — Configurar logging
## 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
Escenarios — 01
🔒 Hardening Básico de Windows

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.

PowerShell — Script de hardening de firewall
## ================================================================
## 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
Escenarios — 02
🖥 Configurar Servidor Web y SSH

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.

PowerShell — Servidor web IIS con gestión segura
## 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
Escenarios — 03
🏢 Entorno de Dominio Active Directory

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.

PowerShell — Puertos AD requeridos por DC y clientes
## 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
💡 Segmentación lateral — Defensa críticaUna de las mejores prácticas en entornos AD es bloquear SMB (445) y WMI (135) entre estaciones de trabajo. Si un equipo es comprometido, el atacante no puede moverse lateralmente via PsExec, impacket o similar. Los DCs y servidores sí deben tener estos puertos abiertos desde los clientes.
Escenarios — 04
🔍 Perspectiva del Auditor

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.

PowerShell — Auditoría de configuración de firewall
## 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"
Laboratorio — 01
🧪 Lab: Reglas Básicas

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.

🧪LAB-WFW-01 — Crear y probar reglas básicasFÁCIL

Requisito: Windows 10/11 o Windows Server. Ejecutar PowerShell como Administrador. Usaremos un servidor HTTP de Python como servicio de prueba.

PowerShell — Lab reglas básicas paso a paso
## 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
Laboratorio — 02
🧪 Lab: Hardening Completo

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.

🧪LAB-WFW-02 — Hardening: de estado inicial a seguroMEDIO

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.

PowerShell — Hardening completo con verificación
## 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"
Laboratorio — 03
🧪 Lab: Auditoría y Análisis de Logs

Activar logging completo, generar tráfico de prueba y analizar el log del firewall para identificar patrones, intentos de conexión y anomalías.

PowerShell — Activar logs y analizar patrones
## 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"
}
Referencia
🔧 Troubleshooting

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.

PowerShell / CMD — Diagnóstico sistemático
## 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
Referencia
✅ Referencia Rápida

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

ServicioPuertoProtocoloDirección típica
RDP3389TCPEntrada
WinRM HTTP5985TCPEntrada
WinRM HTTPS5986TCPEntrada
SMB445TCPEntrada
Kerberos88TCP/UDPEntrada (DC)
LDAP389TCP/UDPEntrada (DC)
LDAPS636TCPEntrada (DC)
DNS53TCP/UDPSalida
HTTP80TCPEntrada / Salida
HTTPS443TCPEntrada / Salida
SMTP587TCPSalida
NTP123UDPSalida