defensive
keylogger
malware
spyware

What Is a Keylogger: Types, How It Works and How to Protect

What a keylogger is, types (software, hardware, web, acoustic), distribution, detection with EDR and antivirus, and protective measures.

SecraMay 10, 202613 min read

A keylogger is a program or device that records every keystroke on a machine. More complete versions also capture screenshots, mouse position and clipboard. The literal translation is "key recorder". It gets used both in legitimate contexts (parental audit with consent, authorised judicial investigation, declared corporate control) and, far more often, in malicious contexts: credential theft, banking data capture, unlawful surveillance and remote control via trojans.

This guide explains what a keylogger actually is, the six types that appear in forensic investigations (pure software, hardware, BIOS/firmware, web, acoustic/electromagnetic and mobile stalkerware), how it gets distributed, how modern defensive controls detect it, what legal framework applies in Spain and, above all, what protective measures have real impact against the attack.

What a keylogger is

A keylogger is a software or hardware component whose central function is to intercept and store a user's keystrokes, normally accompanied by metadata (timestamp, active application, window title). The output may stay local or be exfiltrated to a server controlled by the attacker via HTTP/S, SMTP, DNS tunneling or its own C2 channel.

What it gives the attacker:

  • Credentials in clear, with no need to crack hashes or intercept encrypted traffic.
  • Victim context: banks used, corporate platforms, internal communications.
  • Lateral movement support: PowerShell commands typed by the sysadmin, passwords written for RDP connections, SSH keys copied.
  • Extortion material: private conversations, searches, messages.
  • Silent persistence: a well-implemented keylogger can live for months undetected if the user doesn't use MFA or rotate passwords.

Keyloggers existed before consumer internet: the first documented one was a Soviet program from the 1970s that monitored IBM Selectric machines. Today most get distributed as a module inside a trojan or RAT, and the difference between pure "keylogger" and spyware is blurry.

Keylogger types

Six main variants appear in forensic investigations.

Software keyloggers (the most common)

Programs installed on the victim's operating system that intercept keyboard events via system APIs. Subtypes by where they hook:

  • User-mode API hooking. They use SetWindowsHookEx (Windows) or equivalents on macOS/Linux to register callbacks that receive every key. The simplest implementation and the one used by most commercial trojans.
  • Kernel-mode keyloggers. Drivers or kernel-loaded modules that intercept at a lower level. Much stealthier and harder to detect, but require elevated privileges to install and a valid certificate to load the driver on modern systems.
  • Browser form-grabbing. Don't intercept OS keyboard but HTML forms before they get sent encrypted. Bypass HTTPS because they act in the client. Heavily used by the Zeus family and derivatives (Citadel, ICEDID).
  • Screen scraping. Take periodic screenshots or on click. Useful against virtual keyboards some banks use precisely to avoid classic keylogging.

Hardware keyloggers

Physical devices placed between the keyboard and the machine. Three modalities:

  • USB inline. A small dongle a few centimetres long that goes between the USB keyboard cable and the PC port. Stores keystrokes in internal flash memory and, in recent models, exfiltrates them over Wi-Fi. Requires no software install, antivirus doesn't see it.
  • PS/2 inline. Variant for old PS/2 keyboards. Still appears in industrial environments.
  • Wireless sniffer. Captures radio traffic between the wireless keyboard and the receiver. Old models without encryption or with broken encryption (KeySweeper by Samy Kamkar, 2015) get intercepted from metres away.

The common factor is that no endpoint defensive software can detect them. Only periodic physical inspection.

BIOS/firmware keyloggers

Implanted in UEFI firmware, in the keyboard's own firmware (very rare but documented in investigations of supply-chain-compromised devices) or in the firmware of a chain device (KVM, malicious USB hub).

They persist across operating system reinstalls. Typically state-actor or compromised supply chain. For a Spanish SME it's an irrelevant vector; for a defence or energy entity under state threat, it isn't.

Web keyloggers (injected JavaScript)

JavaScript code injected into a compromised page that captures keydown, paste and form events. Most seen: Magecart-style e-skimming attacks against e-commerce sites, where the attacker injects script into a checkout page and captures card number and CVV before they get sent to the backend.

Doesn't require infecting the user's endpoint. Lives in the browser while the user is on the compromised page. Detection from the site owner's side: script integrity monitoring (CSP, Subresource Integrity), third-party provider review.

Acoustic and electromagnetic keyloggers

Academic research, not common operational malware:

  • Acoustic. ML models that distinguish the sound fingerprint of each key from a nearby microphone recording. Works in controlled conditions; degrades in real offices with background noise.
  • Electromagnetic. Captures electromagnetic emanations from the keyboard cable at several metres. Demonstrated by Vuagnoux and Pasini (2008). Defence: Faraday cages, minimum distances, shielded keyboards (only applies in maximum-security environments).
  • Video analysis. Camera recording the user's hands. Works very well with virtual keyboards shown on screen and combines with OCR.

Mobile stalkerware

