Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
207 changes: 203 additions & 4 deletions powershell/internal/services/ad/queries/Get-MtLdapServiceAccount.ps1
Original file line number Diff line number Diff line change
@@ -1,15 +1,214 @@
function Get-MtLdapServiceAccount {
<#
.SYNOPSIS
Collects gMSA identity and managed-password retrieval authorization without requesting the password.
.NOTES
Author: Mario Contestabile
LinkedIn: https://www.linkedin.com/in/mario-contestabile/
#>
[CmdletBinding()]
[OutputType([object[]])]
param(
[Parameter(Mandatory)]
[System.DirectoryServices.Protocols.LdapConnection] $Connection,

[string] $SearchBase
)

if ([string]::IsNullOrWhiteSpace($SearchBase)) { $SearchBase = (Get-MtLdapRootDse -Connection $Connection).DefaultNamingContext }
$attributes = @('distinguishedName', 'name', 'sAMAccountName', 'dNSHostName', 'whenCreated', 'whenChanged', 'objectSid')
if ([string]::IsNullOrWhiteSpace($SearchBase)) {
$SearchBase = (Get-MtLdapRootDse -Connection $Connection).DefaultNamingContext
}

function ConvertTo-MtGmsaSidFilterValue {
param([Parameter(Mandatory)][object]$Sid)

# Convert the textual SID to the escaped little-endian binary form required by an LDAP objectSid equality filter.
$sidValue = if ($null -ne $Sid.PSObject.Properties['Value']) { [string]$Sid.Value } else { [string]$Sid }
$parts = $sidValue -split '-'
if ($parts.Count -lt 4 -or $parts[0] -ne 'S') { return $null }

$bytes = [System.Collections.Generic.List[byte]]::new()
$bytes.Add([byte]$parts[1])
$bytes.Add([byte]($parts.Count - 3))
$authority = [uint64]$parts[2]
for ($shift = 40; $shift -ge 0; $shift -= 8) {
$bytes.Add([byte](($authority -shr $shift) -band 0xff))
}
for ($index = 3; $index -lt $parts.Count; $index++) {
$bytes.AddRange([BitConverter]::GetBytes([uint32]$parts[$index]))
}
return (($bytes | ForEach-Object { '\{0:x2}' -f $_ }) -join '')
}

# Request the authorization descriptor only. The managed-password value is intentionally excluded.
$attributes = @(
'distinguishedName','name','sAMAccountName','dNSHostName','whenCreated','whenChanged',
'objectSid','userAccountControl','msDS-GroupMSAMembership'
)
$entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(objectClass=msDS-GroupManagedServiceAccount)' -Attributes $attributes)
return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; SamAccountName = [string]$_.sAMAccountName; DnsHostName = [string]$_.dNSHostName; Created = $_.whenCreated; Modified = $_.whenChanged; Sid = $_.objectSid } })

$broadSidMap = [ordered]@{
'S-1-1-0'='Everyone'
'S-1-5-7'='Anonymous Logon'
'S-1-5-11'='Authenticated Users'
'S-1-5-32-545'='BUILTIN\Users'
}

function Get-MtGmsaBroadPrincipalName {
param([string]$Sid)
if ($broadSidMap.Contains($Sid)) { return $broadSidMap[$Sid] }
if ($Sid -match '^S-1-5-21-\d+-\d+-\d+-513$') { return 'Domain Users' }
if ($Sid -match '^S-1-5-21-\d+-\d+-\d+-515$') { return 'Domain Computers' }
return $null
}

function Test-MtGmsaPasswordRetrievalAccessMask {
param([object]$AccessMask)
try {
$signedMask=[int64]$AccessMask
if($signedMask -lt 0){$signedMask+=4294967296L}
if($signedMask -gt [uint32]::MaxValue){return $false}
$mask=[uint32]$signedMask
} catch { return $false }
$rightDsReadProperty=[uint32]0x00000010
$genericAll=[uint32]0x10000000
$genericRead=[uint32]2147483648
return (($mask -band $rightDsReadProperty) -ne 0) -or (($mask -band $genericAll) -ne 0) -or (($mask -band $genericRead) -ne 0)
}

# Cache SID lookups for this collection because the same host or group often authorizes several gMSAs.
$sidResolutionCache = @{}

