Grant domain Builtin administrators local rights on lab workstations

This commit is contained in:
alexrg committed 2026-09-23 16:07:30 -06:00
1 parent 77091c023d
commit 738df9ceea
6 files changed
+180 -13

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
# Administradores de las estaciones Windows
El grupo `LCI\Administrators` ubicado en `CN=Builtin` administra Active
Directory y los controladores de dominio. No convierte por sí solo a sus
miembros en administradores locales de las estaciones Windows. `Domain Admins`
sí suele estar en el grupo local `Administrators` de cada equipo unido al
dominio, pero agregar una cuenta a `Domain Admins` le daría mucho más alcance.
La GPO **SGU - Windows client experience**, vinculada a `OU=Laboratorio`,
ejecuta `Enable-SguWorkstationAdministrators.ps1` al inicio de cada equipo
Windows. El script consulta por LDAP a los usuarios (incluidos miembros
anidados) de `CN=Administrators,CN=Builtin,DC=lci,DC=lasalle,DC=mx` y agrega
sus SID de dominio al grupo `Administrators` local. No se aplica a los
controladores de dominio ni a los equipos Linux. Si el DC no responde, no
cambia la pertenencia local y lo reintenta en el siguiente arranque.
En siguientes arranques elimina solo los SID que esta política había agregado
y que ya no pertenecen al grupo de AD. Conserva los administradores locales
y los grupos agregados por otras políticas. Los cambios de membresía de AD
requieren reiniciar la estación y volver a iniciar sesión para obtener un
token de acceso nuevo; no se elevan las sesiones ya abiertas.
Comprobación en un cliente Windows, desde una consola elevada:
```powershell
gpresult /scope computer /r
Get-LocalGroupMember -SID 'S-1-5-32-544'
whoami /groups
```
Para actualizar la política en un equipo encendido, ejecute
`gpupdate /target:computer /force`, reinicie e inicie sesión nuevamente. La
concesión se limita a los equipos Windows que heredan la GPO del laboratorio.
+4
View File
@@ -5,6 +5,10 @@ equipo en la GPO existente **SGU - Windows client experience**, vinculada a
`OU=Laboratorio`. El bootstrap del controlador lo instala después de crear esa `OU=Laboratorio`. El bootstrap del controlador lo instala después de crear esa
GPO. No crea una tarea programada en los clientes. GPO. No crea una tarea programada en los clientes.
La misma GPO ejecuta un segundo script de inicio para conceder administración
local a los miembros del grupo `Administrators` de Active Directory; véase
[Administradores de las estaciones Windows](workstation-administrators.md).
Al arrancar una estación Windows 10 u 11 unida al dominio, el script activa Al arrancar una estación Windows 10 u 11 unida al dominio, el script activa
Escritorio remoto con NLA y PowerShell Remoting, inicia `TermService` y `WinRM`, Escritorio remoto con NLA y PowerShell Remoting, inicia `TermService` y `WinRM`,
y añade el grupo `LCI\SG-Laboratorio-Usuarios-RDP` a Usuarios de escritorio y añade el grupo `LCI\SG-Laboratorio-Usuarios-RDP` a Usuarios de escritorio
@@ -0,0 +1,105 @@
[CmdletBinding()]
param()
$ErrorActionPreference = 'Stop'
$computer = Get-CimInstance Win32_ComputerSystem
if (-not $computer.PartOfDomain -or $computer.DomainRole -ge 4) { return }
# The domain's Builtin\Administrators group is not the local Administrators
# group on a member workstation, even though both have SID S-1-5-32-544.
# Resolve its *users* through LDAP, then grant their domain SIDs locally.
# The directory lookup must succeed before any local membership is changed.
$domainDn = 'DC=' + (($computer.Domain -split '\.') -join ',DC=')
$domainAdministratorsDn = "CN=Administrators,CN=Builtin,$domainDn"
$directoryRoot = [DirectoryServices.DirectoryEntry]::new("LDAP://$domainDn")
$searcher = [DirectoryServices.DirectorySearcher]::new($directoryRoot)
$searcher.Filter = "(&(objectCategory=person)(objectClass=user)(memberOf:1.2.840.113556.1.4.1941:=$domainAdministratorsDn))"
$searcher.PageSize = 500
$searcher.ClientTimeout = [TimeSpan]::FromSeconds(5)
$searcher.ServerTimeLimit = [TimeSpan]::FromSeconds(5)
[void]$searcher.PropertiesToLoad.Add('objectSid')
try {
$results = $searcher.FindAll()
try {
$desiredSids = @(
foreach ($result in $results) {
$sidBytes = [byte[]]$result.Properties['objectsid'][0]
if ($sidBytes.Length -gt 0) {
[Security.Principal.SecurityIdentifier]::new($sidBytes, 0).Value
}
}
) | Sort-Object -Unique
}
finally { $results.Dispose() }
}
catch {
Write-Warning "Cannot read domain Administrators; local membership was left unchanged: $($_.Exception.Message)"
return
}
finally {
$searcher.Dispose()
$directoryRoot.Dispose()
}
$localAdministratorsSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
$localAdministrators = Get-LocalGroup -SID $localAdministratorsSid
$group = [ADSI]("WinNT://$env:COMPUTERNAME/$($localAdministrators.Name),group")
function Get-MemberSids {
@($group.psbase.Invoke('Members') | ForEach-Object {
try {
$bytes = $_.GetType().InvokeMember('objectSid',
[Reflection.BindingFlags]::GetProperty, $null, $_, $null)
if ($bytes) {
[Security.Principal.SecurityIdentifier]::new([byte[]]$bytes, 0).Value
}
}
catch { }
})
}
$statePath = 'HKLM:\SOFTWARE\SGU\WorkstationAdministrators'
$managedSids = if (Test-Path -LiteralPath $statePath) {
@((Get-ItemProperty -LiteralPath $statePath -Name ManagedSids -ErrorAction SilentlyContinue).ManagedSids)
} else { @() }
$managedSids = @($managedSids | Where-Object { $_ -match '^S-1-5-21-' } | Sort-Object -Unique)
$presentSids = @(Get-MemberSids)
foreach ($sid in $desiredSids) {
if ($presentSids -notcontains $sid) {
Add-LocalGroupMember -Group $localAdministrators.Name -Member $sid
$presentSids += $sid
$managedSids += $sid
}
}
# Remove only entries previously added by this policy. Other local or domain
# administrators remain untouched if they have a separate authorization path.
foreach ($sid in @($managedSids | Where-Object { $desiredSids -notcontains $_ })) {
if ($presentSids -contains $sid) {
Remove-LocalGroupMember -Group $localAdministrators.Name -Member $sid
}
}
New-Item -Path $statePath -Force | Out-Null
$remainingManagedSids = @($managedSids |
Where-Object { $desiredSids -contains $_ } | Sort-Object -Unique)
if ($remainingManagedSids.Count -gt 0) {
$state = @{
Path = $statePath
Name = 'ManagedSids'
PropertyType = 'MultiString'
Value = $remainingManagedSids
Force = $true
}
New-ItemProperty @state | Out-Null
}
else {
Remove-ItemProperty -Path $statePath -Name ManagedSids -ErrorAction SilentlyContinue
}
$verifiedSids = @(Get-MemberSids)
$missingSids = @($desiredSids | Where-Object { $verifiedSids -notcontains $_ })
if ($missingSids.Count -gt 0) {
throw "Domain Administrators were not added to local Administrators: $($missingSids -join ', ')"
}
@@ -520,6 +520,7 @@ foreach ($requiredPath in @(
(Join-Path $scriptsRoot 'Set-LabBrokerDns.ps1'), (Join-Path $scriptsRoot 'Set-LabBrokerDns.ps1'),
(Join-Path $scriptsRoot 'Set-SguDomainComputerPolicies.ps1'), (Join-Path $scriptsRoot 'Set-SguDomainComputerPolicies.ps1'),
(Join-Path $scriptsRoot 'Enable-SguWorkstationRemoteAccess.ps1'), (Join-Path $scriptsRoot 'Enable-SguWorkstationRemoteAccess.ps1'),
(Join-Path $scriptsRoot 'Enable-SguWorkstationAdministrators.ps1'),
(Join-Path $scriptsRoot 'Install-SguWorkstationRemoteAccessPolicy.ps1'), (Join-Path $scriptsRoot 'Install-SguWorkstationRemoteAccessPolicy.ps1'),
(Join-Path $scriptsRoot 'Set-SguDomainUserPolicies.ps1'), (Join-Path $scriptsRoot 'Set-SguDomainUserPolicies.ps1'),
(Join-Path $scriptsRoot 'Set-SguLaboratorioWallpaperPolicy.ps1'), (Join-Path $scriptsRoot 'Set-SguLaboratorioWallpaperPolicy.ps1'),
@@ -28,25 +28,48 @@ if (-not @($links | Where-Object { $_.DisplayName -eq $GpoName -and
throw "The existing GPO '$GpoName' must be linked and enabled on $TargetOuDn." throw "The existing GPO '$GpoName' must be linked and enabled on $TargetOuDn."
} }
# The existing machine GPO also manages the credential tile. The startup # The existing machine GPO also manages the credential tile. These startup
# script is a native Group Policy extension, not a scheduled client task. # scripts are a native Group Policy extension, not scheduled client tasks.
$scriptName = 'Enable-SguWorkstationRemoteAccess.ps1' $scriptNames = @(
$sourcePath = Join-Path $PSScriptRoot $scriptName 'Enable-SguWorkstationRemoteAccess.ps1',
'Enable-SguWorkstationAdministrators.ps1'
)
$startupRoot = Join-Path $env:WINDIR "SYSVOL\domain\Policies\{$($gpo.Id)}\Machine\Scripts" $startupRoot = Join-Path $env:WINDIR "SYSVOL\domain\Policies\{$($gpo.Id)}\Machine\Scripts"
$startupPath = Join-Path $startupRoot "Startup\$scriptName"
$scriptsIniPath = Join-Path $startupRoot 'scripts.ini' $scriptsIniPath = Join-Path $startupRoot 'scripts.ini'
$source = [IO.File]::ReadAllText($sourcePath) $startupScripts = @(
$unc = "\\$domainName\SYSVOL\$domainName\Policies\{$($gpo.Id)}\Machine\Scripts\Startup\$scriptName" foreach ($scriptName in $scriptNames) {
$ini = "[Startup]`r`n0CmdLine=powershell.exe`r`n0Parameters=-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$unc`"`r`n" $sourcePath = Join-Path $PSScriptRoot $scriptName
$scriptChanged = -not (Test-Path -LiteralPath $startupPath) -or $startupPath = Join-Path $startupRoot "Startup\$scriptName"
[IO.File]::ReadAllText($startupPath) -cne $source $source = [IO.File]::ReadAllText($sourcePath)
[pscustomobject]@{
Name = $scriptName
Path = $startupPath
Source = $source
Changed = -not (Test-Path -LiteralPath $startupPath) -or
[IO.File]::ReadAllText($startupPath) -cne $source
}
}
)
$iniLines = @('[Startup]')
for ($index = 0; $index -lt $scriptNames.Count; $index++) {
$unc = "\\$domainName\SYSVOL\$domainName\Policies\{$($gpo.Id)}\Machine\Scripts\Startup\$($scriptNames[$index])"
$iniLines += "${index}CmdLine=powershell.exe"
$iniLines += "${index}Parameters=-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$unc`""
}
$ini = ($iniLines -join "`r`n") + "`r`n"
$scriptChanged = @($startupScripts | Where-Object Changed).Count -gt 0
$iniChanged = -not (Test-Path -LiteralPath $scriptsIniPath) -or $iniChanged = -not (Test-Path -LiteralPath $scriptsIniPath) -or
[IO.File]::ReadAllText($scriptsIniPath) -cne $ini [IO.File]::ReadAllText($scriptsIniPath) -cne $ini
if (($scriptChanged -or $iniChanged) -and if (($scriptChanged -or $iniChanged) -and
$PSCmdlet.ShouldProcess($startupRoot, 'Install computer startup script')) { $PSCmdlet.ShouldProcess($startupRoot, 'Install computer startup script')) {
New-Item -ItemType Directory -Path (Split-Path $startupPath) -Force | Out-Null New-Item -ItemType Directory -Path (Join-Path $startupRoot 'Startup') -Force | Out-Null
[IO.File]::WriteAllText($startupPath, $source, [Text.UTF8Encoding]::new($false)) foreach ($startupScript in $startupScripts) {
if ($startupScript.Changed) {
[IO.File]::WriteAllText($startupScript.Path, $startupScript.Source,
[Text.UTF8Encoding]::new($false))
}
}
[IO.File]::WriteAllText($scriptsIniPath, $ini, [Text.Encoding]::Unicode) [IO.File]::WriteAllText($scriptsIniPath, $ini, [Text.Encoding]::Unicode)
$gpoDn = "CN={$($gpo.Id)},CN=Policies,CN=System,$($domain.DistinguishedName)" $gpoDn = "CN={$($gpo.Id)},CN=Policies,CN=System,$($domain.DistinguishedName)"
$adGpo = Get-ADObject -Identity $gpoDn -Server $DomainController ` $adGpo = Get-ADObject -Identity $gpoDn -Server $DomainController `
@@ -72,6 +95,6 @@ if (($scriptChanged -or $iniChanged) -and
GpoName = $GpoName GpoName = $GpoName
GpoId = $gpo.Id GpoId = $gpo.Id
TargetOu = $TargetOuDn TargetOu = $TargetOuDn
StartupScript = $startupPath StartupScripts = @($startupScripts.Path)
Changed = $scriptChanged -or $iniChanged Changed = $scriptChanged -or $iniChanged
} }
+1
View File
@@ -211,6 +211,7 @@ $serverScripts = @(
'Enable-SguAzureUserRoaming.ps1', 'Enable-SguAzureUserRoaming.ps1',
'Enable-SguServerRemoteManagement.ps1', 'Enable-SguServerRemoteManagement.ps1',
'Enable-SguWorkstationRemoteAccess.ps1', 'Enable-SguWorkstationRemoteAccess.ps1',
'Enable-SguWorkstationAdministrators.ps1',
'Get-SguUsageReport.ps1', 'Get-SguUsageReport.ps1',
'Get-SguBrokerLog.ps1', 'Get-SguBrokerLog.ps1',
'Install-SguDomainMonitoring.ps1', 'Install-SguDomainMonitoring.ps1',