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
3 changes: 3 additions & 0 deletions powershell/Maester.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
'ConvertFrom-MailAuthenticationRecordDmarc',
'ConvertFrom-MailAuthenticationRecordMx',
'ConvertFrom-MailAuthenticationRecordSpf',
'ConvertTo-MtLdapFilterValue',
Comment thread
soulemike marked this conversation as resolved.
Resolved
'Disconnect-Maester',
'Disconnect-MtGitHub',
'Get-MailAuthenticationRecord',
Expand Down Expand Up @@ -113,12 +114,14 @@
'Install-MaesterTests',
'Install-MtPack',
'Invoke-Maester',
'Invoke-MtADQuery',
'Invoke-MtAzureRequest',
'Invoke-MtAzureResourceGraphRequest',
'Invoke-MtGraphRequest',
'Invoke-MtGraphSecurityQuery',
'Invoke-MtTest',
'Merge-MtMaesterResult',
'New-MtADQuery',
'New-MtMaesterApp',
'New-MtPack',
'New-MtTest',
Expand Down
54 changes: 54 additions & 0 deletions powershell/internal/services/ad/Complete-MtADQueryRange.ps1
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 powershell/internal/services/ad/ConvertFrom-MtADQueryEntry.ps1
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
}
}
26 changes: 26 additions & 0 deletions powershell/internal/services/ad/Copy-MtADQueryResult.ps1
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 powershell/internal/services/ad/Get-MtADQueryDefinition.ps1
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 powershell/internal/services/ad/Invoke-MtADQueryCached.ps1
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]
}
19 changes: 19 additions & 0 deletions powershell/internal/services/ad/Resolve-MtADQuery.ps1
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
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,12 @@

[scriptblock] $ProcessPage,

[object] $PageState
[object] $PageState,

# Opt-in contract for the modular query API. Legacy conversion remains the default.
[switch] $AsAttributeBag,

[switch] $RequireComplete
)

function ConvertTo-LdapFilterLiteral {
Expand Down Expand Up @@ -66,6 +71,10 @@
function Convert-SearchEntry {
param($Entry)

if ($AsAttributeBag) {
return ConvertFrom-MtADQueryEntry -Entry $Entry -Attributes $Attributes
}

$properties = [ordered]@{
DistinguishedName = [string]$Entry.DistinguishedName
}
Expand Down Expand Up @@ -169,6 +178,12 @@
return $null
}

if (($AsAttributeBag -or $RequireComplete) -and ($ReturnDirectoryEntry -or $null -ne $ProcessPage)) {
throw 'The modular query contract cannot be combined with DirectoryEntry output or page callbacks.'
}
if ($AsAttributeBag -and (-not $Attributes -or $Attributes.Count -eq 0)) {
throw 'Attribute-bag conversion requires explicit Attributes.'
}
$results = [System.Collections.Generic.List[object]]::new()
$requestedAttributes = [string[]]$Attributes
if ($null -eq $requestedAttributes -or $requestedAttributes.Count -eq 0) {
Expand Down Expand Up @@ -204,6 +219,11 @@
[void]$request.Controls.Add($securityDescriptorControl)
}

if ($RequireComplete) {
# Bound this query to one naming context instead of silently chasing other partitions.
[void]$request.Controls.Add([System.DirectoryServices.Protocols.DomainScopeControl]::new())
}

try {
$overrideProperty = $Connection.PSObject.Properties['MtSendRequestOverride']
if ($null -ne $overrideProperty) {
Expand All @@ -230,6 +250,14 @@
throw "LDAP search failed. $($_.Exception.Message)"
}

if ($RequireComplete -and ($null -eq $response.ResultCode -or
$response.ResultCode -ne [System.DirectoryServices.Protocols.ResultCode]::Success)) {
throw 'LDAP did not return a successful, complete query response.'
}
if ($RequireComplete -and @($response.References).Where({ $null -ne $_ }).Count -gt 0) {
throw 'LDAP returned continuation references despite domain-scoped collection.'
}

if ($null -ne $ProcessPage) {
$pageEntries = [System.Collections.Generic.List[object]]::new()
foreach ($entry in @($response.Entries)) {
Expand All @@ -243,6 +271,9 @@
}

$pageResponseControl = Get-PageControlFromResponse -Response $response
if ($RequireComplete -and $PageSize -gt 0 -and $null -eq $pageResponseControl) {
throw 'LDAP did not return the required paging response control.'
}
$pageCookie = if ($null -ne $pageResponseControl -and $null -ne $pageResponseControl.Cookie) {
[byte[]]@($pageResponseControl.Cookie)
}
Expand Down
Loading
Loading