Introduction
Batch scripts run locally and have no sandbox. They can modify system files, registry entries, and execute anything the user has permission to do. Securing your Batch tools is crucial — especially if you distribute them.
1. Never Store Passwords in Plain Text
set PASSWORD=1234 <-- NEVER do this
Batch has no encryption. Always request passwords at runtime:
set /p PASSWORD=Enter password:
2. Use Admin Privilege Checks
net session >nul 2>&1
if %errorlevel% neq 0 (
echo Run as Administrator.
pause
exit /b
)
3. Validate User Input
set /p choice=Continue (y/n):
if /i not "%choice%"=="y" exit /b
4. Restrict Dangerous Commands Behind Prompts
echo This will delete temp files.
pause
del /q /f "%temp%\*"
5. Avoid Hardcoded Absolute Paths
REM BAD:
del C:\Windows\System32\*
REM GOOD:
del "%temp%\*"
6. Use Quotes to Prevent Path Injection
set file=%1
del "%file%"
7. Sanitize Arguments
if "%~1"=="" (
echo Missing file.
exit /b
)
if not exist "%~1" (
echo Invalid file.
exit /b
)
8. Limit Registry Modifications
Always backup first:
reg export HKCU\Software backup.reg
9. Use Temporary Working Folders
set work=%temp%\ct_work
mkdir "%work%"
cd /d "%work%"
10. Check OS Version Before Running Commands
ver | find "10." >nul
if %errorlevel% neq 0 (
echo Windows 10 required.
exit /b
)
11. Avoid Using `pause >nul` in Sensitive Scripts
Users need to see warnings before executing risky actions.
12. Obfuscation Helps, But Only Lightly
REM Not real security, just hides logic.
set "x=powershell"
%x% -command "Write-Host Secure"
13. Prevent Double Execution
tasklist | find /i "mytool.bat" >nul
if %errorlevel%==0 (
echo Already running.
exit /b
)
14. Use Logging
echo [%date% %time%] Started >> "%temp%\ct_log.txt"
15. Warn Users Before System Modifications
echo This will modify system settings.
choice /m "Continue?"
if errorlevel 2 exit /b
Summary
- Request passwords at runtime, never store them
- Check admin rights before critical actions
- Sanitize all user input and arguments
- Quote paths to prevent injection
- Use backups before registry edits
- Add warnings, prompts, and logs
- Batch has zero security → you must enforce it manually