Repository navigation
feat(ad): add modular cached LDAP query API #2849
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
soulemike
wants to merge
2
commits into
maester365:main
Choose a base branch
from
soulemike:feature/ad-collection-design
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
54 changes: 54 additions & 0 deletions
54
powershell/internal/services/ad/Complete-MtADQueryRange.ps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| function Complete-MtADQueryRange { | ||
| [CmdletBinding()] | ||
| param( | ||
| [Parameter(Mandatory)] [System.DirectoryServices.Protocols.LdapConnection] $Connection, | ||
| [Parameter(Mandatory)] [object] $Entry, | ||
| [Parameter(Mandatory)] [timespan] $Timeout | ||
| ) | ||
|
|
||
| foreach ($key in @($Entry.Attributes.Keys)) { | ||
| if ($key -notmatch ';') { continue } | ||
| if ($key -notmatch '^([A-Za-z][A-Za-z0-9-]*);range=(\d+)-(\d+|\*)$') { | ||
| throw 'LDAP returned an unsupported attribute option.' | ||
| } | ||
| $attribute = $matches[1] | ||
| $values = [System.Collections.Generic.List[object]]::new() | ||
| $expectedStart = 0L | ||
| $rangeKey = $key | ||
| $rangeBag = $Entry.Attributes | ||
| # AD can return an empty base attribute alongside the populated range. | ||
| # Only a populated base attribute conflicts with the ranged values. | ||
| if ($Entry.Attributes.Contains($attribute) -and $Entry.Attributes[$attribute].Count -gt 0) { | ||
| throw 'LDAP returned ambiguous ranged and non-ranged values.' | ||
| } | ||
|
|
||
| while ($true) { | ||
| if ($rangeKey -notmatch ('^' + [regex]::Escape($attribute) + ';range=(\d+)-(\d+|\*)$')) { | ||
| throw 'LDAP returned an invalid attribute range.' | ||
| } | ||
| $start = [long]$matches[1] | ||
| $end = $matches[2] | ||
| if ($start -ne $expectedStart) { throw 'LDAP attribute range was not contiguous.' } | ||
| $chunk = $rangeBag[$rangeKey] | ||
| if ($end -ne '*' -and ([long]$end -lt $start -or $chunk.Count -ne ([long]$end - $start + 1))) { | ||
| throw 'LDAP attribute range length did not match its bounds.' | ||
| } | ||
| foreach ($value in $chunk) { $values.Add($value) } | ||
| if ($end -eq '*') { break } | ||
| $expectedStart = [long]$end + 1 | ||
| $continuation = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $Entry.DistinguishedName -Scope Base ` | ||
| -Filter '(objectClass=*)' -Attributes @("$attribute`;range=$expectedStart-*") -PageSize 0 ` | ||
| -Timeout $Timeout -AsAttributeBag -RequireComplete) | ||
| if ($continuation.Count -ne 1 -or $continuation[0].DistinguishedName -ine $Entry.DistinguishedName) { | ||
| throw 'LDAP attribute range continuation did not return the original entry.' | ||
| } | ||
| $rangeBag = $continuation[0].Attributes | ||
| $rangeKeys = @($rangeBag.Keys | Where-Object { $_ -like "$attribute`;range=*" }) | ||
| if ($rangeKeys.Count -ne 1) { throw 'LDAP attribute range continuation was missing or ambiguous.' } | ||
| $rangeKey = $rangeKeys[0] | ||
| } | ||
| $Entry.Attributes.Remove($key) | ||
| $Entry.Attributes[$attribute] = [object[]]$values.ToArray() | ||
| } | ||
| return $Entry | ||
| } |
83 changes: 83 additions & 0 deletions
83
powershell/internal/services/ad/ConvertFrom-MtADQueryEntry.ps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| function ConvertFrom-MtADQueryEntry { | ||
| [CmdletBinding()] | ||
| param( | ||
| [Parameter(Mandatory)] [object] $Entry, | ||
| [Parameter(Mandatory)] [string[]] $Attributes | ||
| ) | ||
|
|
||
| $bag = [ordered]@{} | ||
| $requestedNames = @($Attributes | ForEach-Object { ($_ -split ';')[0].ToLowerInvariant() }) | ||
| $utf8 = [System.Text.UTF8Encoding]::new($false, $true) | ||
| # DirectoryAttribute enumeration exposes the server's bytes, even for textual values. | ||
| # Decode by known attribute semantics, never by whether unknown bytes happen to be valid UTF-8. | ||
| $textNames = @( | ||
| 'name', 'cn', 'samaccountname', 'displayname', 'dnshostname', 'description', 'member', 'memberof', | ||
| 'gplink', 'gpcfilesyspath', 'ldapdisplayname', 'serviceprincipalname', 'objectclass', 'distinguishedname', | ||
| 'defaultnamingcontext', 'configurationnamingcontext', 'schemanamingcontext', 'rootdomainnamingcontext', | ||
| 'namingcontexts', 'supportedldapversion', 'supportedsaslmechanisms', 'supportedcontrol', | ||
| 'operatingsystem', 'operatingsystemversion', 'managedby', 'manager', 'homedirectory', 'profilepath', | ||
| 'scriptpath', 'userworkstations', 'location', 'dnsroot', 'ncname', 'netbiosname', 'trustpartner', | ||
| 'fsmoroleowner', 'serverreference', 'fromserver', 'transporttype', 'siteobject', 'gpcwqlfilter', | ||
| 'msds-allowedtodelegateto', 'msds-psoappliesto' | ||
| ) | ||
| $fileTimeNames = @('accountexpires', 'badpasswordtime', 'lastlogoff', 'lastlogon', 'lastlogontimestamp', 'pwdlastset') | ||
| $convertedNames = @( | ||
| 'useraccountcontrol', 'forestfunctionality', 'domainfunctionality', 'ms-ds-machineaccountquota', | ||
| 'lockoutthreshold', 'minpwdlength', 'pwdproperties', 'pwdhistorylength', 'objectversion', | ||
| 'msds-behavior-version', 'primarygroupid', 'admincount', 'grouptype', 'options', 'trusttype', | ||
| 'trustdirection', 'trustattributes', 'gpoptions', 'flags', 'versionnumber', 'msds-passwordsettingsprecedence', | ||
| 'msds-lockoutthreshold', 'msds-minimumpasswordlength', 'msds-passwordhistorylength', | ||
| 'msds-requiredforestbehaviorversion', 'tombstonelifetime', 'iscriticalsystemobject', 'enabledconnection', | ||
| 'msds-passwordcomplexityenabled', 'msds-isrodc', 'maxpwdage', 'minpwdage', 'lockoutduration', | ||
| 'msds-lockoutduration', 'msds-maximumpasswordage', 'msds-minimumpasswordage', | ||
| 'whencreated', 'whenchanged', 'createtimestamp', 'modifytimestamp' | ||
| ) + $fileTimeNames | ||
| $names = if ($Entry.Attributes -is [System.Collections.IDictionary]) { @($Entry.Attributes.Keys) } | ||
| else { @($Entry.Attributes.AttributeNames) } | ||
| foreach ($name in $names) { | ||
| $baseName = ([string]$name -split ';')[0].ToLowerInvariant() | ||
| if ($requestedNames -notcontains $baseName) { continue } | ||
| $values = [System.Collections.Generic.List[object]]::new() | ||
| $rawAttribute = $Entry.Attributes[[string]$name] | ||
| if ($rawAttribute -is [byte[]]) { $rawValues = ,$rawAttribute } | ||
| else { $rawValues = @($rawAttribute) } | ||
| foreach ($raw in $rawValues) { | ||
| if ($raw -is [byte[]] -and $baseName -in ($textNames + $convertedNames)) { | ||
| $raw = $utf8.GetString($raw) | ||
| } | ||
| if ($raw -is [byte[]]) { | ||
| if ($baseName -in 'objectguid', 'invocationid', 'msds-optionalfeatureguid' -and $raw.Length -eq 16) { | ||
| $value = [guid]::new($raw) | ||
| } elseif ($baseName -in 'objectsid', 'sidhistory', 'securityidentifier', 'ms-ds-creatorsid') { | ||
| # All these attributes carry SID bytes. Reuse the base SID converter without | ||
| # depending on newer legacy collectors recognizing each attribute alias. | ||
| $sid = ConvertFrom-MtLdapValue -Value $raw -AttributeName 'objectSid' | ||
| if ($sid -is [byte[]]) { $value = $raw.Clone() } | ||
| else { $value = [string]$sid.Value } | ||
| } else { | ||
| # Unknown binary and security descriptors are never guessed to be UTF-8 strings. | ||
| $value = $raw.Clone() | ||
| } | ||
| } elseif ($raw -is [string]) { | ||
| $sentinel = 0L | ||
| if ($baseName -in $fileTimeNames -and [long]::TryParse($raw, [ref]$sentinel) -and | ||
| $sentinel -in 0L, [long]::MaxValue) { | ||
| # Keep AD's unset/never FILETIME sentinels distinguishable from an absent attribute. | ||
| $value = $sentinel | ||
| } elseif ($baseName -in $convertedNames) { | ||
| $value = ConvertFrom-MtLdapValue -Value $raw -AttributeName $baseName | ||
| } else { | ||
| # No generalized-date guessing for text or unrecognized names. | ||
| $value = $raw | ||
| } | ||
| } else { $value = $raw } | ||
| $values.Add($value) | ||
| } | ||
| $bag[([string]$name).ToLowerInvariant()] = [object[]]$values.ToArray() | ||
| } | ||
| return [pscustomobject]@{ | ||
| PSTypeName = 'Maester.AD.Entry' | ||
| DistinguishedName = [string]$Entry.DistinguishedName | ||
| Attributes = $bag | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| function Copy-MtADQueryResult { | ||
| [CmdletBinding()] | ||
| [OutputType([object], [object[]], [System.Collections.Specialized.OrderedDictionary], [pscustomobject])] | ||
| param([AllowNull()] [object] $Value) | ||
|
|
||
| if ($null -eq $Value) { return $null } | ||
| if ($Value -is [byte[]]) { return ,([byte[]]$Value.Clone()) } | ||
| if ($Value -is [System.Collections.IDictionary]) { | ||
| $copy = [ordered]@{} | ||
| foreach ($key in $Value.Keys) { $copy[$key] = Copy-MtADQueryResult -Value $Value[$key] } | ||
| return $copy | ||
| } | ||
| if ($Value -is [array]) { | ||
| $copy = [object[]]::new($Value.Length) | ||
| for ($i = 0; $i -lt $Value.Length; $i++) { $copy[$i] = Copy-MtADQueryResult -Value $Value[$i] } | ||
| return ,$copy | ||
| } | ||
| if ($Value -is [System.Management.Automation.PSCustomObject]) { | ||
| $copy = [ordered]@{} | ||
| foreach ($property in $Value.PSObject.Properties) { $copy[$property.Name] = Copy-MtADQueryResult -Value $property.Value } | ||
| $result = [pscustomobject]$copy | ||
| $result.PSObject.TypeNames.Insert(0, $Value.PSObject.TypeNames[0]) | ||
| return $result | ||
| } | ||
| return $Value | ||
| } |
18 changes: 18 additions & 0 deletions
18
powershell/internal/services/ad/Get-MtADQueryDefinition.ps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| function Get-MtADQueryDefinition { | ||
| [CmdletBinding()] | ||
| param( | ||
| [Parameter(Mandatory)] | ||
| [ValidateSet('User', 'Computer', 'Group', 'OrganizationalUnit', 'Gpo')] | ||
| [string] $Name | ||
| ) | ||
|
|
||
| # Starter queries, not replacements for the legacy collectors' richer projections. | ||
| $definitions = @{ | ||
| User = @{ Filter = '(&(objectClass=user)(!(objectClass=computer)))'; Attributes = @('objectGUID', 'name', 'sAMAccountName', 'userAccountControl', 'primaryGroupID') } | ||
| Computer = @{ Filter = '(objectClass=computer)'; Attributes = @('objectGUID', 'name', 'sAMAccountName', 'dNSHostName', 'userAccountControl') } | ||
| Group = @{ Filter = '(objectClass=group)'; Attributes = @('objectGUID', 'name', 'sAMAccountName', 'groupType') } | ||
| OrganizationalUnit = @{ Filter = '(objectClass=organizationalUnit)'; Attributes = @('objectGUID', 'name', 'gPLink', 'gPOptions') } | ||
| Gpo = @{ Filter = '(objectClass=groupPolicyContainer)'; Attributes = @('objectGUID', 'name', 'displayName', 'gPCFileSysPath', 'versionNumber') } | ||
| } | ||
| return $definitions[$Name] | ||
| } |
96 changes: 96 additions & 0 deletions
96
powershell/internal/services/ad/Invoke-MtADQueryCached.ps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| function Invoke-MtADQueryCached { | ||
| [CmdletBinding()] | ||
| param( | ||
| [Parameter(Mandatory)] [object] $Query, | ||
| [Parameter(Mandatory)] [hashtable] $Operation, | ||
| [Parameter(Mandatory)] [int] $PageSize, | ||
| [Parameter(Mandatory)] [timespan] $Timeout | ||
| ) | ||
|
|
||
| $evidence = $__MtSession.ADConnection | ||
| if (-not (Test-MtConnection -Service ActiveDirectory) -or -not $evidence.ProtocolValidated -or | ||
| [string]::IsNullOrWhiteSpace($evidence.ResolvedServer)) { | ||
| throw 'Connect-Maester -Service ActiveDirectory must validate a target before running LDAP queries.' | ||
| } | ||
| if ($evidence.TlsMode -notin 'Ldaps', 'StartTls') { throw 'The validated AD session has no supported TLS mode.' } | ||
|
|
||
| $base = $Query.SearchBase | ||
| if ($null -ne $Query.NamingContext) { | ||
| $base = $evidence.("$($Query.NamingContext)NamingContext") | ||
| if ([string]::IsNullOrWhiteSpace($base)) { throw 'The selected naming context is unavailable on the connected server.' } | ||
| } | ||
| $target = [ordered]@{ | ||
| Server = $evidence.ResolvedServer.ToLowerInvariant() | ||
| Port = if ($evidence.TlsMode -eq 'StartTls') { 389 } else { 636 } | ||
| AuthenticationMode = $evidence.AuthenticationMode | ||
| TlsMode = $evidence.TlsMode | ||
| SkipCertificateCheck = [bool]$evidence.SkipCertificateCheck | ||
| } | ||
| $targetIdentity = $target | ConvertTo-Json -Compress | ||
| $state = $__MtSession.ADCache['ADQueryState'] | ||
| if ($null -eq $state -or -not [object]::ReferenceEquals($state.ConnectionState, $evidence) -or | ||
| -not [object]::ReferenceEquals($state.Credential, $__MtSession.ADCredential) -or $state.TargetIdentity -cne $targetIdentity) { | ||
| $state = @{ | ||
| ConnectionState = $evidence | ||
| Credential = $__MtSession.ADCredential | ||
| TargetIdentity = $targetIdentity | ||
| Results = [System.Collections.Generic.Dictionary[string, object]]::new([System.StringComparer]::Ordinal) | ||
| } | ||
| $__MtSession.ADCache['ADQueryState'] = $state | ||
| } | ||
| if ($Operation.ContainsKey('State') -and -not [object]::ReferenceEquals($Operation.State, $state)) { | ||
| if ($null -ne $Operation.Connection) { $Operation.Connection.Dispose(); $Operation.Connection = $null } | ||
| } | ||
| $Operation.State = $state | ||
|
|
||
| $request = [ordered]@{ | ||
| Target = $target | ||
| SearchBase = [string]$base | ||
| Scope = $Query.Scope | ||
| Filter = $Query.Filter | ||
| Attributes = [string[]]$Query.Attributes | ||
| SecurityDescriptorFlags = if ($Query.PSObject.Properties['SecurityDescriptorFlags']) { [int]$Query.SecurityDescriptorFlags } else { $null } | ||
| ContractVersion = 1 | ||
| } | ||
| $json = $request | ConvertTo-Json -Depth 5 -Compress | ||
| $key = [Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData([System.Text.Encoding]::UTF8.GetBytes($json))) | ||
| if (-not $state.Results.ContainsKey($key)) { | ||
| if ($null -eq $Operation.Connection) { | ||
| # Use validated, resolved evidence directly; never rediscover a DC behind a cache key. | ||
| $Operation.Connection = New-MtAdProtocolConnection -ProtocolEvidence $evidence | ||
| } | ||
| $parameters = @{ | ||
| Connection = $Operation.Connection | ||
| SearchBase = [string]$base | ||
| Scope = $Query.Scope | ||
| Filter = $Query.Filter | ||
| Attributes = $Query.Attributes | ||
| PageSize = $PageSize | ||
| Timeout = $Timeout | ||
| AsAttributeBag = $true | ||
| RequireComplete = $true | ||
| } | ||
| if ($null -ne $request.SecurityDescriptorFlags) { $parameters.SecurityDescriptorFlags = $Query.SecurityDescriptorFlags } | ||
| $previousErrorPreference = $ErrorActionPreference | ||
| try { | ||
| # Method/conversion errors must abort collection even when the caller uses Continue. | ||
| $ErrorActionPreference = 'Stop' | ||
| $entries = @(Invoke-MtLdapSearch @parameters | ForEach-Object { | ||
| Complete-MtADQueryRange -Connection $Operation.Connection -Entry $_ -Timeout $Timeout | ||
| }) | ||
| } catch { | ||
| # Rethrow so the caller's script stops, rather than merely skipping the failed statement. | ||
| throw | ||
| } finally { | ||
| $ErrorActionPreference = $previousErrorPreference | ||
| } | ||
| # Commit only after every page and every ranged attribute succeeds, including successful empty results. | ||
| $state.Results[$key] = [pscustomobject]@{ | ||
| PSTypeName = 'Maester.AD.QueryResult' | ||
| Request = [pscustomobject]$request | ||
| CollectedAt = [datetime]::UtcNow | ||
| Entries = [object[]]$entries | ||
| } | ||
| } | ||
| return Copy-MtADQueryResult -Value $state.Results[$key] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| function Resolve-MtADQuery { | ||
| [CmdletBinding()] | ||
| param([Parameter(Mandatory)] [object] $Query) | ||
|
|
||
| $parameters = @{} | ||
| $names = if ($Query -is [System.Collections.IDictionary]) { @($Query.Keys) } | ||
| elseif ($Query -is [System.Management.Automation.PSCustomObject]) { @($Query.PSObject.Properties.Name) } | ||
| else { throw 'Query must be a query definition, dictionary or PSCustomObject.' } | ||
| foreach ($name in $names) { | ||
| if ($name -eq 'PSTypeName') { continue } | ||
| if ($name -notin 'Name', 'SearchBase', 'NamingContext', 'Scope', 'Filter', 'Attributes', 'SecurityDescriptorFlags') { | ||
| throw 'Query contains an unsupported field.' | ||
| } | ||
| $value = if ($Query -is [System.Collections.IDictionary]) { $Query[$name] } else { $Query.$name } | ||
| if ($name -in 'SearchBase', 'NamingContext' -and $null -eq $value) { continue } | ||
| $parameters[$name] = $value | ||
| } | ||
| return New-MtADQuery @parameters | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.