T1649

Steal or Forge Authentication Certificates

Credential Access Last updated:

This detection identifies adversary attempts to steal or forge authentication certificates from Windows certificate stores, Active Directory Certificate Services (AD CS) infrastructure, or via crypto APIs. Key behaviors include use of certutil.exe with export flags, Mimikatz crypto module commands (crypto::certificates, crypto::capi), known AD CS abuse tools (Certify, Certipy), suspicious certificate file creation (.pfx/.p12), anomalous certificate enrollment or template modification events (Security EventIDs 4886, 4887, 4899, 4900), and process access to certificate material in LSASS or DPAPI-protected storage. Successful certificate theft enables persistent authentication as valid accounts and lateral movement without requiring password knowledge.

What is T1649 Steal or Forge Authentication Certificates?

Steal or Forge Authentication Certificates (T1649) maps to the Credential Access tactic — the adversary is trying to steal account names and passwords in MITRE ATT&CK.

This page provides production-ready detection logic for Steal or Forge Authentication Certificates, covering the data sources and telemetry it touches: Microsoft Defender for Endpoint, Windows Security Event Log. The queries below are rated high severity at medium confidence, and ship for 7 SIEM platforms — KQL, SPL, Elastic, QRadar, Sumo, YARA-L, LogScale.

MITRE ATT&CK

Tactic
Credential Access
Technique
T1649 Steal or Forge Authentication Certificates
Canonical reference
https://attack.mitre.org/techniques/T1649/
Microsoft Sentinel / Defender
kusto
let CertTheftCLIKeywords = dynamic(["-exportpfx", "exportpfx", "crypto::certificates", "crypto::capi", "crypto::keys", "/export", "-pkcs12", "adcs", "certsrv", "certstore", "-repairstore", "-importpfx"]);
let KnownCertTheftTools = dynamic(["certify.exe", "certipy.exe", "sharpdpapi.exe", "sharpweb.exe", "certstealer.exe", "ghostpack"]);
let SensitiveExtensions = dynamic([".pfx", ".p12", ".pem", ".key"]);
// Detection 1: Process-based — certutil/certreq abuse and known tools
let ProcessDetections = DeviceProcessEvents
| where TimeGenerated > ago(1d)
| where (
    (FileName =~ "certutil.exe" and ProcessCommandLine has_any (CertTheftCLIKeywords))
    or (FileName =~ "certreq.exe" and (ProcessCommandLine has "-submit" or ProcessCommandLine has "-retrieve"))
    or FileName has_any (KnownCertTheftTools)
    or ProcessCommandLine has_any ("crypto::certificates", "crypto::capi /patch", "crypto::keys /export", "sekurlsa::certificates")
  )
| extend DetectionSource = "ProcessEvent"
| extend SuspiciousIndicator = case(
    ProcessCommandLine has "exportpfx", "CertUtil Certificate Export",
    ProcessCommandLine has "crypto::certificates", "Mimikatz Cert Module",
    ProcessCommandLine has "crypto::capi", "Mimikatz CryptoAPI Patch",
    ProcessCommandLine has "crypto::keys", "Mimikatz Key Export",
    ProcessCommandLine has "sekurlsa::certificates", "Mimikatz LSA Cert Dump",
    FileName has_any (KnownCertTheftTools), "Known Cert Theft Tool",
    "Suspicious Certificate CLI Activity"
  )
| project TimeGenerated, DeviceName, AccountName, InitiatingProcessFileName,
    FileName, ProcessCommandLine, SuspiciousIndicator, FolderPath, DetectionSource;
// Detection 2: File-based — suspicious PFX/P12 written to non-standard locations
let FileDetections = DeviceFileEvents
| where TimeGenerated > ago(1d)
| where ActionType in ("FileCreated", "FileModified")
| where FileName has_any (SensitiveExtensions)
| where not(FolderPath has_any (
    "C:\\Windows\\System32\\CertSrv",
    "C:\\ProgramData\\Microsoft\\Crypto",
    "C:\\Users\\All Users\\Microsoft\\Crypto",
    "C:\\Windows\\ServiceProfiles"
  ))
