How to Block All Inbound Connections (Port Whitelisting) in Firewall in Batch Script
The standard configuration for most firewalls is to "Allow all, except what's blocked." For high-security servers or machines exposed directly to the internet, you should reverse this logic: "Block all, except what's allowed." This strategy, known as whitelisting, ensures that even if a new vulnerability is discovered or a new piece of software with a backdoor is installed, it won't be able to communicate because its port isn't on the approved list. A Batch script can use netsh advfirewall to set this strict policy and then precisely carve out exceptions for your trusted services.
This is a major security policy change that can instantly disconnect remote sessions and break network services. Read the entire guide before executing any scripts. Always have physical or out-of-band console access before implementing a lockdown.
This guide will explain how to implement a whitelist-only firewall policy.
Method 1: The "Lockdown and Carve" Strategy
This approach involves three critical steps: backing up the current configuration, adding your whitelist rules FIRST, and then setting the default policy to block.
@echo off
setlocal enabledelayedexpansion
:: Check for Administrator privileges
net session >nul 2>&1
if !errorlevel! neq 0 (
echo [ERROR] This script requires Administrator privileges.
echo Right-click and select "Run as administrator."
pause
endlocal
exit /b 1
)
set "LogFile=%USERPROFILE%\firewall_changes.log"
set "BackupFile=%USERPROFILE%\firewall_backup_prelockdown.wfw"
echo =====================================================
echo FIREWALL LOCKDOWN - WHITELIST MODE
echo =====================================================
echo.
echo This script will:
echo 1. Back up your current firewall configuration
echo 2. Create whitelist rules for essential services
echo 3. Set the default inbound policy to BLOCK ALL
echo.
echo After lockdown, ONLY whitelisted ports will work.
echo Everything else will be silently dropped.
echo.
echo =====================================================
echo.
:: Critical safety check - detect if connected via RDP
set "IsRDP=0"
netstat -ano | findstr ":3389.*ESTABLISHED" >nul 2>&1
if !errorlevel! equ 0 set "IsRDP=1"
if !IsRDP! equ 1 (
echo [!! WARNING !!] You appear to be connected via Remote Desktop!
echo If you proceed without whitelisting RDP, you will
echo be IMMEDIATELY DISCONNECTED with no way to reconnect.
echo.
)
:: Confirmation
set /p "confirm=Type LOCKDOWN to proceed: "
if /i "!confirm!" neq "LOCKDOWN" (
echo [CANCELLED] No changes made.
pause
endlocal
exit /b 0
)
echo.
:: ===== STEP 1: BACKUP =====
echo [1/3] Backing up current firewall configuration...
netsh advfirewall export "%BackupFile%" >nul 2>&1
if !errorlevel! equ 0 (
echo [OK] Backup saved to: %BackupFile%
echo [OK] To restore: netsh advfirewall import "%BackupFile%"
) else (
echo [WARN] Backup failed - proceeding anyway.
)
echo.
:: ===== STEP 2: CREATE WHITELIST RULES FIRST =====
:: CRITICAL: Add rules BEFORE setting the block policy
:: Otherwise you lock yourself out during rule creation
echo [2/3] Creating whitelist exceptions...
echo.
:: Allow ICMP Ping (optional - useful for monitoring)
netsh advfirewall firewall show rule name="WHITELIST_PING" >nul 2>&1
if !errorlevel! neq 0 (
netsh advfirewall firewall add rule name="WHITELIST_PING" dir=in action=allow protocol=ICMPv4 enable=yes >nul 2>&1
echo [OK] ICMP Ping - allowed
) else (
echo [SKIP] ICMP Ping - already exists
)
:: Allow DNS (required for name resolution)
netsh advfirewall firewall show rule name="WHITELIST_DNS" >nul 2>&1
if !errorlevel! neq 0 (
netsh advfirewall firewall add rule name="WHITELIST_DNS" dir=in action=allow protocol=UDP localport=53 enable=yes >nul 2>&1
echo [OK] DNS (UDP 53) - allowed
) else (
echo [SKIP] DNS - already exists
)
:: Allow Web Traffic (HTTP + HTTPS)
netsh advfirewall firewall show rule name="WHITELIST_WEB" >nul 2>&1
if !errorlevel! neq 0 (
netsh advfirewall firewall add rule name="WHITELIST_WEB" dir=in action=allow protocol=TCP localport=80,443 profile=domain,private enable=yes >nul 2>&1
echo [OK] Web (TCP 80,443) - allowed (Domain,Private only)
) else (
echo [SKIP] Web - already exists
)
:: Allow Remote Desktop (CRITICAL for remote management)
netsh advfirewall firewall show rule name="WHITELIST_RDP" >nul 2>&1
if !errorlevel! neq 0 (
netsh advfirewall firewall add rule name="WHITELIST_RDP" dir=in action=allow protocol=TCP localport=3389 profile=domain,private enable=yes >nul 2>&1
echo [OK] RDP (TCP 3389) - allowed (Domain,Private only)
) else (
echo [SKIP] RDP - already exists
)
:: Allow SQL Server (if needed - remove if not applicable)
netsh advfirewall firewall show rule name="WHITELIST_SQL" >nul 2>&1
if !errorlevel! neq 0 (
netsh advfirewall firewall add rule name="WHITELIST_SQL" dir=in action=allow protocol=TCP localport=1433 profile=domain enable=yes >nul 2>&1
echo [OK] SQL (TCP 1433) - allowed (Domain only)
) else (
echo [SKIP] SQL - already exists
)
echo.
:: ===== STEP 3: SET DEFAULT POLICY TO BLOCK =====
echo [3/3] Setting default inbound policy to BLOCK...
:: blockinbound = Block everything not explicitly allowed
:: allowoutbound = Allow all outgoing traffic (standard)
netsh advfirewall set allprofiles firewallpolicy blockinbound,allowoutbound >nul 2>&1
if !errorlevel! equ 0 (
echo [OK] Default inbound policy: BLOCK ALL
echo [OK] Default outbound policy: ALLOW ALL
) else (
echo [ERROR] Failed to set policy.
)
echo.
:: Verify
echo =====================================================
echo LOCKDOWN COMPLETE - VERIFICATION
echo =====================================================
echo.
netsh advfirewall show allprofiles firewallpolicy 2>nul | findstr /i "Policy"
echo.
echo Active whitelist rules:
netsh advfirewall firewall show rule name=all dir=in 2>nul | findstr /i "WHITELIST" | findstr /i "Rule Name:"
echo.
echo =====================================================
echo.
echo [RESTORE] If something breaks, run:
echo netsh advfirewall import "%BackupFile%"
:: Log
echo [%date% %time%] LOCKDOWN activated by %USERNAME% >> "%LogFile%"
pause
endlocal
The script set blockinbound first, then added rules. During the seconds between those commands, ALL inbound traffic is blocked, including your RDP session. If the rule creation fails or the script crashes mid-execution, you're permanently locked out. Adding rules first ensures your management access is preserved throughout the process.
Method 2: Restricting Access by Source IP
For ultimate security, don't just whitelist the port whitelist the source IP address. Only allow your specific management IP to access sensitive services.
@echo off
setlocal enabledelayedexpansion
:: Check for Administrator privileges
net session >nul 2>&1
if !errorlevel! neq 0 (
echo [ERROR] This script requires Administrator privileges.
pause
endlocal
exit /b 1
)
set "LogFile=%USERPROFILE%\firewall_changes.log"
echo [SECURE] Creating IP-restricted whitelist rules...
echo.
:: Management access - only from office IP
set "OfficeIP=203.0.113.50"
set "RuleName=WHITELIST_RDP_OFFICE"
netsh advfirewall firewall show rule name="%RuleName%" >nul 2>&1
if !errorlevel! equ 0 (
echo [SKIP] %RuleName% already exists.
) else (
netsh advfirewall firewall add rule name="%RuleName%" dir=in action=allow protocol=TCP localport=3389 remoteip=%OfficeIP% enable=yes >nul 2>&1
if !errorlevel! equ 0 (
echo [OK] RDP access locked to %OfficeIP% only.
) else (
echo [FAIL] Could not create rule.
)
)
:: SQL access - only from application server
set "AppServerIP=10.0.0.20"
set "RuleName=WHITELIST_SQL_APPSERVER"
netsh advfirewall firewall show rule name="%RuleName%" >nul 2>&1
if !errorlevel! equ 0 (
echo [SKIP] %RuleName% already exists.
) else (
netsh advfirewall firewall add rule name="%RuleName%" dir=in action=allow protocol=TCP localport=1433 remoteip=%AppServerIP% enable=yes >nul 2>&1
if !errorlevel! equ 0 (
echo [OK] SQL access locked to %AppServerIP% only.
) else (
echo [FAIL] Could not create rule.
)
)
:: Multiple IPs can be comma-separated
set "MonitoringIPs=10.0.0.5,10.0.0.6,10.0.0.7"
set "RuleName=WHITELIST_MONITORING"
netsh advfirewall firewall show rule name="%RuleName%" >nul 2>&1
if !errorlevel! equ 0 (
echo [SKIP] %RuleName% already exists.
) else (
netsh advfirewall firewall add rule name="!RuleName!" dir=in action=allow protocol=ICMPv4 remoteip=!MonitoringIPs! enable=yes >nul 2>&1
if !errorlevel! equ 0 (
echo [OK] Monitoring ping locked to !MonitoringIPs!.
) else (
echo [FAIL] Could not create rule.
)
)
echo.
echo [INFO] IP-restricted rules provide the strongest possible access control.
echo Even if a port is open, only the specified source IPs can use it.
echo [%date% %time%] Created IP-restricted whitelist rules by %USERNAME% >> "%LogFile%"
pause
endlocal
Port whitelisting says "only these doors are open." IP restriction says "only these specific people can walk through those doors." Combining both creates the strongest possible access control, even a compromised port can't be exploited from an unauthorized source.
Method 3: Emergency Restore
If you make a mistake and lock yourself out, or if the lockdown breaks services, restore the default configuration.
@echo off
setlocal enabledelayedexpansion
:: Check for Administrator privileges
net session >nul 2>&1
if !errorlevel! neq 0 (
echo [ERROR] This script requires Administrator privileges.
pause
endlocal
exit /b 1
)
set "LogFile=%USERPROFILE%\firewall_changes.log"
set "BackupFile=%USERPROFILE%\firewall_backup_prelockdown.wfw"
echo [EMERGENCY] Firewall Restore Options
echo.
echo 1. Restore from backup file (recommended)
echo 2. Reset to Windows default policy (quick fix)
echo 3. Disable firewall entirely (last resort - temporary only)
echo.
set /p "Choice=Enter choice (1-3): "
if "%Choice%"=="1" (
if not exist "%BackupFile%" (
echo [ERROR] Backup file not found: %BackupFile%
echo Use option 2 instead.
pause
endlocal
exit /b 1
)
echo [ACTION] Restoring from backup...
netsh advfirewall import "%BackupFile%" >nul 2>&1
if !errorlevel! equ 0 (
echo [SUCCESS] Firewall restored to pre-lockdown configuration.
echo [%date% %time%] RESTORED firewall from backup by %USERNAME% >> "%LogFile%"
) else (
echo [ERROR] Restore failed.
)
) else if "%Choice%"=="2" (
echo [ACTION] Resetting to default Windows policy...
:: Reset inbound policy to default
netsh advfirewall set allprofiles firewallpolicy blockinbound,allowoutbound >nul 2>&1
:: Re-enable the firewall on all profiles
netsh advfirewall set allprofiles state on >nul 2>&1
:: Reset to default rules
netsh advfirewall reset >nul 2>&1
echo [SUCCESS] Firewall reset to Windows defaults.
echo [WARN] All custom rules (including whitelist) have been removed.
echo [%date% %time%] RESET firewall to defaults by %USERNAME% >> "%LogFile%"
) else if "%Choice%"=="3" (
echo.
echo [!! DANGER !!] Disabling the firewall removes ALL protection.
echo Only use this to regain access, then re-enable immediately.
echo.
set /p "dangerConfirm=Type DISABLE to confirm: "
if /i "!dangerConfirm!"=="DISABLE" (
netsh advfirewall set allprofiles state off >nul 2>&1
echo [WARNING] Firewall is now COMPLETELY OFF.
echo Re-enable IMMEDIATELY after regaining access:
echo netsh advfirewall set allprofiles state on
echo [%date% %time%] EMERGENCY DISABLE by %USERNAME% >> "%LogFile%"
) else (
echo [CANCELLED] No changes made.
)
) else (
echo [ERROR] Invalid choice.
)
echo.
:: Show current state
echo [CURRENT STATE]
netsh advfirewall show allprofiles state 2>nul | findstr /i "State"
netsh advfirewall show allprofiles firewallpolicy 2>nul | findstr /i "Policy"
pause
endlocal
Method 4: Whitelist Configuration from File
For repeatable, documented deployments, define your whitelist in a configuration file.
@echo off
setlocal enabledelayedexpansion
:: Check for Administrator privileges
net session >nul 2>&1
if !errorlevel! neq 0 (
echo [ERROR] This script requires Administrator privileges.
pause
endlocal
exit /b 1
)
set "ConfigFile=whitelist.cfg"
set "LogFile=%USERPROFILE%\firewall_changes.log"
:: Create sample config if it doesn't exist
if not exist "%ConfigFile%" (
echo # Firewall Whitelist Configuration > "%ConfigFile%"
echo # Format: RuleName^|Protocol^|LocalPort^|RemoteIP^|Profiles >> "%ConfigFile%"
echo # Use 'any' for RemoteIP to allow from anywhere >> "%ConfigFile%"
echo # Use 'domain,private' or 'public' for Profiles >> "%ConfigFile%"
echo WHITELIST_PING^|ICMPv4^|any^|any^|domain,private,public >> "%ConfigFile%"
echo WHITELIST_RDP^|TCP^|3389^|any^|domain,private >> "%ConfigFile%"
echo WHITELIST_WEB^|TCP^|80,443^|any^|domain,private >> "%ConfigFile%"
echo WHITELIST_SQL^|TCP^|1433^|10.0.0.0/24^|domain >> "%ConfigFile%"
echo WHITELIST_SSH^|TCP^|22^|203.0.113.50^|domain,private >> "%ConfigFile%"
echo.
echo [INFO] Created sample %ConfigFile%
echo Edit the file with your whitelist, then run this script again.
pause
endlocal
exit /b 0
)
echo [DEPLOY] Applying whitelist from %ConfigFile%...
echo.
:: Backup first
netsh advfirewall export "%USERPROFILE%\firewall_backup_prewhitelist.wfw" >nul 2>&1
echo [OK] Backup saved.
echo.
:: Step 1: Create all whitelist rules
set "RuleCount=0"
for /f "usebackq tokens=1-5 delims=| eol=#" %%a in ("%ConfigFile%") do (
set "rName=%%a"
set "rProto=%%b"
set "rPort=%%c"
set "rIP=%%d"
set "rProfile=%%e"
:: Check if rule already exists
netsh advfirewall firewall show rule name="!rName!" >nul 2>&1
if !errorlevel! equ 0 (
echo [SKIP] !rName! - already exists
) else (
:: Build command dynamically
set "cmd=netsh advfirewall firewall add rule name="!rName!" dir=in action=allow enable=yes"
:: Handle ICMP separately (no port)
if /i "!rProto!"=="ICMPv4" (
set "cmd=!cmd! protocol=ICMPv4"
) else (
set "cmd=!cmd! protocol=!rProto!"
if /i "!rPort!" neq "any" set "cmd=!cmd! localport=!rPort!"
)
if /i "!rIP!" neq "any" set "cmd=!cmd! remoteip=!rIP!"
if defined rProfile set "cmd=!cmd! profile=!rProfile!"
!cmd! >nul 2>&1
if !errorlevel! equ 0 (
echo [OK] !rName! - created
set /a RuleCount+=1
) else (
echo [FAIL] !rName! - creation failed
)
)
)
echo.
echo [INFO] !RuleCount! whitelist rule(s) created.
echo.
:: Step 2: Set block policy
set /p "applyBlock=Apply BLOCK ALL inbound policy now? (Y/N): "
if /i "!applyBlock!"=="Y" (
netsh advfirewall set allprofiles firewallpolicy blockinbound,allowoutbound >nul 2>&1
echo [OK] Default inbound policy set to BLOCK.
echo [%date% %time%] LOCKDOWN with whitelist config by %USERNAME% >> "%LogFile%"
) else (
echo [INFO] Rules created but block policy NOT applied.
echo Apply manually: netsh advfirewall set allprofiles firewallpolicy blockinbound,allowoutbound
)
pause
endlocal
Whitelist configuration format:
# RuleName|Protocol|LocalPort|RemoteIP|Profiles
WHITELIST_RDP|TCP|3389|any|domain,private
WHITELIST_SQL|TCP|1433|10.0.0.0/24|domain
This makes your whitelist auditable, version-controllable, and repeatable across multiple servers.
How to Avoid Common Errors
Wrong Way: Setting Block Policy BEFORE Adding Rules
If you run blockinbound first and then try to add rules, you'll be locked out during the gap between those commands. If the script crashes mid-execution, you're permanently locked out.
Correct Way: Always add whitelist rules FIRST, verify they exist, and THEN set the block policy. Method 1 follows this order explicitly.
Wrong Way: Locking Yourself Out via RDP
If you set blockinbound while connected via Remote Desktop and haven't added an RDP exception, you will be instantly disconnected with no way to reconnect remotely.
Correct Way: Always whitelist your management access (RDP port 3389, or SSH port 22) before activating the block policy. Method 1 includes automatic RDP session detection and warns you.
Wrong Way: Not Creating a Backup
If your whitelist is misconfigured and breaks services, you need a way to restore the previous working configuration.
Correct Way: Always export the current firewall configuration before making changes:
netsh advfirewall export "%USERPROFILE%\firewall_backup.wfw"
:: To restore:
netsh advfirewall import "%USERPROFILE%\firewall_backup.wfw"
Wrong Way: Using notconfigured as a Policy Reset
The original Method 3 used firewallpolicy notconfigured,allowoutbound, but notconfigured is not a valid parameter for netsh advfirewall set firewallpolicy.
Correct Way: Use netsh advfirewall reset to restore Windows default rules and policy, or explicitly set blockinbound,allowoutbound which is the actual Windows default.
Problem: Profile Mismatch
If you set the publicprofile to block but leave the privateprofile as allow, your machine is still vulnerable on your home network.
Solution: Use allprofiles to ensure the strict policy applies everywhere, then restrict individual whitelist rules to appropriate profiles.
Best Practices and Rules
1. Order of Operations
Always follow this sequence for lockdown:
- Backup the current configuration
- Add all whitelist rules
- Verify the rules exist
- Set the block policy
- Test connectivity
Never reverse steps 2 and 4.
2. Core Services to Whitelist
Windows requires certain traffic to function. Consider whitelisting:
| Service | Port | Protocol | Notes |
|---|---|---|---|
| DNS | 53 | UDP | Required for name resolution |
| DHCP | 67-68 | UDP | Required for IP assignment |
| RDP | 3389 | TCP | Required for remote management |
| ICMP | - | ICMPv4 | Useful for monitoring/ping |
| HTTP/S | 80, 443 | TCP | If hosting web services |
3. Management IP Whitelist
Always include an emergency access rule that allows connections from a known static management IP, regardless of profile:
netsh advfirewall firewall add rule name="EMERGENCY_MGMT" dir=in action=allow remoteip=YOUR.STATIC.IP protocol=TCP localport=3389
4. Test Before Committing
Before applying to a production server, test the whitelist on a non-critical machine. Verify that all required services still function with the block policy active.
5. Document Your Whitelist
Use the configuration file approach (Method 4) so your whitelist is version-controllable and auditable. Store it alongside your server documentation.
6. Always Use setlocal / endlocal
Without setlocal, every variable your script creates persists in the parent shell session, causing potential conflicts when running multiple scripts in sequence.
Conclusions
Implementing a "Block All" inbound policy is the definitive way to harden a Windows system. By moving away from reactive blocking and utilizing a strict whitelist, you create a simplified, high-security environment that is resilient against unknown threats. This professional level of firewall management ensures that your infrastructure only exposes exactly what it needs to, significantly reducing your overall attack surface.