Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
function ConvertTo-MtAdcsEnrollmentPrerequisiteState {
[CmdletBinding()]
[OutputType([PSCustomObject])]
param(
[Parameter(Mandatory)] [AllowNull()] [PSCustomObject] $Configuration
)

# Preserve the difference between an uncollected property and an observed empty value.
$readField = {
param($Item, [string] $Name)
$present = $false
$value = $null
if ($Item -is [Collections.IDictionary]) {
$present = $Item.Contains($Name)
if ($present) { $value = $Item[$Name] }
} elseif ($null -ne $Item) {
$property = $Item.PSObject.Properties[$Name]
$present = $null -ne $property
if ($present) { $value = $property.Value }
}
[pscustomobject]@{ Present = $present; Value = $value }
}
$readNumber = {
param($Field)
$value = if ($Field.Present) { ConvertFrom-MtLdapValue -Value $Field.Value } else { $null }
$number = 0L
$known = $null -ne $value -and $value -isnot [bool] -and
[long]::TryParse([string]$value, [ref]$number) -and $number -ge [int]::MinValue -and $number -le [uint32]::MaxValue
[pscustomobject]@{ Known = $known; Value = if ($known) { $number } else { $null } }
}
$unavailable = [pscustomobject]@{
EvidenceAvailable = $false; Disposition = 'Inconclusive'; Templates = @()
PublishedTemplateCount = 0; PotentiallyEligibleCount = 0; InconclusiveCount = 0
Reason = 'AD CS publication or template inventory is unavailable or incomplete.'
}
$caField = & $readField $Configuration 'EnterpriseCAs'
$templateField = & $readField $Configuration 'CertificateTemplates'
if ($null -eq $Configuration -or $null -eq $caField.Value -or $null -eq $templateField.Value) { return $unavailable }

$publishedBy = @{}
foreach ($ca in @($caField.Value)) {
$publication = & $readField $ca 'certificateTemplates'
if (-not $publication.Present) { return $unavailable }
$caName = [string](ConvertFrom-MtLdapValue -Value (& $readField $ca 'Name').Value)
if ([string]::IsNullOrWhiteSpace($caName)) { $caName = [string](ConvertFrom-MtLdapValue -Value (& $readField $ca 'DistinguishedName').Value) }
foreach ($reference in @($publication.Value)) {
$name = [string](ConvertFrom-MtLdapValue -Value $reference)
if ([string]::IsNullOrWhiteSpace($name)) { return $unavailable }
if (-not $publishedBy.ContainsKey($name)) { $publishedBy[$name] = [Collections.Generic.List[string]]::new() }
$publishedBy[$name].Add($caName)
}
}
$templatesByName = @{}
foreach ($template in @($templateField.Value)) {
$name = [string](ConvertFrom-MtLdapValue -Value (& $readField $template 'Name').Value)
if ([string]::IsNullOrWhiteSpace($name)) { return $unavailable }
if (-not $templatesByName.ContainsKey($name)) { $templatesByName[$name] = [Collections.Generic.List[object]]::new() }
$templatesByName[$name].Add($template)
}

$authenticationOids = @('1.3.6.1.5.5.7.3.2', '1.3.6.1.4.1.311.20.2.2', '1.3.6.1.5.2.3.4', '2.5.29.37.0')
$names = @(@($publishedBy.Keys) + @($templatesByName.Keys) | Sort-Object -Unique)
$facts = @(foreach ($name in $names) {
$published = $publishedBy.ContainsKey($name)
$resolvedTemplates = if ($templatesByName.ContainsKey($name)) { $templatesByName[$name] } else { @() }
$template = if ($resolvedTemplates.Count -eq 1) { $resolvedTemplates[0] } else { $null }
$missing = [Collections.Generic.List[string]]::new()
if ($resolvedTemplates.Count -ne 1) { $missing.Add('Published template could not be resolved uniquely.') }

$ekuField = & $readField $template 'pKIExtendedKeyUsage'
$eku = @(foreach ($value in @($ekuField.Value)) { if ($null -ne $value) { [string](ConvertFrom-MtLdapValue -Value $value) } })
$malformedEku = @($eku | Where-Object { $_ -notmatch '^[0-2]\.\d+(?:\.\d+)*$' }).Count -gt 0
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
$authenticationCapable = if (-not $ekuField.Present -or $malformedEku) { $null } else {
$eku.Count -eq 0 -or @($eku | Where-Object { $_ -in $authenticationOids }).Count -gt 0
}
if ($null -eq $authenticationCapable) { $missing.Add('Authentication EKU evidence is unavailable or malformed.') }
$nameFlag = & $readNumber (& $readField $template 'msPKI-Certificate-Name-Flag')
$enrollmentFlag = & $readNumber (& $readField $template 'msPKI-Enrollment-Flag')
$signatures = & $readNumber (& $readField $template 'msPKI-RA-Signature')
if ($signatures.Known -and ($signatures.Value -lt 0 -or $signatures.Value -gt [int]::MaxValue)) { $signatures.Known = $false; $signatures.Value = $null }
$suppliesSubject = if ($nameFlag.Known) { ($nameFlag.Value -band 1) -ne 0 } else { $null }
$approvalRequired = if ($enrollmentFlag.Known) { ($enrollmentFlag.Value -band 2) -ne 0 } else { $null }
if (-not $nameFlag.Known) { $missing.Add('Subject-supply flag is unavailable or malformed.') }
if (-not $enrollmentFlag.Known) { $missing.Add('Enrollment flag is unavailable or malformed.') }
if (-not $signatures.Known) { $missing.Add('Authorized-signature count is unavailable or malformed.') }
$descriptor = (& $readField $template 'nTSecurityDescriptor').Value
$descriptorAvailable = $null -ne $descriptor -and @($descriptor).Count -gt 0
if (-not $descriptorAvailable) { $missing.Add('Security descriptor is unavailable; authorization is unresolved.') }

# A known gate disproves this modeled path. Unknown evidence alone never disproves a prerequisite.
$disposition = if (-not $published -or $authenticationCapable -eq $false -or $suppliesSubject -eq $false -or
$approvalRequired -eq $true -or ($signatures.Known -and $signatures.Value -gt 0)) {
'PrerequisitesNotSatisfied'
} elseif ($missing.Count -gt 0) { 'Inconclusive' } else { 'PotentiallyEligible' }
[pscustomobject]@{
Name = $name; Published = $published
PublishedBy = if ($published) { @($publishedBy[$name].ToArray() | Sort-Object -Unique) } else { @() }
AuthenticationCapable = $authenticationCapable; EnrolleeSuppliesSubject = $suppliesSubject
ManagerApprovalRequired = $approvalRequired; AuthorizedSignaturesRequired = $signatures.Value
SecurityDescriptorAvailable = $descriptorAvailable; Disposition = $disposition
MissingEvidence = $missing.ToArray()
}
})
$potential = @($facts | Where-Object Disposition -EQ PotentiallyEligible).Count
$inconclusive = @($facts | Where-Object Disposition -EQ Inconclusive).Count
[pscustomobject]@{
EvidenceAvailable = $true
Disposition = if ($inconclusive -gt 0) { 'Inconclusive' } elseif ($potential -gt 0) { 'PotentiallyEligible' } else { 'PrerequisitesNotSatisfied' }
Templates = $facts; PublishedTemplateCount = $publishedBy.Count
PotentiallyEligibleCount = $potential; InconclusiveCount = $inconclusive; Reason = $null
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
$enterprise = Invoke-ConfigurationSearchSafe -RelativeSearchBase "CN=Enrollment Services,$pkiBase" -Scope OneLevel -Filter '(objectClass=pKIEnrollmentService)' -Attributes ($commonAttributes + @('certificateTemplates', 'dNSHostName', 'cACertificate', 'flags'))

$securityDescriptorFlags = [System.DirectoryServices.SecurityMasks]::Owner -bor [System.DirectoryServices.SecurityMasks]::Group -bor [System.DirectoryServices.SecurityMasks]::Dacl
$templates = Invoke-ConfigurationSearchSafe -RelativeSearchBase "CN=Certificate Templates,$pkiBase" -Scope OneLevel -Filter '(objectClass=pKICertificateTemplate)' -Attributes ($commonAttributes + @('displayName', 'pKIExtendedKeyUsage', 'msPKI-Enrollment-Flag', 'msPKI-Certificate-Name-Flag', 'nTSecurityDescriptor')) -SecurityDescriptorFlags $securityDescriptorFlags
$templates = Invoke-ConfigurationSearchSafe -RelativeSearchBase "CN=Certificate Templates,$pkiBase" -Scope OneLevel -Filter '(objectClass=pKICertificateTemplate)' -Attributes ($commonAttributes + @('displayName', 'pKIExtendedKeyUsage', 'msPKI-Enrollment-Flag', 'msPKI-Certificate-Name-Flag', 'msPKI-RA-Signature', 'nTSecurityDescriptor')) -SecurityDescriptorFlags $securityDescriptorFlags

$cdp = Invoke-ConfigurationSearchSafe -RelativeSearchBase "CN=CDP,$pkiBase" -Scope OneLevel -Filter '(|(objectClass=cRLDistributionPoint)(objectClass=certificationAuthority))' -Attributes ($commonAttributes + @('certificateRevocationList'))

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
BeforeAll {
$repoRoot = (Resolve-Path "$PSScriptRoot/../../..").Path
. "$repoRoot/powershell/internal/services/ad/protocol/ConvertFrom-MtLdapValue.ps1"
. "$repoRoot/powershell/internal/services/ad/ConvertTo-MtAdcsEnrollmentPrerequisiteState.ps1"
function Get-AdcsTestConfiguration {
$template = [pscustomobject]@{
Name = 'UserAuth'
pKIExtendedKeyUsage = @('1.3.6.1.5.5.7.3.2')
'msPKI-Enrollment-Flag' = 0
'msPKI-Certificate-Name-Flag' = 1
'msPKI-RA-Signature' = 0
nTSecurityDescriptor = [pscustomobject]@{ Dacl = @(); Owner = 'S-1-5-18' }
}
[pscustomobject]@{
EnterpriseCAs = @([pscustomobject]@{ Name = 'CA01'; certificateTemplates = @('UserAuth') })
CertificateTemplates = @($template)
}
}
}

Describe 'Published AD CS enrollment prerequisite evidence' {
It 'keeps unavailable configuration inconclusive' {
$result = ConvertTo-MtAdcsEnrollmentPrerequisiteState -Configuration $null
$result.EvidenceAvailable | Should -BeFalse
$result.PSObject.Properties.Name | Should -Not -Contain 'EligibleCount'
$result.Disposition | Should -Be 'Inconclusive'
}
It 'correlates a published authentication template without claiming exploitability' {
$result = ConvertTo-MtAdcsEnrollmentPrerequisiteState (Get-AdcsTestConfiguration)
$result.PotentiallyEligibleCount | Should -Be 1
$result.PSObject.Properties.Name | Should -Not -Contain 'EligibleCount'
$result.Templates[0].PublishedBy | Should -Contain 'CA01'
}
It 'does not classify an unpublished template as potentially eligible' {
$config = Get-AdcsTestConfiguration
$config.EnterpriseCAs = @()
$result = ConvertTo-MtAdcsEnrollmentPrerequisiteState $config
$result.Templates[0].Disposition | Should -Be 'PrerequisitesNotSatisfied'
}
It 'recognizes manager approval as a disproven modeled prerequisite' {
$config = Get-AdcsTestConfiguration
$config.CertificateTemplates[0].'msPKI-Enrollment-Flag' = 2
(ConvertTo-MtAdcsEnrollmentPrerequisiteState $config).Templates[0].Disposition | Should -Be 'PrerequisitesNotSatisfied'
}
It 'does not treat unavailable security descriptors as authorization evidence' {
$config = Get-AdcsTestConfiguration
$config.CertificateTemplates[0].nTSecurityDescriptor = $null
(ConvertTo-MtAdcsEnrollmentPrerequisiteState $config).Templates[0].Disposition | Should -Be 'Inconclusive'
}
It 'recognizes required authorization signatures as a separate issuance gate' {
$config = Get-AdcsTestConfiguration
$config.CertificateTemplates[0].'msPKI-RA-Signature' = 1
$result = ConvertTo-MtAdcsEnrollmentPrerequisiteState $config
$result.Templates[0].AuthorizedSignaturesRequired | Should -Be 1
$result.Templates[0].Disposition | Should -Be 'PrerequisitesNotSatisfied'
}
It 'does not infer a missing signature count to be zero' {
$config = Get-AdcsTestConfiguration
$config.CertificateTemplates[0].PSObject.Properties.Remove('msPKI-RA-Signature')
(ConvertTo-MtAdcsEnrollmentPrerequisiteState $config).Templates[0].Disposition | Should -Be 'Inconclusive'
}
It 'does not infer an unobserved subject-supply flag to be false' {
$config = Get-AdcsTestConfiguration
$config.CertificateTemplates[0].PSObject.Properties.Remove('msPKI-Certificate-Name-Flag')
$result = ConvertTo-MtAdcsEnrollmentPrerequisiteState $config
$result.Templates[0].Disposition | Should -Be 'Inconclusive'
$result.Templates[0].EnrolleeSuppliesSubject | Should -BeNullOrEmpty
}
It 'does not infer an unobserved enrollment flag to permit issuance' {
$config = Get-AdcsTestConfiguration
$config.CertificateTemplates[0].PSObject.Properties.Remove('msPKI-Enrollment-Flag')
(ConvertTo-MtAdcsEnrollmentPrerequisiteState $config).Templates[0].Disposition | Should -Be 'Inconclusive'
}
It 'recognizes an explicitly observed empty EKU as unrestricted' {
foreach ($empty in @($null, @())) {
$config = Get-AdcsTestConfiguration
$config.CertificateTemplates[0].pKIExtendedKeyUsage = $empty
$result = ConvertTo-MtAdcsEnrollmentPrerequisiteState $config
$result.Templates[0].AuthenticationCapable | Should -BeTrue
$result.Templates[0].Disposition | Should -Be 'PotentiallyEligible'
}
}
It 'keeps an uncollected EKU property unknown' {
$config = Get-AdcsTestConfiguration
$config.CertificateTemplates[0].PSObject.Properties.Remove('pKIExtendedKeyUsage')
(ConvertTo-MtAdcsEnrollmentPrerequisiteState $config).Templates[0].Disposition | Should -Be 'Inconclusive'
}
It 'preserves a CA publication reference that has no matching template' {
$config = Get-AdcsTestConfiguration
$config.CertificateTemplates = @()
$result = ConvertTo-MtAdcsEnrollmentPrerequisiteState $config
$result.Templates.Count | Should -Be 1
$result.Templates[0].Name | Should -Be 'UserAuth'
$result.Templates[0].Disposition | Should -Be 'Inconclusive'
$result.InconclusiveCount | Should -Be 1
}
It 'does not resolve duplicate template CNs by silently selecting one' {
$config = Get-AdcsTestConfiguration
$config.CertificateTemplates += $config.CertificateTemplates[0].PSObject.Copy()
(ConvertTo-MtAdcsEnrollmentPrerequisiteState $config).InconclusiveCount | Should -BeGreaterThan 0
}
It 'does not let missing evidence override an independently disproven condition' {
$config = Get-AdcsTestConfiguration
$config.CertificateTemplates[0].'msPKI-Enrollment-Flag' = 2
$config.CertificateTemplates[0].PSObject.Properties.Remove('msPKI-Certificate-Name-Flag')
$config.CertificateTemplates[0].PSObject.Properties.Remove('msPKI-RA-Signature')
(ConvertTo-MtAdcsEnrollmentPrerequisiteState $config).Templates[0].Disposition | Should -Be 'PrerequisitesNotSatisfied'
}
It 'uses the real LDAP converter for byte-backed flag and signature values' {
$config = Get-AdcsTestConfiguration
$config.CertificateTemplates[0].'msPKI-Certificate-Name-Flag' = [Text.Encoding]::UTF8.GetBytes('1')
$config.CertificateTemplates[0].'msPKI-Enrollment-Flag' = [Text.Encoding]::UTF8.GetBytes('0')
$config.CertificateTemplates[0].'msPKI-RA-Signature' = [Text.Encoding]::UTF8.GetBytes('1')
(ConvertTo-MtAdcsEnrollmentPrerequisiteState $config).Templates[0].Disposition | Should -Be 'PrerequisitesNotSatisfied'
}
It 'treats malformed, negative or multivalued signature evidence as unknown' {
foreach ($bad in @('invalid', -1, @('0', '1'))) {
$config = Get-AdcsTestConfiguration
$config.CertificateTemplates[0].'msPKI-RA-Signature' = $bad
(ConvertTo-MtAdcsEnrollmentPrerequisiteState $config).Templates[0].Disposition | Should -Be 'Inconclusive'
}
}
It 'does not report complete evidence when a CA publication list was not collected' {
$config = Get-AdcsTestConfiguration
$config.EnterpriseCAs[0].PSObject.Properties.Remove('certificateTemplates')
(ConvertTo-MtAdcsEnrollmentPrerequisiteState $config).Disposition | Should -Be 'Inconclusive'
}
It 'keeps an unavailable inventory distinct from a completed empty inventory' {
$config = Get-AdcsTestConfiguration
$config.CertificateTemplates = $null
(ConvertTo-MtAdcsEnrollmentPrerequisiteState $config).EvidenceAvailable | Should -BeFalse
$config.CertificateTemplates = @()
$config.EnterpriseCAs = @()
(ConvertTo-MtAdcsEnrollmentPrerequisiteState $config).EvidenceAvailable | Should -BeTrue
}
}

Describe 'AD-CS-01 native engine outcomes' {
BeforeAll {
Import-Module "$repoRoot/powershell/Maester.psd1" -Force -WarningAction SilentlyContinue
$script:adcsRunConfig = @{ Environment = @{ Services = @{ ActiveDirectory = $true } } }
}
BeforeEach {
$script:adcsConfiguration = Get-AdcsTestConfiguration
Mock -ModuleName Maester Get-MtADDomainState { [pscustomobject]@{ Configuration = $script:adcsConfiguration } }
}
It 'has valid native metadata with an existing resource type and author handle' {
$test = Get-MtTest AD-CS-01
$test.IsValid | Should -BeTrue
$test.Errors | Should -BeNullOrEmpty
$test.Author | Should -Contain 'rolling-code'
$test.Contributor | Should -Contain 'FiraSenax'
}
It 'reports a known issuance gate as passed' {
$script:adcsConfiguration.CertificateTemplates[0].'msPKI-RA-Signature' = 1
$row = Invoke-MtTest -Id AD-CS-01 -Config $script:adcsRunConfig
$row.Result.ToString() | Should -Be 'Passed'
$row.ResultDetail.TestResult | Should -BeLike '*Well done*'
}
It 'reports configuration candidates as investigation without claiming enrollment success' {
$row = Invoke-MtTest -Id AD-CS-01 -Config $script:adcsRunConfig
$row.Result.ToString() | Should -Be 'Investigate'
$row.ResultDetail.TestResult | Should -BeLike '*UserAuth*PotentiallyEligible*'
$row.ResultDetail.TestResult | Should -Not -BeLike '*S-1-5-18*'
$row.ReasonCode | Should -Not -Be 'InvalidReturn'
}
It 'shows unknown flag values instead of false in an inconclusive result' {
$script:adcsConfiguration.CertificateTemplates[0].PSObject.Properties.Remove('msPKI-Certificate-Name-Flag')
$row = Invoke-MtTest -Id AD-CS-01 -Config $script:adcsRunConfig
$row.Result.ToString() | Should -Be 'Investigate'
$row.ResultDetail.TestResult | Should -BeLike '*Unknown*Inconclusive*'
}
It 'does not pass an unavailable configuration inventory' {
$script:adcsConfiguration = $null
$row = Invoke-MtTest -Id AD-CS-01 -Config $script:adcsRunConfig
$row.Result.ToString() | Should -Be 'Investigate'
}
It 'uses NotApplicable for a completed inventory without published templates' {
$script:adcsConfiguration.EnterpriseCAs = @()
$script:adcsConfiguration.CertificateTemplates = @()
$row = Invoke-MtTest -Id AD-CS-01 -Config $script:adcsRunConfig
$row.Result.ToString() | Should -Be 'Skipped'
$row.ReasonCode | Should -Be 'NotApplicable'
}
It 'escapes directory-controlled names without changing table columns or rendering HTML' {
$name = "Template | <img src=x> `$&`nnext"
$script:adcsConfiguration.CertificateTemplates[0].Name = $name
$script:adcsConfiguration.EnterpriseCAs[0].certificateTemplates = @($name)
$script:adcsConfiguration.EnterpriseCAs[0].Name = 'CA | <b>name</b>'
$row = Invoke-MtTest -Id AD-CS-01 -Config $script:adcsRunConfig
$row.Result.ToString() | Should -Be 'Investigate'
$detail = $row.ResultDetail.TestResult
$detail | Should -Not -Match '<img|<b>'
$tableRows = @($detail -split '\r?\n' | Where-Object { $_.StartsWith('| ') })
$tableRows.Count | Should -Be 3
foreach ($line in $tableRows) { [regex]::Matches($line, '(?<!\\)\|').Count | Should -Be 10 }
}
}
Loading
Loading