| where InitiatingProcessFileName !in~ ("svchost.exe", "lsass.exe", "MicrosoftEdgeUpdate.exe")
| extend DetectionSource = "FileEvent"
| extend SuspiciousIndicator = "Certificate File Written to Non-Standard Location"
| project TimeGenerated, DeviceName, AccountName = InitiatingProcessAccountName,
    InitiatingProcessFileName, FileName, FolderPath, SuspiciousIndicator, DetectionSource;
// Detection 3: AD CS enrollment anomalies from Security event log
let ADCSDetections = SecurityEvent
| where TimeGenerated > ago(1d)
| where EventID in (4886, 4887, 4899, 4900)
| extend CertRequestDetails = parse_xml(EventData)
| where EventID in (4886, 4887) and SubjectUserName !endswith "$"
| extend DetectionSource = "SecurityEvent"
| extend SuspiciousIndicator = case(
    EventID == 4886, "AD CS Certificate Request Received (User Account)",
    EventID == 4887, "AD CS Certificate Issued to User Account",
    EventID == 4899, "AD CS Certificate Template Modified",
    EventID == 4900, "AD CS Certificate Template Security Updated",
    "AD CS Event"
  )
| project TimeGenerated, DeviceName = Computer, AccountName = SubjectUserName,
    InitiatingProcessFileName = "", FileName = "", FolderPath = "",
    SuspiciousIndicator, DetectionSource;
union ProcessDetections, FileDetections, ADCSDetections
| order by TimeGenerated desc

Detects certificate theft and forgery via three correlated signals: (1) suspicious certutil.exe or certreq.exe command-line flags for certificate export, known AD CS abuse tools (Certify, Certipy), and Mimikatz crypto module commands; (2) certificate file (.pfx/.p12/.pem) creation outside expected system certificate storage paths; (3) AD CS Security Event IDs 4886/4887 (certificate requests/issuance to non-machine accounts) and 4899/4900 (template modifications). Combines process, file, and event log telemetry for high-fidelity coverage.

high severity medium confidence

Data Sources

Microsoft Defender for Endpoint Windows Security Event Log

Required Tables

DeviceProcessEvents DeviceFileEvents SecurityEvent

False Positives

  • Legitimate PKI administrators exporting certificates for backup or migration using certutil.exe with -exportPFX
  • Web server or application administrators renewing SSL/TLS certificates and exporting as PFX for IIS or other services
  • Enterprise MDM/endpoint management tools (Intune, SCCM) that programmatically request or renew device certificates via certreq.exe
  • Security operations tooling (vulnerability scanners, certificate inventory tools) that enumerate certificate templates or stores
  • Developers testing code-signing workflows who export self-signed certificates in PFX format to non-standard directories

Sigma rule & cross-platform mapping

The detection logic for Steal or Forge Authentication Certificates (T1649) above is provided in a vendor-neutral form so you can deploy it on any SIEM. The same logic is shipped here as native KQL (Microsoft Sentinel / Defender), SPL (Splunk), Elastic (Elastic Security (EQL)), QRadar (IBM QRadar (AQL)), Sumo (Sumo Logic CSE), YARA-L (Google Chronicle / SecOps), LogScale (CrowdStrike LogScale (CQL)) queries. In Sigma terms, this detection targets the following logsource:

logsource:
  category: process_creation
  product: windows

Browse the community-maintained Sigma rules for this technique:


Testing Methodology

