Windows Basics - Essential System Skills¶
Related reading: Use Windows host knowledge when assessing hybrid Android apps and enterprise backends. See
basics/android-basics.mdfor mobile front-end andbasics/dfir.mdfor host artifacts.
Why Windows Knowledge Matters - The Uncomfortable Truth¶
Let me be straight with you. If you're in security and you don't understand Windows, you're going to have a bad time. I'm not saying this to be mean. I'm saying it because Windows is everywhere in enterprise environments and if you can't navigate it, you can't do your job effectively.
The Reality Check:
Most corporate networks run Windows:
Love it or hate it (and many security professionals fall into the "hate it" category), Windows dominates enterprise environments. When you walk into most companies, you'll see Windows servers, Windows workstations, Windows everything. You can't escape it.
Active Directory is Windows-based:
Active Directory is the foundation of most enterprise security. If you don't understand Windows, you can't understand AD. If you can't understand AD, you can't understand enterprise security. It's that simple. AD runs on Windows Server. It manages Windows clients. It uses Windows protocols like LDAP, Kerberos, and SMB.
Many attacks target Windows systems: Attackers target Windows because it's everywhere. Ransomware? Mostly Windows. Malware? Overwhelmingly Windows. APT groups? They live in Windows environments. Understanding how Windows works is understanding how attackers work.
Understanding defense requires understanding the target:
You can't defend what you don't understand. Windows has unique security features like UAC, BitLocker, Windows Defender, and Group Policy. It has unique attack surfaces like the Registry, Services, and SMB. It has unique forensics artifacts like Event Logs, Prefetch, and Registry hives. If you don't understand these, you're fighting blind.
The Personal Confession:
I've seen security professionals who are Linux wizards but get completely lost on a Windows system. I've seen people who can reverse engineer malware but can't navigate the Registry. I've seen pentesters who can exploit web applications but panic when they see a Windows domain.
These are gaps. Not badges of honor. Real security work requires understanding the most common operating system in enterprise environments.
What You'll Actually Do:
When you're doing security assessments: - You'll encounter Windows systems (probably most of them) - You'll need to analyze Windows logs - You'll need to understand Windows security features - You'll need to navigate Windows internals
When you're doing incident response: - Most incidents happen on Windows systems - You'll analyze Windows event logs - You'll examine Windows Registry - You'll investigate Windows processes and services - You'll work with Windows forensics tools
When you're doing penetration testing: - Most targets are Windows systems - You'll exploit Windows vulnerabilities - You'll navigate Windows domains - You'll understand Windows lateral movement techniques
But Wait, There's a But:
Windows isn't inherently bad (well, that's debatable, but let's be professional). It's just different. It has different architecture, different security model, different way of doing things. Once you understand it, it makes sense. Not necessarily elegant sense, but sense nonetheless.
The Good News:
Windows is learnable. It's not rocket science. The concepts are different from Linux, but they're systematic. Once you understand the Registry, Services, NTFS, and the overall architecture, everything else builds on that foundation.
My Advice:
Don't skip Windows. Don't think "I'll learn it later" or "I'll just focus on Linux." In enterprise security, Windows is unavoidable. Learn it now. Practice on it. Build a Windows lab. Understand how it works.
Start with the basics - understand the Registry, NTFS permissions, Services, Event Logs. Build from there. Learn PowerShell (it's actually pretty good once you get past the verbosity). Understand how Windows security works.
You'll thank yourself later. I promise.
Windows Architecture Basics - How Windows Actually Works¶
Okay, let's talk about Windows architecture. This is important. Windows is fundamentally different from Linux, and if you try to understand Windows through a Linux lens, you're going to be confused and frustrated.
The First Thing You Need to Understand:
Windows isn't Unix. It doesn't work like Unix. It doesn't think like Unix. Trying to apply Unix/Linux mental models to Windows is like trying to drive a car with bicycle instructions. Similar concepts, completely different execution.
Why This Matters:
When you're doing security work on Windows: - The file system works differently (NTFS vs ext4) - Permissions work differently (ACLs vs rwx) - Process management works differently - System configuration works differently (Registry vs config files) - Logging works differently (Event Logs vs syslog)
Understanding these differences isn't just academic - it's practical. When you're investigating an incident, analyzing malware behavior, or configuring security settings, you need to think in Windows terms, not Linux terms.
The Windows Philosophy (If It Can Be Called That):
Windows prioritizes: - Ease of use: GUI-first, automation-second - Backward compatibility: Things that worked 20 years ago still work - Integration: Everything talks to everything (sometimes too much) - Registry: The answer to everything is "put it in the Registry"
Linux prioritizes: - Simplicity: Do one thing, do it well - Text files: Configuration in human-readable text - Composability: Small tools that work together - Transparency: Open source, inspectable
Neither is "better" - they're just different. But understanding these differences helps you understand why Windows does things the way it does.
Windows Architecture Layers:
Think of Windows like an onion (or an ogre, depending on your pop culture references): 1. User Mode: Applications, user processes 2. Kernel Mode: Operating system core, drivers 3. Hardware Abstraction Layer (HAL): Hardware interaction 4. Hardware: The actual physical components
This separation is important for security. User mode processes can't directly access kernel mode or hardware. That's why you need admin privileges (or UAC elevation) for certain operations.
Key Components - The Building Blocks of Windows¶
Windows has several key architectural components that are completely different from Linux. Understanding these is crucial.
File System (NTFS) - Not Your Father's Filesystem:
NTFS (New Technology File System):
NTFS is Windows' default filesystem (has been since Windows NT). It's not like ext4 or XFS. It's... different. And in some ways, it's more powerful. In other ways, it's more complex. Mostly both.
Why NTFS Exists:
NTFS was designed for: - Security: Fine-grained permissions (ACLs) - Reliability: Journaling, transaction logging - Features: Encryption, compression, quotas built in - Enterprise: Designed for large corporate networks
Compare this to ext4 (Linux default), which was designed for simplicity and performance. Different goals, different designs.
NTFS Features That Matter:
1. Access Control Lists (ACLs):
ACLs are NTFS's permission system. Unlike Unix's simple "owner/group/others" with "read/write/execute", ACLs are much more granular:
Unix: rwxrwxrwx (owner, group, others)
NTFS:
- User "Alice": Full Control
- Group "Admins": Modify
- User "Bob": Read
- Group "Contractors": Deny Write
- System: Full Control
- ... and so on
Why ACLs Matter: - You can set permissions for specific users - You can deny permissions (Unix can't easily deny) - You can set permissions at a very granular level - Inheritance works differently (subfolders inherit from parents)
Security Implications: - Granular permissions are great for security - Complex permissions can lead to misconfigurations - ACLs can hide permission problems (harder to audit) - Inheritance can cause unexpected permissions
2. Alternate Data Streams (ADS) - The Hidden Feature:
Alternate Data Streams are one of those Windows features that most people don't know about, but attackers love. They let you attach multiple data streams to a single file.
How ADS Works:
A file has a main data stream (the normal file content) and can have alternate streams:
file.txt (main stream - the actual file)
file.txt:secret.txt (alternate stream - hidden data)
Creating an ADS:
# Create a file with alternate stream
echo "This is hidden data" > file.txt:secret.txt
# The main file appears normal
type file.txt # Shows main content
# But the alternate stream is there
more < file.txt:secret.txt # Shows hidden data
Why Attackers Use ADS: - Antivirus often doesn't scan alternate streams - Hidden data doesn't show up in normal file listings - Can hide malware, stolen data, tools - Forensics tools might miss them
Security Implications: - ADS can hide malicious content - Some backup tools don't backup ADS - File size doesn't reflect ADS content - Most users (and many admins) don't know ADS exists
How to Find ADS:
# Using dir command
dir /r file.txt # Shows alternate streams
# Using PowerShell
Get-Item file.txt -Stream * # Lists all streams
3. Journaling - The Safety Net:
NTFS uses journaling to protect against corruption. Think of it like a transaction log - before making changes, NTFS logs what it's going to do. If something goes wrong (power loss, crash), NTFS can replay the log and recover.
Why This Matters: - Better reliability than older filesystems - Faster recovery after crashes - Less data loss in power failures
4. Encryption (EFS - Encrypting File System):
EFS is Windows' built in file encryption. It's transparent (you don't notice it) and automatic (you just enable it). But it's also complicated and can cause problems.
How EFS Works: - Files are encrypted with a symmetric key - That key is encrypted with your public key - Only you (and admins with recovery certificates) can decrypt - Encryption happens transparently - you don't see it
Security Implications: - Good: Encrypted files are protected - Bad: Lost certificates = lost data forever - Bad: Forensics becomes harder - Bad: Backup/restore can break encryption
5. Compression:
NTFS can compress files transparently. Enable compression on a folder, and files compress automatically. You don't notice it (mostly), but files take less space.
When to Use: - Files that compress well (text, some binaries) - Old data that's rarely accessed - Space is more important than CPU
When NOT to Use: - Files that don't compress (already compressed files, videos) - Performance-critical files - System files (usually)
6. Disk Quotas:
NTFS can enforce disk space limits per user. User can only use X GB, then they're cut off. Useful in shared environments.
7. Symbolic Links and Junction Points:
Windows has symlinks (like Unix), but also: - Junction Points: Directory symlinks (NTFS-only) - Hard Links: Multiple names for same file - Symbolic Links: Pointers to other files/directories
Why This Matters: - Can create complex directory structures - Can confuse users (and attackers) - Can cause security issues (bypassing directory restrictions)
NTFS in Practice:
When you're working with Windows: - Most drives use NTFS (C: drive definitely does) - Understanding ACLs is crucial for security - Knowing about ADS helps in forensics - Understanding how NTFS works helps troubleshooting
The Reality:
NTFS is powerful but complex. It has features Unix filesystems don't have (ACLs, ADS), but it's also harder to understand and configure. Most Windows security issues involve NTFS permissions at some level. Understanding NTFS is understanding Windows security.
Registry - The Everything Database:
What is the Registry?
The Registry is Windows' answer to "where do we put configuration?" And the answer is: everywhere, but also nowhere. It's a hierarchical database that stores... well, almost everything. Think of it as the Windows equivalent of /etc in Linux, except it's binary, it's hard to read, and everything uses it.
Why the Registry Exists:
In Linux, configuration is in text files: - /etc/hosts - host mappings - /etc/passwd - user accounts - /etc/ssh/sshd_config - SSH settings
In Windows, configuration is in the Registry: - HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Hosts - host mappings (sort of) - HKLM\SAM - user accounts (encrypted, can't easily read) - Various registry keys for SSH settings (if installed)
What Lives in the Registry:
System Configuration: - Hardware settings - Driver configurations - Boot configuration - System paths and environment
Application Settings: - Where programs store their config - Installation paths - License keys (sometimes) - Preferences and settings
User Preferences: - Desktop wallpaper - Start menu layout - Application preferences - User-specific settings
Security Policies: - Group Policy settings (most of them) - User rights assignments - Security settings - Audit policies
Startup Programs: - Programs that run at boot - Services configuration - Scheduled tasks (some)
The Registry Structure - The Hives:
The Registry is divided into "hives" (not actual hives, just major sections):
HKEY_LOCAL_MACHINE (HKLM) - The System-Wide Stuff:
This is where system-wide settings live. It's like /etc in Linux - affects all users:
HKLM\SOFTWARE- Installed software, program settingsHKLM\SYSTEM- System configuration, services, driversHKLM\SAM- Security Account Manager (user accounts, encrypted)HKLM\SECURITY- Security policies, user rights
Security Note: You can't easily read HKLM\SAM or HKLM\SECURITY - Windows protects these. You need SYSTEM privileges (or use tools like reg.exe with proper permissions).
HKEY_CURRENT_USER (HKCU) - Your Personal Stuff:
This is user-specific settings. It's like ~/.config in Linux - only affects current user:
HKCU\SOFTWARE- Your application preferencesHKCU\Control Panel- Desktop settings, appearanceHKCU\Console- Command prompt settingsHKCU\Run- Programs that start when you log in
HKEY_CLASSES_ROOT (HKCR) - File Associations:
This is where Windows stores "what program opens what file":
.txtfiles open with Notepad (or whatever you set).exefiles are executables- COM objects and ActiveX controls
- File type handlers
HKEY_USERS (HKU) - All User Profiles:
This contains all user profiles (not just current user). Each user has a subkey: - HKU\S-1-5-21-... - A user's profile (those long numbers are SIDs) - HKU\.DEFAULT - Default profile (template for new users)
HKEY_CURRENT_CONFIG (HKCC) - Current Hardware Config:
This points to the current hardware configuration (usually just a pointer to HKLM).
Navigating the Registry:
The Registry uses a path-like structure:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
└─┬──┘└───┬───┘└───┬────┘└───┬────┘└───┬──┘└─┬─┘
│ │ │ │ │ └─ Key name
│ │ │ │ └───────── Subkey
│ │ │ └────────────────── Subkey
│ │ └───────────────────────────── Subkey
│ └────────────────────────────────────── Subkey
└─────────────────────────────────────────────── Hive
Registry Data Types:
Registry values have types: - REG_SZ: String (text) - REG_DWORD: 32-bit number - REG_QWORD: 64-bit number - REG_BINARY: Binary data (hex) - REG_MULTI_SZ: Multiple strings - REG_EXPAND_SZ: String with environment variables
The Registry in Practice:
Viewing Registry:
# Command Prompt
reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
# PowerShell
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
Common Registry Locations You Should Know:
Startup Programs:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
Installed Software:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
dpkg -l in Linux). Windows Version:
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion
Security Significance - Why Security People Care:
1. Credentials (Sometimes Insecurely Stored):
Applications sometimes store credentials in the Registry. Sometimes encrypted, sometimes... not so much:
# Some applications store passwords here (bad practice!)
HKCU\SOFTWARE\ApplicationName\Settings\Password
Tools to Find Credentials: - Registry search for "password" - Check common application locations - Look for base64/hex encoded values
2. Malware Persistence:
Malware LOVES the Registry for persistence:
- Add to startup locations
- Modify system settings
- Hook into legitimate processes
- Disable security features
Common Malware Registry Locations:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
HKLM\SYSTEM\CurrentControlSet\Services (services)
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon (logon hooks)
3. Incident Response - Registry Analysis:
Registry analysis is crucial in forensics: - USB device history: What USB devices were connected - Program execution: What programs ran (UserAssist, RecentDocs) - Network connections: Recent connections, hosts - System changes: When things were modified - User activity: What users did, when
Registry Forensics Tools: - reg.exe - built in registry tool - RegRipper - Automated registry analysis - Registry Explorer - GUI tool - PowerShell Get-ItemProperty - Query registry
4. Group Policy Enforcement:
Group Policy (the Windows way of managing settings) is enforced through the Registry. When a GPO applies, it modifies Registry keys. Understanding Registry = understanding GPOs.
Registry Best Practices:
For Administrators: - Backup Registry before major changes - Use Group Policy when possible (not direct Registry edits) - Document custom Registry changes - Test in lab first
For Security Professionals: - Know common malware persistence locations - Understand how to query Registry programmatically - Learn Registry forensics techniques - Know where credentials might hide
The Reality:
The Registry is Windows' way of doing things. It's different from Linux's text-file approach, and that difference matters. When you're doing Windows security work, you'll spend a lot of time in the Registry. Understanding it isn't optional - it's essential.
Pro Tips:
- Always backup before editing:
reg exportbefore major changes - Use reg.exe for scripting: More reliable than GUI
- Know the common locations: Startup, services, software
- Registry can be slow: Large Registry = slow boot/operations
- Some keys are protected: SAM, SECURITY need special permissions
Services - The Invisible Workers:
What Are Windows Services?
Services are background processes that run regardless of whether anyone is logged in. They're like Linux daemons, except Windows calls them "services" because... Windows.
Why Services Exist:
Some things need to run all the time: - Windows Update needs to check for updates - Event Log needs to write logs - File sharing needs to respond to requests - Antivirus needs to scan files - Database servers need to listen for connections
These can't wait for a user to log in. They need to start when Windows starts and keep running.
Service Characteristics:
Run Independently: Services don't need a logged-in user. They start when Windows boots and keep running. You can log out, and services keep going.
System Context: Most services run with high privileges (SYSTEM, LocalService, NetworkService accounts). They can do things regular users can't.
Automatic Start: Services start automatically at boot (usually). You can configure startup type: - Automatic: Starts at boot - Automatic (Delayed): Starts after boot, delays a bit - Manual: Starts only when needed - Disabled: Won't start (even if needed)
No User Interface: Services run in the background. No windows, no dialogs, no visible interface. They just... work.
Managed by SCM: Service Control Manager (SCM) is Windows' way of managing services. It starts them, stops them, monitors them.
Types of Services:
System Services: Core Windows functionality: - EventLog - Writes to Event Logs - Windows Update - Handles updates - Windows Time - Time synchronization - Plug and Play - Hardware detection
Network Services: Network-related functionality: - Server - File and printer sharing (SMB) - Workstation - Client for file sharing - Remote Desktop Services - RDP functionality - DNS Client - DNS resolution
Application Services: Third-party application services: - Database servers (SQL Server, MySQL) - Web servers (IIS, Apache) - Application backends - Development tools
Security Services: Security-related services: - Windows Defender - Antivirus - Windows Firewall - Firewall - Security Center - Security monitoring - Third-party antivirus
Service Accounts - Who Runs Services:
Services run as specific user accounts:
SYSTEM Account: - Highest privileges (more than admin!) - Full system access - Most services run as SYSTEM - Can't log in interactively - Dangerous if compromised
LocalService Account: - Limited privileges - No network credentials - Good for services that don't need much access - Safer than SYSTEM
NetworkService Account: - Limited privileges - Has network credentials (can access network resources) - Good for network services - Safer than SYSTEM, more capable than LocalService
Custom Service Accounts: - Services can run as specific users - Usually domain accounts for enterprise services - Permissions assigned to the account - Can have excessive permissions (security risk!)
Security Concerns - Why Services Matter:
1. High Privileges = High Risk:
Services run with high privileges. If a service is compromised: - Attacker gets SYSTEM access (often) - Can modify system settings - Can access sensitive data - Can create persistence
2. Vulnerable Services Are Attack Vectors:
Old, unpatched services are common entry points: - SMB vulnerabilities (EternalBlue, anyone?) - RDP vulnerabilities - Web server vulnerabilities - Database vulnerabilities
3. Service Accounts Often Over-Privileged:
Service accounts often have more permissions than needed: - Full access to entire drives - Database administrator rights - Network administrator rights - "Because it's easier" permissions
4. Services for Persistence:
Malware loves creating services: - Creates a service that runs at boot - Service runs malicious code - Persists across reboots - Hard to remove (requires admin)
Common Malware Service Locations:
HKLM\SYSTEM\CurrentControlSet\Services
Managing Services:
Command Prompt:
# List services
sc query
# List running services
sc query state= running
# Start service
sc start ServiceName
# Stop service
sc stop ServiceName
# Query service details
sc qc ServiceName
# Create service (yes, you can create services!)
sc create ServiceName binPath= "C:\path\to\service.exe"
PowerShell:
# List services
Get-Service
# Get specific service
Get-Service -Name "EventLog"
# Start service
Start-Service -Name "ServiceName"
# Stop service
Stop-Service -Name "ServiceName"
# Get service details
Get-WmiObject -Class Win32_Service | Where-Object {$_.Name -eq "ServiceName"}
Services GUI (services.msc): - Visual interface - Easy to use - Shows dependencies - Shows startup type - Can start/stop services
Service Security Best Practices:
1. Least Privilege: - Don't run services as SYSTEM if possible - Use LocalService/NetworkService when possible - Custom service accounts with minimal permissions
2. Regular Updates: - Keep services patched - Update application services - Monitor for vulnerabilities
3. Disable Unnecessary Services: - Turn off services you don't need - Reduces attack surface - Improves performance
4. Monitor Service Behavior: - Log service starts/stops - Monitor service failures - Alert on unexpected service creation
5. Secure Service Accounts: - Use strong passwords - Limit permissions - Regularly audit permissions - Don't reuse service accounts
Service Analysis in Incident Response:
When investigating incidents: - Check for new services: Malware often creates services - Review service failures: Crashes might indicate compromise - Check service permissions: Over-privileged services are risks - Review service logs: Services often log their activity
The Reality:
Services are everywhere in Windows. Understanding services is understanding Windows security. When you're doing security assessments, incident response, or hardening, you'll constantly work with services. They're powerful, necessary, and dangerous if misconfigured.
Pro Tips:
- Know your services: Understand what each service does
- Disable what you don't need: Reduces attack surface
- Monitor service changes: New services = investigate
- Understand service accounts: Who runs what, with what privileges
- Services can hide: Some malware creates well-hidden services
Essential Command Line Tools¶
Command Prompt (cmd.exe) - The Old Reliable¶
Command Prompt (cmd.exe) is Windows' original command line interface. It's been around since... well, forever (well, since DOS, which became Windows Command Prompt). PowerShell is more powerful, but cmd.exe is still everywhere, still useful, and you'll see it constantly.
Why cmd.exe Still Matters:
Even though PowerShell exists and is more powerful: - It's the default in many contexts: Scripts, batch files, legacy systems - It's faster to load: PowerShell takes a moment; cmd is instant - It's simpler for simple tasks: Sometimes you just need dir and copy - It's what many people know: Not everyone knows PowerShell - It's what some tools expect: Some older tools/scripts expect cmd
The cmd.exe Philosophy:
cmd.exe is simple. It does basic things well: - File operations (copy, move, delete) - Directory navigation (cd, dir) - Batch scripting (basic automation) - System information (systeminfo, hostname) - Network commands (ipconfig, ping)
It's not trying to be a programming language. It's a command shell. Simple commands, simple scripting.
cmd.exe vs PowerShell:
cmd.exe: - Simple commands - Basic scripting - Fast - Legacy compatibility - Limited capabilities
PowerShell: - object oriented - Powerful scripting - Slower to start - Modern features - Extensive capabilities
When to Use cmd.exe: - Quick commands (dir, cd, copy) - Legacy batch scripts - When PowerShell isn't available - Simple file operations - When you need speed
When to Use PowerShell: - Complex scripting - Working with objects - System administration - Automation tasks - When you need power
The Reality:
You'll use both. cmd.exe for quick things, PowerShell for complex things. Knowing both makes you more effective. Don't ignore cmd.exe just because PowerShell exists - sometimes the simple tool is the right tool.
Basic Navigation:
Directory Commands:
dir # List files (detailed)
dir /b # Bare format (filenames only)
dir /a # Show all files including hidden
dir /s # Recursive (subdirectories)
dir *.txt # List only .txt files
dir /o:n # Sort by name
dir /o:d # Sort by date
dir /p # Pause between pages
cd # Show current directory
cd C:\Windows # Change to specific directory
cd .. # Go up one level
cd \ # Go to root of current drive
cd /d D:\Projects # Change drive and directory
Directory Management:
mkdir MyFolder # Create directory
mkdir C:\Temp\Test # Create with full path
mkdir Folder1 Folder2 # Create multiple directories
rmdir MyFolder # Remove empty directory
rmdir /s MyFolder # Remove directory and contents (prompts)
rmdir /s /q MyFolder # Quiet mode (no prompt - DANGEROUS!)
File Operations:
Copying Files:
copy file1.txt file2.txt # Copy and rename
copy file.txt C:\Backup\ # Copy to directory
copy *.txt C:\Backup\ # Copy all .txt files
copy /Y file.txt dest\ # Overwrite without prompt
copy /A file.txt dest\ # Copy as ASCII text
copy /B file.bin dest\ # Copy as binary
copy file1.txt + file2.txt combined.txt # Concatenate files
Moving Files:
move file1.txt file2.txt # Rename file
move file.txt C:\Backup\ # Move to directory
move *.txt C:\Backup\ # Move all .txt files
move /Y file.txt dest\ # Overwrite without prompt
Deleting Files:
del file.txt # Delete file
del *.txt # Delete all .txt files
del /F file.txt # Force delete read-only files
del /Q file.txt # Quiet (no confirmation)
del /S folder\ # Delete all files in folder and subfolders
del /F /S /Q folder\ # Force delete all (DANGEROUS!)
Viewing Files:
type file.txt # Display file contents
type file.txt | more # Display with paging
more file.txt # Display with paging
type nul > file.txt # Create empty file
System Information:
systeminfo # Comprehensive system information
systeminfo | findstr /B /C:"OS Name" # Find specific info
hostname # Computer name
whoami # Current user
whoami /groups # User groups
echo %USERNAME% # Username environment variable
echo %COMPUTERNAME% # Computer name variable
ver # Windows version
Network Commands:
ipconfig # Network configuration
ipconfig /all # Detailed network info
ipconfig /release # Release IP address
ipconfig /renew # Renew IP address
ping google.com # Test connectivity
tracert google.com # Trace route
netstat -an # Network connections
netstat -an | findstr LISTENING # Find listening ports
Process and Service Commands:
tasklist # List running processes
tasklist /v # Verbose process list
tasklist /svc # Show services in processes
taskkill /PID 1234 # Kill process by PID
taskkill /IM notepad.exe # Kill process by name
taskkill /F /IM notepad.exe # Force kill
sc query # List services
sc query state= running # List running services
sc start ServiceName # Start service
sc stop ServiceName # Stop service
sc qc ServiceName # Query service config
Practical Security Examples:
# Check for listening ports
netstat -an | findstr LISTENING
# List running processes
tasklist /v /fo csv > processes.csv
# Check system information
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
# View recent files
dir /o:d /a-d C:\Users\%USERNAME%\Documents | more
# Check network configuration
ipconfig /all | findstr /i "ip address"
PowerShell - The Modern Shell (That Actually Makes Sense)¶
PowerShell is Windows' modern command line interface. It's object oriented, it's powerful, and once you get past the verbosity, it's actually pretty good. I know, shocking - a Microsoft tool that's not terrible.
Why PowerShell Exists:
Windows needed something better than cmd.exe. Something that could: - Handle objects (not just text) - Script complex tasks - Manage modern Windows features - Integrate with .NET - Actually be useful for automation
PowerShell is that thing.
The PowerShell Philosophy:
PowerShell is object oriented. Everything is an object: - Commands return objects (not just text) - You can pass objects between commands - Objects have properties and methods - You can manipulate objects programmatically
This is different from cmd.exe (or bash), which works with text. PowerShell works with structured data.
PowerShell Basics:
The Verb-Noun Naming:
PowerShell commands follow a pattern: Verb-Noun - Get-Process - Get (verb) Process (noun) - Set-Service - Set (verb) Service (noun) - Start-Process - Start (verb) Process (noun) - Stop-Service - Stop (verb) Service (noun)
This makes commands self-documenting. You can guess what a command does.
Common Verbs: - Get - Retrieve something - Set - Configure something - New - Create something - Remove - Delete something - Start - Start something - Stop - Stop something - Test - Test something
Basic Commands - The Essentials:
File Operations:
# List files (like ls or dir)
Get-ChildItem
Get-ChildItem -Recurse # Recursive (like dir /s)
# View file contents
Get-Content file.txt
Get-Content file.txt -Head 10 # First 10 lines
Get-Content file.txt -Tail 10 # Last 10 lines
# Copy files
Copy-Item file.txt destination\
Copy-Item -Recurse folder\ destination\
# Move files
Move-Item file.txt destination\
# Delete files
Remove-Item file.txt
Remove-Item -Recurse folder\ # Delete folder and contents
Directory Navigation:
# Change directory
Set-Location C:\Windows # or just: cd C:\Windows
# Show current directory
Get-Location # or: pwd
# Create directory
New-Item -ItemType Directory -Path "C:\MyFolder"
# Remove directory
Remove-Item -Path "C:\MyFolder" -Recurse
System Information:
# Comprehensive system info
Get-ComputerInfo
# Running processes
Get-Process
Get-Process -Name "chrome" # Specific process
# System services
Get-Service
Get-Service -Name "EventLog" # Specific service
# Network configuration
Get-NetIPAddress
Get-NetTCPConnection # Active connections
PowerShell Features That Make It Powerful:
1. Pipelines (But Better):
PowerShell pipelines pass objects, not text:
# Get processes, filter by CPU, sort, show top 5
Get-Process | Where-Object {$_.CPU -gt 100} | Sort-Object CPU -Descending | Select-Object -First 5
This is powerful. You're working with actual process objects, not parsing text.
2. Object Properties:
Everything is an object with properties:
# Get a process object
$process = Get-Process -Name "chrome"
# Access properties
$process.Name
$process.CPU
$process.Memory
$process.StartTime
3. Filtering with Where-Object:
Filter objects based on properties:
# Processes using more than 100MB memory
Get-Process | Where-Object {$_.WorkingSet -gt 100MB}
# Services that are running
Get-Service | Where-Object {$_.Status -eq "Running"}
4. Selecting with Select-Object:
Choose which properties to display:
# Show only Name and CPU
Get-Process | Select-Object Name, CPU
# Show first 10 processes by CPU
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 Name, CPU
5. Variables and Scripting:
PowerShell is a real scripting language:
# Variables
$name = "Windows"
$version = 10
# Arrays
$processes = Get-Process
$first = $processes[0]
# Hash tables (like dictionaries)
$config = @{
Name = "Server01"
IP = "192.168.1.100"
}
# Conditionals
if ($version -gt 10) {
Write-Host "New Windows"
} else {
Write-Host "Old Windows"
}
# Loops
foreach ($process in Get-Process) {
Write-Host $process.Name
}
PowerShell for Security:
Process Analysis:
# Find processes with network connections
Get-Process | Where-Object {$_.Path} | ForEach-Object {
$connections = Get-NetTCPConnection -OwningProcess $_.Id -ErrorAction SilentlyContinue
if ($connections) {
[PSCustomObject]@{
Process = $_.Name
PID = $_.Id
Connections = $connections.Count
}
}
}
Service Investigation:
# Services running as SYSTEM
Get-WmiObject Win32_Service | Where-Object {$_.StartName -eq "LocalSystem"} | Select-Object Name, DisplayName, PathName
Registry Queries:
# Startup programs
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" | Format-List
Get-ItemProperty "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" | Format-List
Event Log Analysis:
# Recent failed logons
Get-WinEvent -LogName Security -FilterXPath "*[System[EventID=4625]]" | Select-Object -First 10 TimeCreated, Message
PowerShell Best Practices:
1. Use Aliases Sparingly: PowerShell has aliases (ls for Get-ChildItem, cat for Get-Content). They're convenient, but in scripts, use full names for clarity.
2. Use -WhatIf: Many cmdlets support -WhatIf to preview changes:
Remove-Item file.txt -WhatIf # Shows what would happen
3. Error Handling:
# Try-catch for error handling
try {
Get-Process -Name "Nonexistent" -ErrorAction Stop
} catch {
Write-Host "Error: $_"
}
4. Pipeline Efficiency: Filter early in pipelines:
# Good: Filter first, then process
Get-Process | Where-Object {$_.CPU -gt 100} | Select-Object Name
# Bad: Process all, then filter
Get-Process | Select-Object Name | Where-Object {$_.CPU -gt 100}
5. Learn the Help System:
Get-Help Get-Process # Basic help
Get-Help Get-Process -Examples # Examples
Get-Help Get-Process -Full # Full documentation
Get-Help Get-Process -Online # Online documentation
The Reality:
PowerShell is Windows' answer to bash. It's more powerful, more structured, and more modern. Learning PowerShell makes Windows administration way easier. Yes, it's verbose. Yes, it takes getting used to. But it's worth it.
Pro Tips:
- Use ISE or VS Code: Better than basic PowerShell window
- Learn the common cmdlets: Get-, Set-, New-, Remove-
- Use tab completion: PowerShell has excellent tab completion
- Read the help:
Get-Helpis your friend - Practice scripting: PowerShell shines in automation
PowerShell vs cmd.exe - The Verdict:
Use both: - cmd.exe: Quick commands, legacy scripts, simple tasks - PowerShell: Complex tasks, automation, modern Windows administration
Knowing both makes you effective. Don't be a snob about either one - use the right tool for the job.
File System and Permissions - Who Can Do What¶
NTFS permissions are Windows' way of controlling who can access what. Unlike Unix's simple rwx (read/write/execute), NTFS uses Access Control Lists (ACLs) - more powerful, more complex, more... Windows.
Why NTFS Permissions Matter:
Permissions control access. Understanding them is crucial for: - Security assessments (finding misconfigured permissions) - Incident response (understanding what attackers could access) - System hardening (limiting access appropriately) - Troubleshooting (when users can't access files they should)
NTFS Permissions - The Granular Control¶
Basic Permissions - What They Mean:
Full Control: - All permissions (read, write, execute, delete) - Can change permissions - Can take ownership - Basically: "Do whatever you want"
Modify: - Read, write, execute, delete - Cannot change permissions - Cannot take ownership - Good for users who need to work with files
Read & Execute: - Read files - Execute programs - List folder contents - Cannot write or delete - Good for programs, scripts
Read: - View files only - List folder contents - Cannot modify or execute - Most restrictive (for viewing)
Write: - Create files - Modify files - Delete files (in folders) - Cannot read (weird, but possible) - Rarely used alone
Special Permissions:
Beyond basic permissions, NTFS has special permissions: - Traverse Folder: Navigate through folders - List Folder: See folder contents - Read Attributes: View file properties - Write Attributes: Modify file properties - Read Extended Attributes: View extended properties - Write Extended Attributes: Modify extended properties - Create Files: Create files in folder - Create Folders: Create subfolders - Delete: Delete files/folders - Read Permissions: View ACL - Change Permissions: Modify ACL - Take Ownership: Become owner
Permission Inheritance - The Cascade Effect:
NTFS permissions inherit. A folder's permissions apply to its contents (unless explicitly blocked).
How Inheritance Works:
C:\Data (Full Control for Admins)
└── Folder1 (inherits Full Control)
└── Folder2 (inherits Full Control)
└── file.txt (inherits Full Control)
Blocking Inheritance: You can block inheritance on specific folders/files. They won't inherit from parent. You then set explicit permissions.
Permission Precedence - When Permissions Conflict:
What happens when someone has multiple permissions (user + group)? 1. Explicit Deny wins (always) 2. Explicit Allow comes next 3. Inherited Deny then 4. Inherited Allow last
Viewing Permissions:
Command Prompt (icacls):
# View permissions
icacls filename.txt
# View with details
icacls filename.txt /T # Recursive
# Example output:
# filename.txt BUILTIN\Administrators:(F)
# BUILTIN\Users:(R)
# NT AUTHORITY\SYSTEM:(F)
PowerShell (Get-Acl):
# View permissions
Get-Acl filename.txt | Format-List
# Detailed view
Get-Acl filename.txt | Select-Object -ExpandProperty Access | Format-Table IdentityReference, FileSystemRights, AccessControlType
# Recursive (all files in folder)
Get-ChildItem -Recurse | Get-Acl | Select-Object Path, Owner, @{Name="Access";Expression={$_.Access | Format-Table -AutoSize}}
Modifying Permissions:
Command Prompt (icacls):
# Grant Full Control
icacls filename.txt /grant Users:F
# Grant Read
icacls filename.txt /grant Users:R
# Deny Write
icacls filename.txt /deny Users:W
# Remove permissions
icacls filename.txt /remove Users
# Reset permissions (remove all, add new)
icacls filename.txt /inheritance:r # Remove inheritance
icacls filename.txt /grant Users:R # Add permission
PowerShell:
# Get current ACL
$acl = Get-Acl filename.txt
# Create access rule (grant)
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Users", "Read", "Allow")
$acl.SetAccessRule($accessRule)
# Create access rule (deny)
$denyRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Users", "Write", "Deny")
$acl.SetAccessRule($denyRule)
# Apply ACL
Set-Acl filename.txt $acl
Common Permission Issues:
1. Over-Permissive: - Users with Full Control who don't need it - Everyone with Write access - Public folders with sensitive data
2. Under-Permissive: - Users who can't access files they need - Broken inheritance causing access denied - Service accounts without necessary permissions
3. Inheritance Problems: - Blocked inheritance creating inconsistent permissions - Child objects not inheriting correctly - Explicit permissions overriding inheritance unexpectedly
Permission Best Practices:
1. Principle of Least Privilege: - Give minimum permissions needed - Don't give Full Control unless necessary - Use Modify instead of Full Control when possible
2. Use Groups: - Don't assign permissions to individual users - Use groups (easier to manage) - Apply permissions to groups, add users to groups
3. Document Changes: - Document why permissions were changed - Keep track of custom permissions - Review permissions regularly
4. Test Before Applying: - Test permission changes in non-production - Verify users can still do their jobs - Check that security requirements are met
5. Regular Audits: - Review permissions periodically - Find and fix over-permissive settings - Remove unnecessary explicit permissions
Security Implications:
Misconfigured Permissions: - Sensitive files accessible to unauthorized users - Users with excessive permissions - Service accounts with unnecessary access
Permission Enumeration: - Attackers check for weak permissions - Looking for folders with "Everyone: Full Control" - Finding files with overly permissive ACLs
Permission Escalation: - Some permission misconfigurations allow privilege escalation - Taking ownership of files/folders - Modifying permissions on system files
The Reality:
NTFS permissions are everywhere. Understanding them is understanding Windows security. When you're doing security work, you'll constantly encounter permissions - reviewing them, modifying them, troubleshooting them. They're not optional knowledge.
Pro Tips:
- Use icacls for quick checks: Fast, simple permission viewing
- Use PowerShell for complex tasks: Better for automation
- Understand inheritance: Most permission problems stem from inheritance
- Document unusual permissions: When you deviate from defaults, document why
- Regular audits: Permissions drift over time - review them
Special NTFS Features¶
Alternate Data Streams:
# Create file with alternate stream
echo "hidden text" > file.txt:secret.txt
# View alternate stream
more < file.txt:secret.txt
File Attributes:
attrib +h file.txt # Hide file
attrib +r file.txt # Make read-only
attrib -s file.txt # Remove system attribute
User and Group Management¶
Local Users and Groups¶
Command Prompt:
net user # List users
net user username # User information
net localgroup # List local groups
PowerShell:
Get-LocalUser # List local users
Get-LocalGroup # List local groups
New-LocalUser # Create new user
User Account Control (UAC)¶
- Security feature that prevents unauthorized changes
- Prompts for admin approval
- Can be configured through Group Policy
Network Configuration¶
Basic Network Commands¶
Command Prompt:
ipconfig # Network configuration
ping google.com # Network connectivity
netstat -an # Network connections
tracert google.com # Network route tracing
PowerShell:
Get-NetIPAddress # IP configuration
Test-NetConnection # Network testing
Get-NetTCPConnection # Active connections
Windows Firewall¶
Basic Management:
netsh advfirewall show currentprofile # Show firewall status
netsh advfirewall set allprofiles state on # Enable firewall
PowerShell:
Get-NetFirewallProfile # Firewall status
Set-NetFirewallProfile -Enabled True # Enable firewall
Process and Service Management¶
Task Manager¶
- Ctrl+Shift+Esc to open
- View running processes
- Monitor performance
- Manage startup programs
Services Management¶
Command Prompt:
sc query # List services
sc start servicename # Start service
sc stop servicename # Stop service
PowerShell:
Get-Service # List services
Start-Service # Start service
Stop-Service # Stop service
Registry Basics¶
What is the Registry?¶
- Hierarchical database
- System and application settings
- User configurations
- Divided into hives (HKEY_*)
Basic Registry Commands¶
Command Prompt:
reg query "HKLM\Software" # Query registry
reg add "HKLM\Software\Test" # Add registry key
reg delete "HKLM\Software\Test" # Delete key
PowerShell:
Get-ItemProperty -Path "HKLM:\Software" # Read registry
Set-ItemProperty -Path "HKLM:\Software\Test" -Name "Value" -Value "Data" # Write registry
Event Logging¶
Windows Event Logs¶
Main Log Types: - Application: Program events - Security: Audit and security events - System: System component events
Viewing Logs:
# Command Prompt
wevtutil qe Security /c:5 # Query security log
# PowerShell
Get-EventLog -LogName Security -Newest 10 # Get recent security events
Event Viewer GUI¶
- Visual tool for log analysis
- Filtering and searching capabilities
- Custom views and subscriptions
Security Features¶
BitLocker Encryption¶
- Full disk encryption
- Protects data at rest
- Requires TPM or startup key
Windows Defender¶
- built in antivirus
- Real-time protection
- Regular definition updates
Group Policy¶
- Centralized management
- Security configurations
- User and computer policies
Useful Utilities¶
System Information¶
msinfo32 # System Information tool
taskmgr # Task Manager
services.msc # Services management
eventvwr # Event Viewer
Administrative Tools¶
compmgmt.msc # Computer Management
secpol.msc # Local Security Policy
lusrmgr.msc # Local Users and Groups
Advanced Windows Administration¶
Windows Services and Processes¶
Managing Services¶
# List services
Get-Service
# Start/stop services
Start-Service -Name "ServiceName"
Stop-Service -Name "ServiceName"
# Service status
Get-Service -Name "ServiceName" | Select-Object Status, Name, DisplayName
# Create custom service
New-Service -Name "MyService" -BinaryPathName "C:\path\to\service.exe" -DisplayName "My Custom Service" -StartupType Automatic
Process Management¶
# List processes
Get-Process
# Kill process
Stop-Process -Name "notepad" -Force
# Process details
Get-Process -Name "chrome" | Select-Object CPU, Memory
# Process tree
Get-Process | Where-Object {$_.Parent} | Format-Table Name, Id, Parent
Windows Registry Management¶
Registry Structure: - HKEY_CLASSES_ROOT (HKCR): File associations and COM objects - HKEY_CURRENT_USER (HKCU): User-specific settings - HKEY_LOCAL_MACHINE (HKLM): System-wide settings - HKEY_USERS (HKU): All user profiles - HKEY_CURRENT_CONFIG (HKCC): Hardware configuration
Registry Operations:
# Read registry value
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion" -Name "ProgramFilesDir"
# Set registry value
Set-ItemProperty -Path "HKLM:\SOFTWARE\MyApp" -Name "Setting" -Value "Value" -Type String
# Create registry key
New-Item -Path "HKLM:\SOFTWARE\MyApp" -Force
# Delete registry key
Remove-Item -Path "HKLM:\SOFTWARE\MyApp" -Recurse
Common Registry Locations:
# Startup programs
HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
# System policies
HKLM:\SOFTWARE\Policies\Microsoft\Windows
# Security settings
HKLM:\SYSTEM\CurrentControlSet\Services
Group Policy Management¶
Local Group Policy Editor:
# Open Group Policy Editor
gpedit.msc
# Computer Configuration
# User Configuration
# Administrative Templates
Group Policy Objects (GPOs):
# List GPOs
Get-GPO -All
# Create GPO
New-GPO -Name "Security Policy"
# Link GPO to OU
New-GPLink -Name "Security Policy" -Target "OU=Computers,DC=domain,DC=com"
# Force policy update
gpupdate /force
Common Group Policy Settings: - Password Policies: Minimum length, complexity requirements - Account Lockout: Failed login attempts, lockout duration - Audit Policies: Log security events - Software Restrictions: Block unauthorized applications - Firewall Settings: Configure Windows Firewall
Windows Event Logs¶
Event Log Types: - Application: Application-specific events - System: System-level events - Security: Security-related events - Setup: Installation events - Forwarded Events: Events from other computers
Event Log Management:
# View event logs
Get-EventLog -LogName System -Newest 10
# Clear event log
Clear-EventLog -LogName Application
# Create custom event
Write-EventLog -LogName Application -Source "MyApp" -EventID 1000 -EntryType Information -Message "Custom event"
# Filter events
Get-WinEvent -LogName Security -FilterXPath "*[System[EventID=4625]]" | Select-Object TimeCreated, Message
Event Log Analysis:
# Search for specific events
Get-WinEvent -LogName Security | Where-Object {$_.Id -eq 4625} | Select-Object TimeCreated, Message
# Export event logs
Get-WinEvent -LogName System | Export-Csv -Path "system_events.csv"
# Monitor real-time events
Get-WinEvent -LogName Security -MaxEvents 1 | Format-List *
Windows Firewall and Network Security¶
Windows Firewall Management:
# Show firewall status
Get-NetFirewallProfile
# Enable/disable firewall
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True
# Create firewall rule
New-NetFirewallRule -DisplayName "Allow HTTP" -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow
# Block specific IP
New-NetFirewallRule -DisplayName "Block IP" -Direction Inbound -RemoteAddress "192.168.1.100" -Action Block
Advanced Firewall Configuration:
# Configure firewall logging
Set-NetFirewallProfile -LogFileName "%systemroot%\system32\LogFiles\Firewall\pfirewall.log" -LogMaxSizeKilobytes 32767 -LogAllowed True -LogBlocked True
# Port forwarding
netsh interface portproxy add v4tov4 listenport=8080 listenaddress=0.0.0.0 connectport=80 connectaddress=192.168.1.100
# Network isolation
Set-NetFirewallProfile -Profile Public -DefaultInboundAction Block -DefaultOutboundAction Allow
Windows Update Management¶
Windows Update Configuration:
# Check for updates
Get-WindowsUpdate
# Install updates
Install-WindowsUpdate
# Configure automatic updates
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value 4
# WSUS configuration
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "http://wsus.domain.com"
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "http://wsus.domain.com"
Update History:
# View update history
Get-WindowsUpdateLog
# List installed updates
Get-HotFix | Sort-Object InstalledOn -Descending
# Remove update
wusa /uninstall /kb:KB123456
Disk Management and Storage¶
Disk Management:
# List disks
Get-Disk
# Initialize disk
Initialize-Disk -Number 1 -PartitionStyle GPT
# Create partition
New-Partition -DiskNumber 1 -Size 50GB -DriveLetter F
# Format volume
Format-Volume -DriveLetter F -FileSystem NTFS -NewFileSystemLabel "Data"
Storage Spaces:
# Create storage pool
New-StoragePool -FriendlyName "MyPool" -StorageSubsystemFriendlyName "Windows Storage*" -PhysicalDisks (Get-PhysicalDisk -CanPool $true)
# Create virtual disk
New-VirtualDisk -StoragePoolFriendlyName "MyPool" -FriendlyName "MyVDisk" -Size 100GB -ResiliencySettingName "Mirror"
# Create volume
Get-VirtualDisk -FriendlyName "MyVDisk" | Get-Disk | Initialize-Disk -PartitionStyle GPT | New-Partition -UseMaximumSize | Format-Volume -FileSystem NTFS -NewFileSystemLabel "Storage"
BitLocker Encryption:
# Enable BitLocker
Enable-BitLocker -MountPoint "C:" -EncryptionMethod Aes256 -UsedSpaceOnly
# Check BitLocker status
Get-BitLockerVolume
# Backup recovery key
(Get-BitLockerVolume -MountPoint "C:").KeyProtector | Where-Object {$_.KeyProtectorType -eq "RecoveryPassword"} | Select-Object -ExpandProperty RecoveryPassword
Windows Security Features¶
User Account Control (UAC):
# Configure UAC
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "EnableLUA" -Value 1
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "ConsentPromptBehaviorAdmin" -Value 2
Windows Defender:
# Scan system
Start-MpScan -ScanType FullScan
# Update definitions
Update-MpSignature
# Configure exclusions
Add-MpPreference -ExclusionPath "C:\Temp"
Add-MpPreference -ExclusionProcess "notepad.exe"
# Check status
Get-MpComputerStatus
AppLocker:
# Create AppLocker rule
New-AppLockerPolicy -RuleType Publisher -PublisherName "Microsoft Corporation" -ProductName "Internet Explorer" -Action Allow
# Apply policy
Set-AppLockerPolicy -PolicyObject $policy -Merge
# View rules
Get-AppLockerPolicy -Effective
Active Directory Management¶
AD User Management:
# Create user
New-ADUser -Name "John Doe" -SamAccountName "jdoe" -UserPrincipalName "jdoe@domain.com" -Path "OU=Users,DC=domain,DC=com" -AccountPassword (ConvertTo-SecureString "Password123!" -AsPlainText -Force) -Enabled $true
# Modify user
Set-ADUser -Identity jdoe -Description "IT Administrator"
# Reset password
Set-ADAccountPassword -Identity jdoe -NewPassword (ConvertTo-SecureString "NewPassword123!" -AsPlainText -Force)
# Disable account
Disable-ADAccount -Identity jdoe
AD Group Management:
# Create group
New-ADGroup -Name "IT Admins" -SamAccountName "ITAdmins" -GroupCategory Security -GroupScope Global -Path "OU=Groups,DC=domain,DC=com"
# Add user to group
Add-ADGroupMember -Identity "IT Admins" -Members jdoe
# List group members
Get-ADGroupMember -Identity "IT Admins"
AD Computer Management:
# Join computer to domain
Add-Computer -DomainName "domain.com" -Credential (Get-Credential) -Restart
# List domain computers
Get-ADComputer -Filter * | Select-Object Name, DNSHostName
# Remove computer from domain
Remove-ADComputer -Identity "COMPUTER01" -Confirm:$false
Windows Server Administration¶
Server Core Management:
# Configure remote management
Enable-NetFirewallRule -DisplayGroup "Windows Remote Management"
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*" -Force
# Install roles/features
Install-WindowsFeature -Name Web-Server -IncludeManagementTools
# List installed features
Get-WindowsFeature | Where-Object {$_.InstallState -eq "Installed"}
IIS Management:
# Install IIS
Install-WindowsFeature -Name Web-Server -IncludeAllSubFeature
# Create website
New-Website -Name "MySite" -Port 80 -PhysicalPath "C:\inetpub\wwwroot\mysite" -ApplicationPool "DefaultAppPool"
# Configure SSL
New-WebBinding -Name "MySite" -Protocol https -Port 443
Remote Desktop Services:
# Enable RDP
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" -Value 0
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
# Configure RDP settings
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" -Name "MaxConnectionTime" -Value 28800000
Windows Performance Monitoring¶
Performance Counters:
# Get performance data
Get-Counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1 -MaxSamples 5
# List available counters
Get-Counter -ListSet * | Select-Object CounterSetName
# Monitor multiple counters
Get-Counter -Counter "\Memory\Available MBytes","\Processor(_Total)\% Processor Time" -Continuous
Resource Monitor:
# Start Resource Monitor
resmon.exe
# Performance Monitor
perfmon.exe
Task Manager Automation:
# Get system performance
Get-WmiObject -Class Win32_OperatingSystem | Select-Object TotalVisibleMemorySize, FreePhysicalMemory, TotalVirtualMemorySize, FreeVirtualMemory
# Process performance
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 Name, CPU, Memory
Windows Backup and Recovery¶
Windows Server Backup:
# Install Windows Server Backup
Install-WindowsFeature -Name Windows-Server-Backup
# Create backup policy
$policy = New-WBPolicy
$volume = Get-WBVolume -VolumePath "C:"
Add-WBVolume -Policy $policy -Volume $volume
$backupLocation = New-WBBackupTarget -VolumePath "E:"
Add-WBBackupTarget -Policy $policy -Target $backupLocation
Set-WBSchedule -Policy $policy -Schedule 12:00
# Start backup
Start-WBBackup -Policy $policy
System Restore:
# Enable system restore
Enable-ComputerRestore -Drive "C:"
# Create restore point
Checkpoint-Computer -Description "Before major changes"
# List restore points
Get-ComputerRestorePoint
# Restore system
Restore-Computer -RestorePoint 123
Windows Scripting and Automation¶
PowerShell Remoting:
# Enable PS remoting
Enable-PSRemoting -Force
# Execute remote command
Invoke-Command -ComputerName "SERVER01" -ScriptBlock { Get-Service }
# Enter remote session
Enter-PSSession -ComputerName "SERVER01"
Scheduled Tasks:
# Create scheduled task
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-File C:\scripts\backup.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At 2am
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "DailyBackup" -Description "Daily backup task"
Windows Management Instrumentation (WMI):
# Query WMI
Get-WmiObject -Class Win32_ComputerSystem
# Remote WMI
Get-WmiObject -Class Win32_Service -ComputerName "SERVER01"
# WMI events
Register-WmiEvent -Query "SELECT * FROM Win32_ProcessStartTrace" -Action { Write-Host "Process started: $($event.SourceEventArgs.NewEvent.ProcessName)" }
Windows Security Hardening¶
Security Templates:
# Apply security template
secedit /configure /db secedit.sdb /cfg "C:\security\template.inf"
# Analyze security
secedit /analyze /db secedit.sdb /cfg "C:\security\template.inf" /log "C:\security\analysis.log"
Audit Policies:
# Configure audit policy
auditpol /set /category:"Logon/Logoff" /success:enable /failure:enable
auditpol /set /category:"Account Management" /success:enable /failure:enable
# View audit settings
auditpol /get /category:*
Windows Defender Advanced:
# Configure ASR rules
Set-MpPreference -AttackSurfaceReductionRules_Ids "56a863a9-875e-4185-98a7-b882c64b5ce5" -AttackSurfaceReductionRules_Actions Enabled
# Network protection
Set-MpPreference -EnableNetworkProtection Enabled
# Controlled folder access
Set-MpPreference -EnableControlledFolderAccess Enabled
Windows Troubleshooting¶
Common Issues:
# Check system health
Get-ComputerInfo | Select-Object WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer
# Event log errors
Get-WinEvent -LogName System -Level 2 -MaxEvents 10 | Format-Table TimeCreated, Id, Message
# Disk health
Get-PhysicalDisk | Select-Object FriendlyName, HealthStatus, OperationalStatus
# Network diagnostics
Test-NetConnection -ComputerName google.com -Port 80
Blue Screen Analysis:
# View BSOD logs
Get-WinEvent -LogName System | Where-Object {$_.Id -eq 1001} | Select-Object TimeCreated, Message
# Memory dump analysis
# Use WinDbg or BlueScreenView
Performance Troubleshooting:
# High CPU usage
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5
# Memory leaks
Get-Process | Sort-Object WS -Descending | Select-Object -First 5 Name, WS, PrivateMemorySize
# Disk I/O issues
Get-Counter "\PhysicalDisk(_Total)\% Disk Time" -Continuous
Practice Exercises¶
Exercise 1: System Exploration¶
- Use
systeminfoto gather system details - Check running processes with Task Manager
- Examine network configuration with
ipconfig
Exercise 2: File System¶
- Create a test directory and file
- Experiment with NTFS permissions
- Practice file operations in both cmd and PowerShell
Exercise 3: Security Basics¶
- Check Windows Defender status
- Examine firewall settings
- Review recent security events
Common Security Considerations¶
Best Practices¶
- Regular updates and patching
- Strong password policies
- Least privilege principle
- Regular backups
- Monitoring and logging
Common Vulnerabilities¶
- Unpatched systems
- Weak passwords
- Excessive permissions
- Unnecessary services
- Poor configuration
Learning Resources¶
built in Help¶
command /? # Command help (cmd)
Get-Help command # PowerShell help
Online Resources¶
- Microsoft Documentation
- Windows Security blogs
- Practice labs and simulations
Practice Platforms¶
- Windows-based vulnerable machines
- Active Directory lab environments
- Security challenge platforms
Next Steps¶
You now have the basic Windows knowledge needed for security work. Practice these commands and concepts to build familiarity with the Windows environment.
Remember: Windows security is about understanding both how to defend systems and how attackers might target them.
Ready to continue? Let's move on to Networking Basics to understand how systems communicate.