Abuso de Confiança entre Florestas Active Directory: Prevenir Escalação para a Raiz
Active Directory · Trust · Florestas · SID Filtering · Escalação · Privilegios · Security · Forest | ✎ Duarte Spínola | 2026-07-07
O abuso de trust entre florestas é um vetor de escalação de privilégios crítico em Active Directory. Quando um atacante compromete uma floresta com trust para outra, pode usar essa confiança para escalar para a floresta raiz (root domain) e comprometer toda a infraestrutura. Este guia prático mostra como auditar, proteger e monitorar trust relationships, com base na documentação Microsoft sobre AD Trusts e no MITRE ATT&CK T1484. Para segurança AD geral, consulta Segurança do Active Directory.
O SID History injection é o ataque mais comum em trust abuse. Se o SID filtering não estiver ativo, um atacante pode injectar o SID de Enterprise Admins da floresta raiz numa conta da floresta comprometida e obter acesso total. Verifica já se SID filtering está ativo em todos os trusts.
Conteúdos
- 1. O Que é Trust entre Florestas no AD
- 2. Tipos de Trust
- 3. Como Funciona o Abuso de Trust
- 4. Ataque de Escalação para a Root Domain
- 5. SID Filtering: A Primeira Linha de Defesa
- 6. Configurar SID Filtering com PowerShell
- 7. Selective Authentication vs Full Authentication
- 8. Auditar Trust Relationships Existentes
- 9. Hardening de Trust entre Florestas
- 10. Monitorização com Event Logs e Sentinel
- 11. Cenário de Ataque Real: Passo a Passo
- 12. Ferramentas de Auditoria (BloodHound, PingCastle)
- 13. Cenário Prático PME (multi-floresta)
- 14. Checklist de Proteção
1. O Que é Trust entre Florestas no AD
Uma trust relationship entre florestas permite que utilizadores de uma floresta (trusted) acedam a recursos de outra floresta (trusting). O AD cria automaticamente trusts internos entre todos os domínios da mesma floresta (parent-child e tree-root trusts). Trusts externos entre florestas diferentes são criados manualmente e são o vetor de ataque mais perigoso. Para comparar com a alternativa Linux, consulta Samba AD para PME.
2. Tipos de Trust (External, Forest, Realm)
| Tipo | Transitive? | Risco | Quando usar |
|---|---|---|---|
| External Trust | Não | Médio | Migração, compatibilidade legacy |
| Forest Trust | Sim | Alto | Colaboração entre organizações |
| Realm Trust | Configurável | Baixo | Interoperabilidade Kerberos não-Windows |
3. Como Funciona o Abuso de Trust
O abuso de trust explora a forma como o AD trata a autenticação entre florestas. Quando um utilizador da floresta B acede a um recurso na floresta A, o DC da floresta A valida o ticket Kerberos e verifica o PAC (Privilege Attribute Certificate) que contém os SIDs (Security Identifiers) do utilizador. Se o SID filtering não estiver ativo, o PAC pode conter SIDs da floresta A (incluindo Enterprise Admins), permitindo acesso administrativo.
# Fluxo do ataque SID History Injection:
# 1. Atacante compromete floresta B (empresa subsidiária)
# 2. Atacante cria conta com SID History = S-1-5-21-ROOT-519 (Enterprise Admins root)
# 3. Floresta B tem trust para floresta A (root)
# 4. Atacante usa conta comprometida para aceder a floresta A
# 5. DC da floresta A vê SID History = Enterprise Admins no PAC
# 6. Se SID filtering OFF → DC aceita SID → acesso total
# Verificar trusts existentes
Get-ADTrust -Filter * |
Select-Object Name, Source, Target, TrustType,
Direction, SIDFilteringQuarantined
4. Ataque de Escalação para a Root Domain
# MITRE ATT&CK T1484.002 — Domain Trust Modification
# Ataque: DCShadow + SID History injection
# 1. Verificar SIDs sensíveis que devem ser bloqueados por SID filtering:
# S-1-5-21-root-518 = Schema Admins
# S-1-5-21-root-519 = Enterprise Admins
# S-1-5-21-root-512 = Domain Admins (root)
# S-1-5-root-498 = Enterprise Read-Only Domain Controllers
# 2. Verificar se a conta tem SID History suspeito
Get-ADUser -Identity "svc-comprometida" -Properties sIDHistory |
Select-Object Name, sIDHistory, sID
# 3. Enumerar todas as contas com SID History
Get-ADUser -Filter { sIDHistory -like "*" } -Properties sIDHistory |
Select-Object Name, SamAccountName, sIDHistory, Enabled
5. SID Filtering: A Primeira Linha de Defesa
O SID filtering (também chamado SID quarantine) remove todos os SIDs do PAC que pertençam a outra floresta. Isto impede que SIDs privilegiados da floresta trusting sejam aceites. A documentação oficial está em How to configure SID filtering quarantining.
# Verificar estado de SID filtering em todos os trusts
Get-ADTrust -Filter * |
Select-Object Name, Target, TrustType, Direction,
SIDFilteringQuarantined, SIDFilteringForestAware
6. Configurar SID Filtering com PowerShell
# Ativar SID filtering num external trust
Set-ADTrust -Identity "empresa-sub.pt" `
-SIDFilteringQuarantined $true
# Verificar
Get-ADTrust -Identity "empresa-sub.pt" |
Select-Object Name, SIDFilteringQuarantined
# Para forest trusts, usar forest-aware SID filtering
Set-ADTrust -Identity "empresa-parceira.pt" `
-SIDFilteringForestAware $true
# desativar selective auth (não recomendado em produção)
# Set-ADTrust -Identity "empresa-sub.pt" -SelectiveAuthentication $false
O forest-aware SID filtering é mais inteligente que o quarantined — bloqueia apenas SIDs da outra floresta, permitindo SIDs legítimos do mesmo domínio. Usar em forest trusts. Usar Quarantined em external trusts. Para gestão de grupos AD, consulta AD Security Groups com PowerShell.
7. Selective Authentication vs Full Authentication
# Selective Authentication: apenas recursos explicitamente autorizados
# são acessíveis a utilizadores da floresta trusted
# ativar selective authentication
Set-ADTrust -Identity "empresa-parceira.pt" `
-SelectiveAuthentication $true
# Conceder acesso a um servidor específico
$server = Get-ADComputer -Identity "SRV-FILE01"
$foreignUser = Get-ADUser -Identity "user-parceiro" -Server "empresa-parceira.pt"
$server | Set-ADObject -Add @{
'msDS-AllowedToActOnBehalfOfOtherIdentity' = $foreignUser.DistinguishedName
}
8. Auditar Trust Relationships Existentes
# Script completo de auditoria de trusts
$trusts = Get-ADTrust -Filter *
foreach ($t in $trusts) {
Write-Host "Trust: $($t.Name)"
Write-Host " Tipo: $($t.TrustType)"
Write-Host " Direção: $($t.Direction)"
Write-Host " SID Filtering: $($t.SIDFilteringQuarantined)"
Write-Host " Forest Aware: $($t.SIDFilteringForestAware)"
Write-Host " Selective Auth: $($t.SelectiveAuthentication)"
if (-not $t.SIDFilteringQuarantined -and -not $t.SIDFilteringForestAware) {
Write-Host " ⚠️ RISCO: SID filtering DESATIVADO!" -ForegroundColor Red
}
if ($t.TrustType -eq "Forest" -and -not $t.SelectiveAuthentication) {
Write-Host " ⚠️ AVISO: Forest trust sem selective auth" -ForegroundColor Yellow
}
Write-Host ""
}
9. Hardening de Trust entre Florestas
# Hardening completo de trusts
# 1. ativar SID filtering em todos os external trusts
Get-ADTrust -Filter { TrustType -eq "External" } |
Where-Object { -not $_.SIDFilteringQuarantined } |
ForEach-Object {
Set-ADTrust -Identity $_.Name -SIDFilteringQuarantined $true
Write-Host "SID filtering activado: $($_.Name)"
}
# 2. ativar forest-aware SID filtering em forest trusts
Get-ADTrust -Filter { TrustType -eq "Forest" } |
Where-Object { -not $_.SIDFilteringForestAware } |
ForEach-Object {
Set-ADTrust -Identity $_.Name -SIDFilteringForestAware $true
Write-Host "Forest-aware SID filtering activado: $($_.Name)"
}
# 3. ativar selective authentication em forest trusts
Get-ADTrust -Filter { TrustType -eq "Forest" } |
Where-Object { -not $_.SelectiveAuthentication } |
ForEach-Object {
Set-ADTrust -Identity $_.Name -SelectiveAuthentication $true
}
10. Monitorização com Event Logs e Sentinel
# Event IDs críticos para monitorizar trust abuse:
# 4716 — Trust added to domain
# 4717 — Trust modified
# 4718 — Trust deleted
# 4769 — Kerberos ticket request (cross-domain)
# Query KQL para Sentinel — detectar modificação de trust
SecurityEvent
| where EventID == 4717
| project TimeGenerated, Account, Computer, EventData
// Sentinel: detectar logins cross-domain suspeitos
SecurityEvent
| where EventID == 4624
| where AuthenticationPackageName == "Kerberos"
| where AccountType == "User"
| where IpAddress != "127.0.0.1"
| extend Domain = tostring(split(Account, "@")[1])
| where Domain != tolower(Computer) // Cross-domain login
| summarize LoginCount = count() by Account, Domain, IpAddress, bin(TimeGenerated, 1h)
| where LoginCount > 5
| order by LoginCount desc
11. Cenário de Ataque Real: Passo a Passo
# Cenário: PME com 2 florestas (empresa.pt = root, sub.empresa.pt = subsidiária)
# Atacante compromete sub.empresa.pt (phishing DC admin)
# Trust: forest trust, SID filtering OFF (misconfiguration)
# Passo 1: Atacante enumera trusts
nltest /domain_trusts
# Output: sub.empresa.pt → empresa.pt (Forest trust, transitive)
# Passo 2: Atacante cria conta com SID History
# (requer DC compromised ou DCSync)
lsadump::dcsync /domain:sub.empresa.pt /user:krbtgt
# Usa ticket golden para criar conta com SID History
# Passo 3: Atacante acede a empresa.pt como Enterprise Admin
# Pois SID History contém S-1-5-21-empresa-519
# Prevenção: SID filtering ativo bloqueia o SID History
12. Ferramentas de Auditoria (BloodHound, PingCastle)
# BloodHound — mapear caminhos de ataque cross-forest
# https://github.com/SpecterOps/BloodHound
# Instalar SharpHound collector
Invoke-BloodHound -CollectionMethod All -Domain empresa.pt
# Queries Cypher para trust abuse:
# 1. Encontrar caminhos cross-forest
MATCH (n:Domain {name: "SUB.EMPRESA.PT"})-[:TrustedBy]->(m:Domain)
RETURN m.name
# 2. Utilizadores com SID History
MATCH (u:User) WHERE u.sIDHistory IS NOT NULL
RETURN u.name, u.sIDHistory
# PingCastle — relatório de conformidade AD
# https://www.pingcastle.com
PingCastle.exe --healthcheck --server empresa.pt --user admin --password ********
# Verificar score de risco
# Score < 65% = risco crítico
# Score 65-80% = risco médio
# Score > 80% = conformidade aceitável
13. Cenário Prático PME (multi-floresta)
# PME: empresa.pt (root) + sub.empresa.pt (subsidiária adquirida)
# Requisito: colaboradores da subsidiária acedem a file shares na root
# 1. Criar forest trust
netdom trust sub.empresa.pt /domain:empresa.pt /add /forest /twoway
# 2. ativar SID filtering (forest-aware)
Set-ADTrust -Identity "empresa.pt" -SIDFilteringForestAware $true
# 3. ativar selective authentication
Set-ADTrust -Identity "empresa.pt" -SelectiveAuthentication $true
# 4. Conceder acesso apenas a file server específico
$fs = Get-ADComputer -Identity "SRV-FS01" -Server "empresa.pt"
Get-ADGroup "Domain Users" -Server "sub.empresa.pt" |
Set-ADObject -Server "empresa.pt" -Add @{
'msDS-AllowedToAuthenticateTo' = "ldap/SRV-FS01.empresa.pt"
}
14. Checklist de Proteção
| Medida | Prioridade | Estado |
|---|---|---|
| Verificar SID filtering em todos os trusts | 🔴 Crítica | ☐ |
| ativar SID filtering onde estiver desactivado | 🔴 Crítica | ☐ |
| ativar selective authentication | 🟡 Alta | ☐ |
| Auditar contas com SID History | 🟡 Alta | ☐ |
| Correr BloodHound + PingCastle | 🟡 Alta | ☐ |
| Importar Sentinel detection rules (4717, 4718) | 🟡 Alta | ☐ |
| Documentar todos os trusts existentes | 🟢 Média | ☐ |
| Avaliar eliminação de trusts desnecessários | 🟢 Média | ☐ |