Apps installed on Android or iOS through physical access to the device that record keyboard, messages, location, audio. Marketed as "parental control" or "spouse monitoring", their real mass use is illegal intimate surveillance. Documented families: mSpy, FlexiSpy, Cocospy. The Coalition Against Stalkerware maintains an updated list and works with antivirus vendors to classify them as spyware.

How they get distributed

Realistic vectors in Spain, ordered by frequency in incident investigations:

  • Phishing with malicious attachment or link. Office documents with macros, obfuscated executables, compressed files password-protected in the email body. Still vector number one.
  • Software cracks, pirate keys, "cheats". The user voluntarily runs the binary and the keylogger comes as a module inside.
  • Supply chain compromise. A vendor distributes an installer with an added module. Documented cases: M.E.Doc in NotPetya, SolarWinds.
  • Physical access (uncommon but real). The attacker with minutes of physical access can install a hardware keylogger or USB-persistent software.
  • Drive-by download. Compromised web page that exploits a browser vulnerability to drop malware without user interaction. Reduced in 2026 versus past years thanks to modern sandboxing, but not extinct.
  • MDM or corporate policies misused. In environments where IT has the technical capability to install a keylogger as part of DLP, occasional abuses by an internal owner with personal motivation.

Classic malware families that include a keylogger module: Agent Tesla, FormBook, AsyncRAT, RedLine Stealer, NjRat, Vidar Stealer, Lokibot. Most get bought in underground markets by monthly subscription.

How they get detected

Modern defensive controls attack the problem from several fronts.

Traditional antivirus. Detects signatures of known families. Effective against unobfuscated commodity keyloggers; ineffective against recent variants or with obfuscation specific to the target.

EDR / XDR. Detects behaviour. Patterns that trigger alerts: unknown process reading from clipboard, SetWindowsHookEx hooks in applications that shouldn't install them, exfiltration to no-reputation IPs, continuous screen capture. Detail in what is an EDR.

Attachment sandbox. Before delivering the email, the attachment runs in a sandbox and behaviour gets observed. Detects what signatures don't see.

Network monitoring. Anomalous DNS traffic (DNS tunneling for exfil), HTTPS connections to recently registered domains, upload spikes at unusual hours. Detectable with a well-configured SIEM.

Identity monitoring. Anomalous logins indicating compromised credentials: geolocation, time, device. Services like Microsoft Defender for Identity or identity modules in EDRs detect this pattern even if the keylogger itself wasn't seen.

Physical inspection. For hardware keyloggers: periodic review of USB ports on critical machines, especially in shared environments (universities, coworking spaces, reception desks). Security mark or tamper-evident label on the cable.

Threat hunting. The proactive hunt for keylogging patterns when they haven't triggered alerts is part of mature threat hunting.

How to protect

The measures that actually close the door, ordered by impact.

  • Universal MFA. Two-factor authentication drastically reduces damage even if the keylogger captures the password: the attacker also needs the second factor. Ideally FIDO2/WebAuthn (phishing-resistant); otherwise, TOTP in a dedicated app (not SMS).
  • Password manager. Passwords don't get typed, they get autofilled from the manager. A classic software keylogger doesn't capture passwords that don't go through the keyboard.
  • Modern EDR on endpoints. Covers most software keyloggers including new variants via behavioural detection.
  • Privilege hardening. Users without administrator permission can't install most kernel-mode keyloggers. Most home malware falls here.
  • Updates. Operating system, browser, office applications up to date. Reduces drive-by and exploits.
  • Anti-script policy. Office macro blocking, restricted PowerShell execution for standard users, AMSI enabled.
  • Software policy. AppLocker, Windows Defender Application Control or equivalents to prevent unauthorised binary execution.
  • DNS filtering. Cut resolution of suspicious domains before the keylogger contacts its C2.
  • Awareness. Regular role-specific training. A CFO who understands how a keylogger travels in an "urgent invoice" PDF opens fewer.
  • Periodic physical inspection of critical machines, in offices with visitor access.
  • Leak monitoring (Have I Been Pwned, dark web monitoring) in case credentials appear after a silent compromise.

No single control closes the problem. Defence is layered and the most underrated piece is usually universal MFA: even in 2026 there are large organisations with privileged accounts without MFA, and a keylogger on any user endpoint equals Domain Admin.

Installing a keylogger on someone else's device without their consent can constitute several crimes, depending on circumstances:

  • Article 197 of the Penal Code: discovery and revelation of secrets. Sentenced with one to four years' imprisonment. Capturing private communications or reserved personal data without authorisation falls here.
  • Article 197 bis: computer intrusion. Access to a third party's information system without authorisation.
  • Article 197 ter: production and commercialisation of programs to commit the above crimes. Applicable to developers and distributors of stalkerware.
  • Organic Law 3/2018 (LOPD-GDD) and GDPR: unlawful processing of personal data with administrative sanctions that can reach millions of euros.
  • Workers' Statute and labour case law: corporate monitoring on the worker's computer requires specific prior information, written policy communicated and proportionality test. Spanish Supreme Court and Constitutional Court rulings mark the limits.