return @($entries | ForEach-Object {
$entry = $_
$descriptorError = $null
$descriptorStatus = 'Unknown'
$descriptor = $null
$rawDescriptor = $entry.'msDS-GroupMSAMembership'

if ($null -eq $rawDescriptor) {
$descriptorStatus = 'AuthorizationDescriptorAbsent'
} else {
if ($null -ne $rawDescriptor.PSObject.Properties['Value']) {
$rawDescriptor = $rawDescriptor.Value
}
while ($rawDescriptor -is [System.Array] -and $rawDescriptor -isnot [byte[]]) {
$items=@($rawDescriptor)
$allBytes=$items.Count -gt 0 -and @($items|Where-Object{$_ -isnot [byte] -and -not($_ -is [int] -and $_ -ge 0 -and $_ -le 255)}).Count -eq 0
if($allBytes){$rawDescriptor=[byte[]]@($items|ForEach-Object{[byte]$_});break}
if($items.Count -eq 0){$descriptorStatus='AuthorizationDescriptorEmpty';break}
if($items.Count -ne 1){$descriptorStatus='AuthorizationDescriptorUnsupportedShape';$descriptorError="Authorization descriptor returned $($items.Count) values.";break}
$rawDescriptor=$items[0]
if ($null -ne $rawDescriptor -and $null -ne $rawDescriptor.PSObject.Properties['Value']) {$rawDescriptor=$rawDescriptor.Value}
}

if($rawDescriptor -is [byte[]]){
if($rawDescriptor.Length -eq 0){
$descriptorStatus='AuthorizationDescriptorEmpty'
} else {
try{
$descriptor=ConvertFrom-MtLdapSecurityDescriptor -RawSecurityDescriptor $rawDescriptor
if($null -ne $descriptor){$descriptorStatus='Complete'}else{$descriptorStatus='AuthorizationDescriptorParseFailure';$descriptorError='Security descriptor parser returned no result.'}
}catch{$descriptorStatus='AuthorizationDescriptorParseFailure';$descriptorError=$_.Exception.Message}
}
} elseif($descriptorStatus -eq 'Unknown') {
$descriptorStatus='AuthorizationDescriptorUnsupportedShape'
$descriptorError="Unsupported authorization descriptor type: $($rawDescriptor.GetType().FullName)"
}
}

$trustees=@()
if($null -ne $descriptor){
$trustees=@($descriptor.Access | Where-Object { $_.AccessControlType -eq 'Allow' -and (Test-MtGmsaPasswordRetrievalAccessMask -AccessMask $_.AccessMask) } | ForEach-Object {
$ace = $_
$sid=[string]$ace.Sid
$resolution = $null


$broadPrincipalName=Get-MtGmsaBroadPrincipalName -Sid $sid
if($broadPrincipalName){
$resolution=[pscustomobject][ordered]@{
Status='WellKnownBroadPrincipal';Name=$broadPrincipalName;SamAccountName=$null
DistinguishedName=$null;ObjectClass=$null;Error=$null
}
} elseif($sidResolutionCache.ContainsKey($sid)) {
$resolution=$sidResolutionCache[$sid]
} else {
try {
$sidFilter=ConvertTo-MtGmsaSidFilterValue -Sid $sid
if($null -eq $sidFilter){
$resolution=[pscustomobject][ordered]@{Status='ResolutionError';Name=$null;SamAccountName=$null;DistinguishedName=$null;ObjectClass=$null;Error='SID could not be converted to an LDAP filter value.'}
} else {
# Resolve the authorized SID through LDAP without reading the managed-password attribute.
$principal=Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter "(objectSid=$sidFilter)" -Attributes @('distinguishedName','name','sAMAccountName','objectClass','objectSid') -PageSize 0 | Select-Object -First 1
if($null -eq $principal){
$resolution=[pscustomobject][ordered]@{Status='Unresolved';Name=$null;SamAccountName=$null;DistinguishedName=$null;ObjectClass=$null;Error=$null}
} else {
$classes=@($principal.objectClass)
$leafClass=if($classes.Count){[string]$classes[-1]}else{$null}
$status=switch -Regex ($leafClass) {
'^group$' {'ResolvedGroup';break}
'^computer$' {'ResolvedComputer';break}
'^user$' {'ResolvedUser';break}
'^foreignSecurityPrincipal$' {'ForeignSecurityPrincipal';break}
default {'ResolvedPrincipal'}
}
$resolution=[pscustomobject][ordered]@{
Status=$status;Name=[string]$principal.name;SamAccountName=[string]$principal.sAMAccountName
DistinguishedName=[string]$principal.DistinguishedName;ObjectClass=$leafClass;Error=$null
}
}
}
} catch {
$resolution=[pscustomobject][ordered]@{Status='ResolutionError';Name=$null;SamAccountName=$null;DistinguishedName=$null;ObjectClass=$null;Error=$_.Exception.Message}
}
$sidResolutionCache[$sid]=$resolution
}

$isUnresolved=$resolution.Status -in @('Unresolved','ResolutionError','ForeignSecurityPrincipal')
[pscustomobject][ordered]@{
Sid=$sid
Name=if($resolution.Name){$resolution.Name}else{[string]$ace.IdentityReference}
SamAccountName=$resolution.SamAccountName
DistinguishedName=$resolution.DistinguishedName
ObjectClass=$resolution.ObjectClass
ResolutionStatus=$resolution.Status
ResolutionError=$resolution.Error
Classification=if($broadPrincipalName){'Broad'}elseif($isUnresolved){'Unresolved'}else{'Delegated'}
BroadPrincipalName=$broadPrincipalName
AccessMask=$ace.AccessMask
IsInherited=[bool]$ace.IsInherited
AuthorizationSource='msDS-GroupMSAMembership'
AuthorizationType=if($resolution.Status -eq 'ResolvedGroup'){'DirectGroup'}else{'DirectPrincipal'}
NestedExpansionStatus=if($resolution.Status -eq 'ResolvedGroup'){'NotEvaluated'}else{'NotApplicable'}
}
})
}

$rawUserAccountControl=$entry.userAccountControl
if($null -ne $rawUserAccountControl -and $null -ne $rawUserAccountControl.PSObject.Properties['Value']){$rawUserAccountControl=$rawUserAccountControl.Value}
if($rawUserAccountControl -is [System.Array]){$rawUserAccountControl=@($rawUserAccountControl)[0]}
$enabled=$null
if($null -ne $rawUserAccountControl){
try{$enabled=(([uint32]$rawUserAccountControl -band [uint32]0x00000002) -eq 0)}catch{$enabled=$null}
}

[pscustomobject][ordered]@{
DistinguishedName=[string]$entry.DistinguishedName
Name=[string]$entry.name
SamAccountName=[string]$entry.sAMAccountName
DnsHostName=[string]$entry.dNSHostName
Created=$entry.whenCreated
Modified=$entry.whenChanged
Sid=$entry.objectSid
ObjectClass=@('msDS-GroupManagedServiceAccount')
ServiceAccountType='GroupManagedServiceAccount'
Enabled=$enabled
PasswordRetrievalTrustees=$trustees
BroadPasswordRetrievalTrustees=@($trustees|Where-Object Classification -eq 'Broad')
UnresolvedPasswordRetrievalTrustees=@($trustees|Where-Object Classification -eq 'Unresolved')
AuthorizationEvidenceComplete=($descriptorStatus -eq 'Complete')
AuthorizationEvidenceStatus=$descriptorStatus
AuthorizationCollectionError=$descriptorError
}
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
BeforeAll { $script:Source = Get-Content -LiteralPath (Join-Path $PSScriptRoot '../../../../tests/ad/security/Test.AD-MSA-03.ps1') -Raw }
Describe 'AD-MSA-03 clean evidence disposition contract' {
It 'returns success without Investigate when all evidence is complete' {
$branch=[regex]::Match($script:Source,'if \(\$incomplete.Count -eq 0\).*?\n\s*}','Singleline').Value
$branch | Should -Match 'return \$true'
$branch | Should -Not -Match '-Investigate'
}
}
105 changes: 105 additions & 0 deletions powershell/tests/ad/collection/ADGmsaPasswordAuthorization.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
BeforeAll { Import-Module "$PSScriptRoot/../../../Maester.psd1" -Force }
Describe 'gMSA managed-password authorization source contract' {
It 'never requests or decodes the managed password value' {
$source=Get-Content "$PSScriptRoot/../../../internal/services/ad/queries/Get-MtLdapServiceAccount.ps1" -Raw
$source | Should -Not -Match '(?i)[''"]msDS-ManagedPassword[''"]'
$source | Should -Not -Match 'ConvertFrom-.*ManagedPassword|kinit|New-PSSession|Get-Credential|Invoke-Command'
$source | Should -Match 'msDS-GroupMSAMembership'
}
It 'requires an applicable retrieval access mask' {
$source=Get-Content "$PSScriptRoot/../../../internal/services/ad/queries/Get-MtLdapServiceAccount.ps1" -Raw
$source | Should -Match 'rightDsReadProperty'
$source | Should -Match 'genericRead'
$source | Should -Match 'genericAll'
$source | Should -Match 'Test-MtGmsaPasswordRetrievalAccessMask'
}
It 'recognizes broad domain and builtin groups' {
$source=Get-Content "$PSScriptRoot/../../../internal/services/ad/queries/Get-MtLdapServiceAccount.ps1" -Raw
$source | Should -Match 'S-1-5-32-545'
$source | Should -Match '-513\$'
$source | Should -Match '-515\$'
$source | Should -Match 'Get-MtGmsaBroadPrincipalName'
}
It 'records explicit resolution and evidence status values' {
$source=Get-Content "$PSScriptRoot/../../../internal/services/ad/queries/Get-MtLdapServiceAccount.ps1" -Raw
$source | Should -Match 'ResolutionStatus'
$source | Should -Match 'AuthorizationDescriptorAbsent'
$source | Should -Match 'AuthorizationDescriptorEmpty'
$source | Should -Match 'AuthorizationDescriptorParseFailure'
$source | Should -Match 'AuthorizationDescriptorUnsupportedShape'
}
It 'uses registered taxonomy and High severity for AD-MSA-02' {
$test02=Get-Content "$PSScriptRoot/../../../../tests/ad/security/Test.AD-MSA-02.ps1" -Raw
$test03=Get-Content "$PSScriptRoot/../../../../tests/ad/security/Test.AD-MSA-03.ps1" -Raw
foreach($testSource in @($test02,$test03)){$testSource|Should -Match "Feature='account-security'";$testSource|Should -Match "ResourceType='Computer'"}
$test02 | Should -Match "Area='applications'"
$test03 | Should -Match "Area='applications'"
$test02 | Should -Match "Severity='High'"
}
It 'does not permit a clean pass when ServiceAccounts state is unavailable' {
foreach($path in @("$PSScriptRoot/../../../../tests/ad/security/Test.AD-MSA-02.ps1","$PSScriptRoot/../../../../tests/ad/security/Test.AD-MSA-03.ps1")){(Get-Content $path -Raw)|Should -Match '\$null -eq \$state\.ServiceAccounts'}
}
It 'reports unresolved SID resolution details' {
$source=Get-Content "$PSScriptRoot/../../../../tests/ad/security/Test.AD-MSA-03.ps1" -Raw
$source|Should -Match 'ResolutionStatus';$source|Should -Match 'ResolutionError';$source|Should -Match '\$trustee\.Sid'
}
It 'classifies signed GENERIC_READ through the collector and rejects READ_CONTROL-only ACEs' {
InModuleScope Maester {
$connection = [Runtime.Serialization.FormatterServices]::GetUninitializedObject(
[System.DirectoryServices.Protocols.LdapConnection]
)

Mock Invoke-MtLdapSearch {
[pscustomobject]@{
DistinguishedName = 'CN=svc-web,CN=Managed Service Accounts,DC=contoso,DC=com'
name = 'svc-web'
sAMAccountName = 'svc-web$'
dNSHostName = 'svc-web.contoso.com'
objectSid = 'S-1-5-21-1-2-3-1101'
userAccountControl = 2
'msDS-GroupMSAMembership' = [byte[]](1, 2, 3, 4)
}
} -ParameterFilter {
$Filter -eq '(objectClass=msDS-GroupManagedServiceAccount)'
}

Mock ConvertFrom-MtLdapSecurityDescriptor {
[pscustomobject]@{
Access = @(
[pscustomobject]@{
AccessControlType = 'Allow'
AccessMask = -2147483648
Sid = 'S-1-5-32-545'
IdentityReference = 'BUILTIN\Users'
IsInherited = $false
}
[pscustomobject]@{
AccessControlType = 'Allow'
AccessMask = 131072
Sid = 'S-1-5-11'
IdentityReference = 'NT AUTHORITY\Authenticated Users'
IsInherited = $false
}
)
}
}

$result = @(
Get-MtLdapServiceAccount `
-Connection $connection `
-SearchBase 'DC=contoso,DC=com'
)

$result.Count | Should -Be 1
$result[0].PasswordRetrievalTrustees.Count | Should -Be 1
$result[0].BroadPasswordRetrievalTrustees.Count | Should -Be 1
$result[0].Enabled | Should -BeFalse

$trustee = $result[0].BroadPasswordRetrievalTrustees[0]
$trustee.Sid | Should -Be 'S-1-5-32-545'
$trustee.Classification | Should -Be 'Broad'
$trustee.BroadPrincipalName | Should -Be 'BUILTIN\Users'
$result[0].PasswordRetrievalTrustees.Sid | Should -Not -Contain 'S-1-5-11'
}
}
}
9 changes: 9 additions & 0 deletions tests/ad/security/Test.AD-MSA-02.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The `msDS-GroupMSAMembership` authorization descriptor controls which principals can retrieve a group Managed Service Account password. Broad trustees can extend retrieval eligibility beyond the intended service hosts. This includes well-known broad identities, BUILTIN\Users, Domain Users, and Domain Computers when an applicable password-retrieval Allow ACE is present.

This test reads authorization metadata only. It does not request, decode, export, store, or use `msDS-ManagedPassword`.

#### Remediation action
Replace broad trustees with purpose-specific computer or security groups. Validate service dependencies before changing retrieval authorization.

<!--- Results --->
%TestResult%
Loading
Loading