diff --git a/docs/workstation-administrators.md b/docs/workstation-administrators.md new file mode 100644 index 0000000..20ff5a4 --- /dev/null +++ b/docs/workstation-administrators.md @@ -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. diff --git a/docs/workstation-remote-access.md b/docs/workstation-remote-access.md index f07ad7d..973640c 100644 --- a/docs/workstation-remote-access.md +++ b/docs/workstation-remote-access.md @@ -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 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 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 diff --git a/scripts/Enable-SguWorkstationAdministrators.ps1 b/scripts/Enable-SguWorkstationAdministrators.ps1 new file mode 100644 index 0000000..7a707fd --- /dev/null +++ b/scripts/Enable-SguWorkstationAdministrators.ps1 @@ -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 ', ')" +} diff --git a/scripts/Initialize-SguDomainController.ps1 b/scripts/Initialize-SguDomainController.ps1 index 8312d16..5087bd6 100644 --- a/scripts/Initialize-SguDomainController.ps1 +++ b/scripts/Initialize-SguDomainController.ps1 @@ -520,6 +520,7 @@ foreach ($requiredPath in @( (Join-Path $scriptsRoot 'Set-LabBrokerDns.ps1'), (Join-Path $scriptsRoot 'Set-SguDomainComputerPolicies.ps1'), (Join-Path $scriptsRoot 'Enable-SguWorkstationRemoteAccess.ps1'), + (Join-Path $scriptsRoot 'Enable-SguWorkstationAdministrators.ps1'), (Join-Path $scriptsRoot 'Install-SguWorkstationRemoteAccessPolicy.ps1'), (Join-Path $scriptsRoot 'Set-SguDomainUserPolicies.ps1'), (Join-Path $scriptsRoot 'Set-SguLaboratorioWallpaperPolicy.ps1'), diff --git a/scripts/Install-SguWorkstationRemoteAccessPolicy.ps1 b/scripts/Install-SguWorkstationRemoteAccessPolicy.ps1 index 1b07217..17e0e51 100644 --- a/scripts/Install-SguWorkstationRemoteAccessPolicy.ps1 +++ b/scripts/Install-SguWorkstationRemoteAccessPolicy.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." } -# The existing machine GPO also manages the credential tile. The startup -# script is a native Group Policy extension, not a scheduled client task. -$scriptName = 'Enable-SguWorkstationRemoteAccess.ps1' -$sourcePath = Join-Path $PSScriptRoot $scriptName +# The existing machine GPO also manages the credential tile. These startup +# scripts are a native Group Policy extension, not scheduled client tasks. +$scriptNames = @( + 'Enable-SguWorkstationRemoteAccess.ps1', + 'Enable-SguWorkstationAdministrators.ps1' +) $startupRoot = Join-Path $env:WINDIR "SYSVOL\domain\Policies\{$($gpo.Id)}\Machine\Scripts" -$startupPath = Join-Path $startupRoot "Startup\$scriptName" $scriptsIniPath = Join-Path $startupRoot 'scripts.ini' -$source = [IO.File]::ReadAllText($sourcePath) -$unc = "\\$domainName\SYSVOL\$domainName\Policies\{$($gpo.Id)}\Machine\Scripts\Startup\$scriptName" -$ini = "[Startup]`r`n0CmdLine=powershell.exe`r`n0Parameters=-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$unc`"`r`n" -$scriptChanged = -not (Test-Path -LiteralPath $startupPath) -or - [IO.File]::ReadAllText($startupPath) -cne $source +$startupScripts = @( + foreach ($scriptName in $scriptNames) { + $sourcePath = Join-Path $PSScriptRoot $scriptName + $startupPath = Join-Path $startupRoot "Startup\$scriptName" + $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 [IO.File]::ReadAllText($scriptsIniPath) -cne $ini if (($scriptChanged -or $iniChanged) -and $PSCmdlet.ShouldProcess($startupRoot, 'Install computer startup script')) { - New-Item -ItemType Directory -Path (Split-Path $startupPath) -Force | Out-Null - [IO.File]::WriteAllText($startupPath, $source, [Text.UTF8Encoding]::new($false)) + New-Item -ItemType Directory -Path (Join-Path $startupRoot 'Startup') -Force | Out-Null + 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) $gpoDn = "CN={$($gpo.Id)},CN=Policies,CN=System,$($domain.DistinguishedName)" $adGpo = Get-ADObject -Identity $gpoDn -Server $DomainController ` @@ -72,6 +95,6 @@ if (($scriptChanged -or $iniChanged) -and GpoName = $GpoName GpoId = $gpo.Id TargetOu = $TargetOuDn - StartupScript = $startupPath + StartupScripts = @($startupScripts.Path) Changed = $scriptChanged -or $iniChanged } diff --git a/scripts/New-SguBootstrapPackages.ps1 b/scripts/New-SguBootstrapPackages.ps1 index de06e3c..49ba07b 100644 --- a/scripts/New-SguBootstrapPackages.ps1 +++ b/scripts/New-SguBootstrapPackages.ps1 @@ -211,6 +211,7 @@ $serverScripts = @( 'Enable-SguAzureUserRoaming.ps1', 'Enable-SguServerRemoteManagement.ps1', 'Enable-SguWorkstationRemoteAccess.ps1', + 'Enable-SguWorkstationAdministrators.ps1', 'Get-SguUsageReport.ps1', 'Get-SguBrokerLog.ps1', 'Install-SguDomainMonitoring.ps1',