Legitimate cases:

  • Parent with the minor's consent on their own device, within a proportional framework.
  • Company with express policy, prior employee communication, installation on corporate equipment and use for a proportionate and necessary purpose. The López Ribalda v. Spain ruling (2019, ECtHR) set the European standard.
  • Judicial investigation with authorisation from an investigating judge.
  • Offensive security research on own or authorised infrastructure (Red Team audits, pentesting).

Any use outside those frameworks is illegal even if the motivation is presented as benign. The Spanish Data Protection Agency regularly sanctions keylogging deployments on employees without adequate prior information.

Compliance fit

For Spanish regulated companies, managing keylogging risk falls under several frameworks:

  • NIS2 (article 21). Access control, authentication, incident management measures. MFA and EDR aren't optional.
  • DORA (article 9). Technical and organisational measures to protect financial ICT systems. Includes protection against malware with keylogger module.
  • ISO 27001:2022 (controls 8.7, 8.5, 5.18). Malware protection, secure authentication, privilege management.
  • ENS Royal Decree 311/2022. Measures op.exp.6 (malicious code protection), op.acc (access control).
  • PCI DSS v4.0. Card data protection (req. 5 anti-malware, req. 8 strong authentication).

Frequently asked questions

How do I know if I have a keylogger on my machine?

The most reliable signs are indirect: accounts accessed from strange locations, passwords changed that you don't remember changing, unrecognised banking transactions, friction in applications that wasn't there before. Modern antivirus detects most commodity variants. If you suspect, scan with a second vendor antivirus (Malwarebytes, ESET, ClamAV on Linux) and review running processes and network connections. In corporate environments, contact your security team directly before manipulating the device.

Does a virtual keyboard protect against a keylogger?

Only against the most basic subtype (physical keyboard API interception). Modern keyloggers do screen scraping and form-grabbing, which also capture what's entered with a virtual keyboard. That's why banks replaced almost all virtual keyboards with MFA and out-of-band devices.

Are Linux or macOS immune?

No. There are keyloggers for the three main operating systems. The difference is that the Windows installed base makes attackers invest more there, and the strict privilege separation in modern macOS and Linux makes installing kernel-mode keyloggers somewhat harder. But a user-mode keylogger on macOS captures what you type just as well if the attacker achieves execution.

Does a VPN protect against keyloggers?

No. The keylogger captures keystrokes before they enter any encrypted connection. The VPN protects traffic in transit, which is useful against other vectors but irrelevant against an already installed keylogger.

Can my company legally install a keylogger on me?

Only under very specific conditions: written policy communicated to the employee in advance, corporate device (not personal), proportionality of the control, suitability and necessity of the means, documented legitimate purpose. Without those requirements the installation constitutes intrusion and leads to sanctions for the company. Spanish labour case law is strict on this point.

What is a keylogger used for in a professional Red Team?

Once access to a client endpoint is gained, the operator can deploy a keylogger limited in scope and time to validate whether the client's SOC and EDR detect it. The exercise goal is detection, not extracting real credentials. Contractual authorisation covers it and the data gets deleted at project closure. Detail in the Red Team business guide.

Can a keylogger be installed just by visiting a page?

Today it's very unlikely on updated browsers. Pages can inject JavaScript that captures forms (form-grabbing), but that doesn't install a persistent keylogger on the system. To infect the endpoint requires a browser vulnerability and a sandbox escape, a rare combination in 2026 without an expensive 0-day.

  • Types of malware: broader family where keyloggers sit as a module of trojans, RATs and stealers.
  • What is ransomware: many ransomware campaigns carry a keylogger in the previous phase to get privileged credentials.
  • What is an EDR and what is MDR: detection and response controls that cover modern software keyloggers.
  • What is threat hunting: the discipline hunting keylogging patterns when they haven't triggered automatic alerts.
  • Kerberos attacks in Active Directory: the natural subsequent phase when a keylogger captures privileged credentials in a Windows environment.
  • NIS2 in Spain: the regulatory framework requiring anti-malware controls and MFA in affected companies.

Keylogger defence at Secra

At Secra we assess organisations' real exposure to keyloggers on two fronts: on one side, Red Team exercises that validate whether the SOC and defensive controls detect real keylogging on client endpoints; on the other, audits of EDR configuration, privilege policy, MFA rollout and user training to keep the "compromised credential on an endpoint" scenario as contained as possible. The usual deliverable is a per-user and per-machine risk map with concrete priorities. If you want to understand how long you'd last against a campaign combining phishing and keylogger against your staff, get in touch via contact.

About the author

Secra Solutions team

Ethical hackers with OSCP, OSEP, OSWE, CRTO, CRTL and CARTE certifications, 7+ years of experience in offensive cybersecurity, and authors of CVE-2025-40652 and CVE-2023-3512.

Share article