Validate this detection against 3 adversary techniques from Atomic Red Team. Each test below lists the behaviour to exercise and the telemetry you should expect to see. Executable commands and cleanup steps are available with Pro.

  1. Test 1Export User Certificate from Windows Store via CertUtil

    Expected signal: DeviceProcessEvents: certutil.exe with CommandLine containing '-exportPFX' and '-user'. DeviceFileEvents: FileCreated event for C:\Windows\Temp\stolen_cert.pfx. Sysmon EventID 1: certutil.exe process with full command line. Sysmon EventID 11: .pfx file creation in C:\Windows\Temp.

  2. Test 2Enumerate and Export Certificates via PowerShell CryptoAPI

    Expected signal: DeviceProcessEvents: powershell.exe with command line containing X509Store, X509ContentType, and WriteAllBytes. Sysmon EventID 1: powershell.exe with certificate store access patterns. Sysmon EventID 11: atomic_cert_export.pfx file creation in C:\Windows\Temp. This test specifically validates coverage of non-certutil.exe certificate theft.

  3. Test 3Request Certificate via CertReq Against AD CS

    Expected signal: DeviceProcessEvents: certreq.exe -new execution with INF path in CommandLine. Sysmon EventID 1: certreq.exe process creation with -new flag. Sysmon EventID 11: .csr file creation in C:\Windows\Temp. If submission step is run against a real CA: Windows Security Event 4886 on the CA server (certificate request received), followed by 4887 (issued) or 4888 (denied).


Response Playbook

Triage

  1. Step 1: Identify the triggering signal — is this a process execution (certutil/certreq/Mimikatz), file creation (.pfx/.p12), or AD CS event (4886/4887/4899)? Each has different urgency and follow-on steps.
  2. Step 2: Check the user context — was this executed by a service account, machine account ($), domain admin, or standard user? Non-machine accounts requesting certificates via AD CS are higher risk. Check if the account is authorized to enroll against the requested template.
  3. Step 3: For process detections, retrieve the full command line and identify the specific certificate operation: export (theft from local store), request/submit (enrollment abuse), or Mimikatz module (in-memory extraction). Check parent process — was this launched from a shell, Office document, or legitimate admin tool?
  4. Step 4: For certutil.exe -exportPFX, identify the target certificate thumbprint or store (My, Root, CA) and destination path. Query DeviceFileEvents for the resulting .pfx file creation and whether it was subsequently accessed, compressed, or transferred.
  5. Step 5: For AD CS events 4886/4887, extract the requested certificate template name from the event. Cross-reference against known ESC (Escalation) vulnerable templates: templates with ENROLLEE_SUPPLIES_SUBJECT + Client Authentication EKU (ESC1), or those allowing low-privilege enrollment for sensitive EKUs.
  6. Step 6: Check if the account performed this activity during normal business hours and from their usual device. Cross-reference DeviceLogonEvents for the same account in the past 24 hours — look for new logons from unusual IPs or devices preceding the certificate activity.
  7. Step 7: Search for follow-on authentication events — did the account (or a new account using the same certificate) authenticate via Kerberos (Event 4768/4769) or against Azure AD shortly after the certificate activity? Certificate theft is followed rapidly by use.
  8. Step 8: Query for network connections from the host around the time of certificate activity — look for connections to unusual external IPs that may indicate exfiltration of the PFX file via certutil -encode or direct file transfer.

Containment

  1. If certificate theft is confirmed, immediately disable the affected user or machine account in Active Directory to prevent certificate-based authentication while investigation continues (the certificate remains valid even after password reset).
  2. Revoke the specific certificate(s) identified as stolen or forged via the CA's certificate revocation list (CRL) — run `certutil -revoke <SerialNumber> <ReasonCode>` on the issuing CA, then force a CRL publication with `certutil -crl`.
  3. If a vulnerable AD CS template was exploited (ESC1-ESC8), immediately restrict enrollment rights on the template via the Certificate Templates MMC snap-in — remove the authenticated users or domain users enrollment permission and replace with explicit authorized groups.
  4. Isolate the endpoint where certificate theft occurred via EDR network containment if Mimikatz or offensive tooling was executed — the host is likely fully compromised beyond certificate theft.
  5. If golden certificate attack is suspected (root CA key compromise), treat as a full PKI compromise: take all CA servers offline, initiate emergency PKI rebuild procedure, and issue emergency advisories to all relying parties.
  6. Rotate the machine or user certificate by requesting a new one and revoking the old one, ensuring the new certificate is issued from a clean enrollment process with verified identity.
  7. For Azure AD / Entra ID device certificate abuse (AADInternals), revoke the device registration in Entra ID admin center under Devices — this invalidates the device certificate used for PRT (Primary Refresh Token) acquisition.

Evidence Collection

  1. Export the Windows Certificate Store from the affected host: `certutil -user -store My > C:\temp\certstore_user.txt` and `certutil -store My > C:\temp\certstore_machine.txt` — document all certificates, their thumbprints, issuers, and expiry dates.
  2. Collect the Security event log from both the affected workstation and the issuing CA server, filtered to EventIDs 4886, 4887, 4888, 4890, 4899, 4900 for the relevant time window.
  3. Collect Sysmon logs (EventIDs 1, 3, 11) from the affected endpoint covering the 2-hour window around the detected event — export as EVTX for offline analysis.
  4. If certutil.exe was used, recover the .pfx file from the destination path — hash it and check for transfer artifacts (LNK files, recent documents, clipboard history via forensic triage).
  5. Run `certutil -verifystore -user My <thumbprint>` to verify certificate chain integrity and identify if a CA cert is involved.
  6. Collect the Active Directory Certificate Services audit log from all CA servers: Event Log path is `Applications and Services Logs\Microsoft\Windows\CertificationAuthority\Operational`.
  7. Pull the CA's issued certificate database: `certutil -view -out RequestID,RequesterName,NotAfter,CommonName,CertificateTemplate,Request.RawRequest > C:\temp\ca_issued_certs.txt` — identify any recently issued certs with suspicious SANs or requesters.
  8. Capture memory dump of LSASS if Mimikatz execution is confirmed — certificate material including private keys may be recoverable for forensic analysis and to understand full scope of extraction.
  9. Export relevant prefetch files from `C:\Windows\Prefetch\` for certutil.exe, certreq.exe, powershell.exe, and any identified offensive tools to establish execution timeline.

Escalation Criteria

  • ! Escalate immediately to senior IR if a CA server itself (root or subordinate) shows signs of compromise — this enables golden certificate attacks that can forge authentication for any domain identity indefinitely.
  • ! Escalate if the stolen or forged certificate contains a Subject Alternative Name (SAN) that impersonates a privileged account (Domain Admin, Enterprise Admin, service accounts with admin rights).
  • ! Escalate if certificate theft is combined with evidence of lateral movement — new logons from the affected account to domain controllers, servers, or cloud resources (Azure/AWS/GCP) immediately after the certificate activity.
  • ! Escalate if Kerberos ticket requests (Event 4768/4769) or Azure AD token acquisitions are observed for accounts other than the legitimate owner using the stolen certificate material.
  • ! Escalate if the incident involves AADInternals or similar tools targeting Azure AD / Entra ID device certificate abuse — this can lead to PRT (Primary Refresh Token) theft enabling persistent cloud access.
  • ! Escalate if multiple hosts in the environment show similar certificate theft indicators within the same time window — this suggests automated tooling and a broader campaign rather than isolated incident.

Investigation Guide

Forensic Artifacts

  • > Windows Certificate Store (HKCU\Software\Microsoft\SystemCertificates and HKLM\Software\Microsoft\SystemCertificates) — user and machine cert stores where certificates and private keys are held
  • > DPAPI master keys (C:\Users\<user>\AppData\Roaming\Microsoft\Protect\<SID>\) — certificate private keys in user store are protected by DPAPI; theft requires DPAPI decryption
  • > CNG key storage (C:\Users\<user>\AppData\Roaming\Microsoft\Crypto\Keys\ and C:\ProgramData\Microsoft\Crypto\) — CNG-backed private keys stored here
  • > Prefetch files for certutil.exe (C:\Windows\Prefetch\CERTUTIL.EXE-*.pf) — confirms execution and lists files accessed including source/destination paths
  • > AD CS audit log (Applications and Services Logs\Microsoft\Windows\CertificationAuthority\Operational) on CA servers
  • > CA database — certsrv.msc or `certutil -view` output showing all issued certificates, requesters, and SANs
  • > Windows Security EventIDs 4886, 4887, 4888, 4899, 4900 on CA servers
  • > Sysmon EventID 1 (process create), EventID 11 (file create for .pfx/.p12), EventID 3 (network — certutil may connect to OCSP/CRL endpoints during operations)
  • > .pfx / .p12 / .cer files in user temp directories, downloads, or desktop — evidence of exported certificate material
  • > Registry key HKLM\SYSTEM\CurrentControlSet\Services\CertSvc\Configuration — CA configuration including enabled templates
  • > Memory artifacts from LSASS process if Mimikatz crypto::capi was used (patches CryptoAPI to allow private key export)

Tuning Guidance

The primary source of false positives is legitimate PKI administration: schedule a baseline audit of which accounts regularly use certutil.exe -exportPFX (typically domain admins during cert backup windows) and create exceptions by AccountName + DeviceName pairs for authorized PKI admin workstations. For AD CS enrollment events (4886/4887), build a baseline of expected certificate templates requested by standard users — most endpoints should only request templates like 'User', 'Computer', or 'Workstation Authentication'; any request for 'SubCA', 'WebServer', or custom templates with SAN rights from a non-PKI-admin account should remain alerting. For the file creation detection (.pfx/.p12), tune the exclusion list to include known legitimate certificate storage paths used by your web server farm, load balancers, or DevOps pipelines (e.g., CI/CD agents that build SSL cert bundles). Consider adding an account-type filter to exclude service accounts that legitimately automate certificate renewal. The Kerberos PKINIT hunting query threshold of 5/hour should be adjusted based on your environment — some SSO-heavy environments may see higher legitimate PKINIT rates from smart card users or certificate-based auth services.


Hunting Queries

Hunts for users enrolling certificates more than 3 times in a single day via AD CS (Security EventID 4887). Adversaries exploiting ESC vulnerabilities or performing bulk certificate theft via re-enrollment will show elevated enrollment counts. Excludes machine accounts (ending in $) which legitimately auto-renew.

Hunting — KQL
kql
// Hunt: Identify any certificate enrollment against templates with SAN supply enabled (ESC1 pattern)
// This requires AD CS audit events from the CA server
SecurityEvent
| where TimeGenerated > ago(30d)
| where EventID == 4887
| where Computer has_any ("CA", "PKI", "CERTSRV") // adjust to your CA server names
| extend EventXml = parse_xml(EventData)
| extend RequesterName = tostring(EventXml.EventData.Data[0])
| extend CertificateTemplateName = tostring(EventXml.EventData.Data[5])
| extend SerialNumber = tostring(EventXml.EventData.Data[3])
| where RequesterName !endswith "$" // exclude machine accounts
| summarize EnrollmentCount = count(), TemplateList = make_set(CertificateTemplateName) by RequesterName, bin(TimeGenerated, 1d)
| where EnrollmentCount > 3
| order by EnrollmentCount desc
Hunting — SPL
spl
index=* sourcetype="WinEventLog:Security" EventCode=4887 earliest=-30d
| where NOT like(SubjectUserName,"%$")
| rex field=Message "Certificate Template:\s+(?<TemplateName>[^\r\n]+)"
| rex field=Message "Serial Number:\s+(?<SerialNumber>[^\r\n]+)"
| stats count AS EnrollmentCount, values(TemplateName) AS Templates BY SubjectUserName, date_mday, date_month
| where EnrollmentCount > 3
| sort - EnrollmentCount

Hunts for certutil.exe making outbound network connections to external (non-RFC1918) addresses. Adversaries use certutil -urlcache to download payloads (living off the land) or may use it to upload exfiltrated certificate data. Legitimate certutil CRL/OCSP checks go to known PKI infrastructure addresses — outliers in this query warrant investigation.

Hunting — KQL
kql
// Hunt: Find certutil.exe used with network connectivity — exfiltration via certutil -decode or -urlcache
DeviceNetworkEvents
| where TimeGenerated > ago(14d)
| where InitiatingProcessFileName =~ "certutil.exe"
| where RemoteIPType != "Private" and RemoteIPType != "Loopback"
| join kind=leftouter (
    DeviceProcessEvents
    | where FileName =~ "certutil.exe"
    | project DeviceName, ProcessId, ProcessCommandLine, InitiatingProcessFileName
  ) on DeviceName, $left.InitiatingProcessId == $right.ProcessId
| project TimeGenerated, DeviceName, AccountName, ProcessCommandLine, RemoteIP, RemoteUrl, RemotePort
| where ProcessCommandLine !has "-verify" and ProcessCommandLine !has "-url"
| order by TimeGenerated desc
Hunting — SPL
spl
index=* sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=3 earliest=-14d
| where like(lower(Image),"%certutil.exe")
| where NOT (like(DestinationIp,"10.%") OR like(DestinationIp,"192.168.%") OR like(DestinationIp,"172.1%") OR DestinationIp="127.0.0.1")
| table _time, Computer, User, Image, CommandLine, DestinationIp, DestinationPort, DestinationHostname
| sort - _time

Hunts for high-frequency PKINIT (certificate-based) Kerberos TGT requests from user accounts. Fields CertIssuerName and CertSerialNumber being populated in Event 4768 indicate certificate-based authentication was used. More than 5 PKINIT auths per hour for a user account is anomalous and may indicate automated use of a stolen certificate to repeatedly acquire TGTs.

Hunting — KQL
kql
// Hunt: Detect Kerberos PKINIT authentication — certificates being used for TGT acquisition
// This catches stolen certificates actually being leveraged for authentication
SecurityEvent
| where TimeGenerated > ago(14d)
| where EventID == 4768 // Kerberos TGT Request
| extend CertIssuerName = tostring(parse_xml(EventData).EventData.Data[5])
| extend CertSerialNumber = tostring(parse_xml(EventData).EventData.Data[6])
| where CertIssuerName != "-" and CertSerialNumber != "-" // PKINIT used a certificate
| where TargetUserName !endswith "$" // not machine account
| summarize PKINITCount = count(), Issuers = make_set(CertIssuerName), SerialNumbers = make_set(CertSerialNumber) by TargetUserName, TargetDomainName, IpAddress, bin(TimeGenerated, 1h)
| where PKINITCount > 5
| order by PKINITCount desc
Hunting — SPL
spl
index=* sourcetype="WinEventLog:Security" EventCode=4768 earliest=-14d
| rex field=Message "Certificate Issuer Name:\s+(?<CertIssuer>[^\r\n]+)"
| rex field=Message "Certificate Serial Number:\s+(?<CertSerial>[^\r\n]+)"
| where CertIssuer != "-" AND CertSerial != "-"
| where NOT like(TargetUserName,"%$")
| stats count AS PKINITCount, values(CertIssuer) AS Issuers BY TargetUserName, IpAddress, date_mday
| where PKINITCount > 5
| sort - PKINITCount

Hunts for unexpected processes opening LSASS (Sysmon EventID 10), which is the mechanism Mimikatz uses for crypto::capi patching and sekurlsa::certificates to extract certificate material from LSA memory. Filters known-legitimate LSASS accessors (AV, WER, task manager). Any unexpected process with OpenProcess rights to LSASS warrants investigation for certificate theft.

Hunting — KQL
kql
// Hunt: Process access to CNG key material or CAPI crypto contexts — in-memory cert theft
DeviceEvents
| where TimeGenerated > ago(14d)
| where ActionType == "OpenProcessApiCall"
| where FileName =~ "lsass.exe"
| where InitiatingProcessFileName !in~ ("MsMpEng.exe", "svchost.exe", "csrss.exe", "werfault.exe", "WerFaultSecure.exe", "taskmgr.exe", "procexp.exe", "procexp64.exe")
| where InitiatingProcessCommandLine !has "Microsoft Monitoring Agent"
| project TimeGenerated, DeviceName, InitiatingProcessAccountName, InitiatingProcessFileName,
    InitiatingProcessCommandLine, InitiatingProcessParentFileName
| order by TimeGenerated desc
Hunting — SPL
spl
index=* sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=10 earliest=-14d
| where TargetImage LIKE "%lsass.exe"
| where NOT (Image LIKE "%MsMpEng.exe" OR Image LIKE "%svchost.exe" OR Image LIKE "%csrss.exe" OR Image LIKE "%werfault.exe" OR Image LIKE "%taskmgr.exe")
| table _time, Computer, User, Image, CommandLine, TargetImage, GrantedAccess
| sort - _time

Atomic Red Team Tests

Test 1 Export User Certificate from Windows Store via CertUtil
windows

Simulates an adversary exporting a certificate with private key from the current user's personal certificate store using the built-in certutil.exe utility. This is a common first step in certificate theft — the exported PFX can then be used for authentication on another host.

Command

powershell
# First create a self-signed test certificate to export (run as target user)
$cert = New-SelfSignedCertificate -DnsName "test.corp.local" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable
$thumbprint = $cert.Thumbprint
Write-Output "Created cert with thumbprint: $thumbprint"

# Export using certutil (adversary technique)
certutil.exe -user -exportPFX -p "Password123" My $thumbprint C:\Windows\Temp\stolen_cert.pfx
Write-Output "Export result: $LASTEXITCODE"

Cleanup

powershell
# Remove the test certificate
$thumbprint = (Get-ChildItem Cert:\CurrentUser\My | Where-Object {$_.Subject -like '*test.corp.local*'} | Select-Object -First 1).Thumbprint
if ($thumbprint) { certutil.exe -user -delstore My $thumbprint }
Remove-Item C:\Windows\Temp\stolen_cert.pfx -Force -ErrorAction SilentlyContinue

Expected Telemetry

DeviceProcessEvents: certutil.exe with CommandLine containing '-exportPFX' and '-user'. DeviceFileEvents: FileCreated event for C:\Windows\Temp\stolen_cert.pfx. Sysmon EventID 1: certutil.exe process with full command line. Sysmon EventID 11: .pfx file creation in C:\Windows\Temp.

Expected Detection

KQL ProcessDetections branch fires on certutil.exe with '-exportpfx' in CommandLine. SPL Sysmon EventCode=1 branch fires with CertUtil Certificate Export indicator. FileDetections branch fires for .pfx creation in C:\Windows\Temp (non-standard path).

Test 2 Enumerate and Export Certificates via PowerShell CryptoAPI
windows

Simulates adversary use of PowerShell to enumerate the certificate store and export certificates with exportable private keys — mimicking what tools like CertStealer and Certify do programmatically via the .NET CryptoAPI without spawning certutil.exe.

Command

powershell
# Enumerate exportable certificates in the current user store
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store('My','CurrentUser')
$store.Open('ReadOnly')
$exportableCerts = $store.Certificates | Where-Object { $_.HasPrivateKey -and ($_.PrivateKey.CspKeyContainerInfo.Exportable -eq $true -or $_.PrivateKey -ne $null) }

Write-Output "[*] Found $($exportableCerts.Count) potentially exportable certificates:"
$exportableCerts | ForEach-Object {
    Write-Output "  Subject: $($_.Subject) | Thumbprint: $($_.Thumbprint) | EKU: $(($_.EnhancedKeyUsageList | Select-Object -ExpandProperty FriendlyName) -join ', ')"
}
$store.Close()

# Export first exportable cert to PFX (if any found)
if ($exportableCerts.Count -gt 0) {
    $certToExport = $exportableCerts | Select-Object -First 1
    $pfxBytes = $certToExport.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx, 'AtomicTest123')
    [System.IO.File]::WriteAllBytes('C:\Windows\Temp\atomic_cert_export.pfx', $pfxBytes)
    Write-Output "[+] Exported certificate to C:\Windows\Temp\atomic_cert_export.pfx"
}

Cleanup

powershell
Remove-Item C:\Windows\Temp\atomic_cert_export.pfx -Force -ErrorAction SilentlyContinue

Expected Telemetry

DeviceProcessEvents: powershell.exe with command line containing X509Store, X509ContentType, and WriteAllBytes. Sysmon EventID 1: powershell.exe with certificate store access patterns. Sysmon EventID 11: atomic_cert_export.pfx file creation in C:\Windows\Temp. This test specifically validates coverage of non-certutil.exe certificate theft.

Expected Detection

FileDetections branch in KQL should fire on .pfx file creation in C:\Windows\Temp by powershell.exe (non-standard path, non-standard initiating process). SPL Sysmon EventCode=11 branch fires for .pfx in non-system path. Note: Process detection branch will NOT fire as this doesn't use certutil.exe — this test validates the necessity of the file creation detection layer.

Test 3 Request Certificate via CertReq Against AD CS
windows

Simulates an adversary requesting a certificate from an Active Directory Certificate Services CA using certreq.exe. This mimics the initial enrollment phase of ESC1/ESC3/ESC4 AD CS abuse where attackers request certificates using vulnerable templates. Requires a CA to be reachable — adapt CA name and template to your lab environment.

Command

powershell
# Create a certificate request INF file (simulating ESC1 — supplying a SAN)
$reqInf = @"
[NewRequest]
Subject = "CN=AtomicTestUser,DC=corp,DC=local"
KeySpec = 1
KeyLength = 2048
Exportable = TRUE
MachineKeySet = FALSE
SMIME = FALSE
PrivateKeyArchive = FALSE
UserProtected = FALSE
UseExistingKeySet = FALSE
ProviderName = "Microsoft RSA SChannel Cryptographic Provider"
RequestType = PKCS10

[Extensions]
; SAN extension — this is the ESC1 abuse pattern (supplying alternate identity)
2.5.29.17 = "{text}[email protected]"
"@

$reqInf | Out-File -FilePath C:\Windows\Temp\atomic_cert_request.inf -Encoding ASCII

# Create the CSR from the INF
certreq.exe -new C:\Windows\Temp\atomic_cert_request.inf C:\Windows\Temp\atomic_cert_request.csr

Write-Output "[*] CSR created at C:\Windows\Temp\atomic_cert_request.csr"
Write-Output "[*] In a real attack, the next step would be: certreq.exe -submit -config <CA-Server>\<CA-Name> C:\Windows\Temp\atomic_cert_request.csr"
Write-Output "[!] Submission step skipped — adapt CA-Server and CA-Name for your lab environment"

Cleanup

powershell
Remove-Item C:\Windows\Temp\atomic_cert_request.inf -Force -ErrorAction SilentlyContinue
Remove-Item C:\Windows\Temp\atomic_cert_request.csr -Force -ErrorAction SilentlyContinue
certutil.exe -user -delstore request "AtomicTestUser" 2>$null

Expected Telemetry

DeviceProcessEvents: certreq.exe -new execution with INF path in CommandLine. Sysmon EventID 1: certreq.exe process creation with -new flag. Sysmon EventID 11: .csr file creation in C:\Windows\Temp. If submission step is run against a real CA: Windows Security Event 4886 on the CA server (certificate request received), followed by 4887 (issued) or 4888 (denied).

Expected Detection

SPL branch for certreq.exe -submit fires if submission step is executed. KQL ProcessDetections fires on certreq.exe with -submit or -retrieve in CommandLine. AD CS EventID 4886/4887 on CA server triggers ADCSDetections branch if enrollment succeeds. This test validates coverage of the certificate request phase of AD CS abuse.

Related Detections