From 5cda541e3d5af2027668fe49e6e61fa9d5c06b35 Mon Sep 17 00:00:00 2001 From: Alejandro Rosales Date: Wed, 14 Oct 2026 21:49:32 -0600 Subject: [PATCH] Consolidate laboratory network and client maintenance policies --- docs/ced-wifi-release.md | 24 ++-- docs/policy-consolidation.md | 96 +++++++++++++ docs/release-0.6.23.md | 25 ++++ scripts/Enable-SguWorkstationRemoteAccess.ps1 | 2 +- scripts/Install-SguCedWifiMaintenance.ps1 | 26 ++-- ...tall-SguCredentialProviderUpdatePolicy.ps1 | 13 +- scripts/Install-SguDomainMonitoring.ps1 | 4 +- scripts/Install-SguEnrollmentGuard.ps1 | 3 + scripts/Invoke-SguCedClientEnrollment.ps1 | 52 ++----- scripts/Invoke-SguCedPreparation.ps1 | 33 ++--- .../Invoke-SguWorkstationConsolidation.ps1 | 57 ++++++++ scripts/Merge-SguClientPolicies.ps1 | 135 ++++++++++++++++++ scripts/New-SguBootstrapPackages.ps1 | 15 +- scripts/Repair-SguCedWifi.ps1 | 15 +- scripts/Repair-SguClientEnrollment.ps1 | 6 + scripts/Set-SguCedClientNetwork.ps1 | 68 +++++++++ scripts/Set-SguCedDnsPolicy.ps1 | 8 +- scripts/Set-SguCedWifiPolicy.ps1 | 14 +- scripts/ced-network.json | 9 ++ tests/CedNetworkConsolidation.Tests.ps1 | 36 +++++ 20 files changed, 534 insertions(+), 107 deletions(-) create mode 100644 docs/policy-consolidation.md create mode 100644 docs/release-0.6.23.md create mode 100644 scripts/Invoke-SguWorkstationConsolidation.ps1 create mode 100644 scripts/Merge-SguClientPolicies.ps1 create mode 100644 scripts/Set-SguCedClientNetwork.ps1 create mode 100644 scripts/ced-network.json create mode 100644 tests/CedNetworkConsolidation.Tests.ps1 diff --git a/docs/ced-wifi-release.md b/docs/ced-wifi-release.md index 81ce091..c2cfcf4 100644 --- a/docs/ced-wifi-release.md +++ b/docs/ced-wifi-release.md @@ -3,7 +3,7 @@ Este paquete publica la política **CED - Wi-Fi de salas** para las estaciones `AF-*`, `SD-*` y `SI-*` de Centro de Experiencia Digital, dentro de Laboratorio. Excluye servidores y estaciones `APPS-*`. Está preparado para el dominio -`lci.lasalle.mx`, el controlador local `192.168.54.211` y el SSID +`lci.lasalle.mx`, el controlador principal `SGU-DC01` en `20.9.81.130` y el SSID **Centro de Experiencia Digital**. Para otra infraestructura, revise estas direcciones y los nombres en los scripts antes de publicar. @@ -23,14 +23,14 @@ manualmente; una conexión alternativa elegida a mano se respeta. ## Publicación administrativa -Ejecute en SGU-DC02 con permisos de administración de dominio y GPO. Mantenga -juntos los seis scripts del paquete. Proporcione un perfil Personal WPA2/WPA3 AES +Ejecute en SGU-DC01 con permisos de administración de dominio y GPO. Mantenga +juntos todos los archivos del paquete. Proporcione un perfil Personal WPA2/WPA3 AES con su clave en una ubicación privada accesible solamente por administradores. No lo coloque en SYSVOL, repositorios, notas de release ni carpetas compartidas. ```powershell -.\Set-SguCedWifiPolicy.ps1 -ProfilePath 'C:\ruta-privada\CED.xml' -DomainController SGU-DC02 -.\Sync-SguCedWifiReaders.ps1 -DomainController SGU-DC02 -InstallRefreshTask +.\Set-SguCedWifiPolicy.ps1 -ProfilePath 'C:\ruta-privada\CED.xml' -DomainController SGU-DC01 +.\Sync-SguCedWifiReaders.ps1 -DomainController SGU-DC01 -InstallRefreshTask ``` La publicación usa WLAN nativo de Windows y un script de inicio de equipo de @@ -38,12 +38,16 @@ Directiva de grupos. La recuperación adicional se ejecuta como SYSTEM al arrancar, terminar una actualización de políticas, cerrar sesión o conectar Wi-Fi; no sondea periódicamente. La clave se lee del objeto WLAN restringido de AD usando autenticación de equipo con firma y cifrado LDAP; se conserva cifrada -en el almacén de perfiles de Windows. No hay contraseñas de administrador en el -cliente ni claves Wi-Fi en los scripts del paquete. +en el almacén de perfiles de Windows. Los clientes priorizan DNS del controlador +principal y mantienen `SGU-DC02` solo como DNS de respaldo. Un bloque administrado +en `hosts` hace que el FQDN de `SGU-DC01` use su extremo público, sin cambiar la +dirección privada que los controladores usan para replicar. No hay contraseñas de +administrador en el cliente ni claves Wi-Fi en los scripts del paquete. -La GPO existente también conserva su integración previa con Configuration -Manager. Si el dominio usa una versión propia de -`Invoke-SguCedClientEnrollment.ps1`, conserve esa versión al publicar. +Configuration Manager se administra exclusivamente desde su GPO global de +SYSTEMCENTER. La GPO Wi-Fi no instala un segundo agente ni una tarea repetitiva. +Para consolidar el dominio existente, consulte `policy-consolidation.md` y use +`Merge-SguClientPolicies.ps1` en el principal. El estado sin secretos queda en `C:\ProgramData\LCI-Admin\CED-WiFi\machine-wifi-status.json`. diff --git a/docs/policy-consolidation.md b/docs/policy-consolidation.md new file mode 100644 index 0000000..60ae511 --- /dev/null +++ b/docs/policy-consolidation.md @@ -0,0 +1,96 @@ +# Consolidación de políticas del laboratorio + +La configuración vigente tiene un responsable por función. Las GPO se ven en +`gpmc.msc`; sus scripts se guardan en +`\\SGU-DC01.lci.lasalle.mx\SYSVOL\lci.lasalle.mx\Policies\{GUID}\Machine\Scripts`. +Las tareas se ven en `taskschd.msc` de cada equipo. Los servicios instalados se +administran en `services.msc`. + +| Función | Responsable | Cuándo se ejecuta | +| --- | --- | --- | +| DNS del dominio en CED | CED - DNS de dominio; configuración compartida `ced-network.json` | Actualización nativa de políticas | +| Perfil Wi-Fi de AF, SD y SI | CED - Wi-Fi de salas; WLAN AutoConfig y `CED WiFi policy connection` | Arranque, políticas de equipo, cierre de sesión y conexión Wi-Fi | +| Proveedor de credenciales | SGU - Credential Provider update | Arranque; comprueba la instalación antes de descargar | +| RDP, WinRM y firewall de administración | La Salle - Workstation remote management | GPO nativa y un único auxiliar de arranque | +| Agente ConfigMgr | LCI-ConfigMgr2509-ClientRegistration; SYSTEMCENTER | Registro de la tarea por GPO, arranque y disponibilidad de red | +| Agente SCOM | LCI - SCOM agent deployment; SYSTEMCENTER | Registro de la tarea por GPO, arranque y disponibilidad de red | +| Inventario auxiliar de Azure | SGU-Monitoring-Inventory | Cada hora; no representa el monitoreo continuo de SCOM | +| Retención de eventos | SGU-Monitoring-Retention | Diariamente | + +ConfigMgr y SCOM conservan sus instaladores con comprobación de versión, sitio, +clave de confianza o grupo de administración. Ya no tienen un temporizador de +30 minutos. Sus tareas permiten dos reintentos a intervalos de cinco minutos +solo cuando falla una ejecución. Para publicar una nueva versión del agente, +actualice el origen de SYSTEMCENTER y su GPO; un arranque o una conexión de red +también vuelve a comprobar la versión. Los agentes continúan funcionando entre +estas comprobaciones. + +La GPO Wi-Fi deja de instalar ConfigMgr. La GPO de experiencia de Windows +conserva la configuración visual y el auxiliar de administradores, pero deja +de repetir la configuración de acceso remoto. El guardián antiguo del proveedor +se deshabilita cuando se verifican proveedor, valores de inicio de sesión, +servicios, reenvío de eventos y RustDesk cuando estaba configurado. Se conservan +sus archivos y una copia de su tarea. No reinstala el paquete antiguo cada día. + +## DNS y conectividad + +En CED, `ced-network.json` define `20.9.81.130` primero y `192.168.54.211` como +respaldo, tanto para el adaptador como para NRPT. Solo AF/SD/SI de CED reciben +la modificación del adaptador Wi-Fi. El extremo público de SGU-DC01 y el nombre +del dominio se mantienen en un bloque administrado de `hosts`; los alias de +broker y RustDesk existentes se conservan. Una entrada manual contradictoria +provoca un error para revisión, sin sobrescribirla. + +Una red de emergencia elegida manualmente conserva sus DNS por DHCP y no se +fuerza una desconexión. NRPT mantiene la resolución del dominio. Esa resolución +y el acceso a AD dependen de que el extremo permita la red de salida utilizada. +El orden de DNS expresa preferencia; Active Directory todavía puede elegir +otro controlador mediante DC Locator y sus sitios. No se altera la replicación +privada de los controladores. + +## Aplicación a clientes + +Con conexión al dominio y canal seguro sano, ejecutar como administrador: + +```powershell +Test-ComputerSecureChannel -Server SGU-DC01.lci.lasalle.mx +gpupdate.exe /target:computer /force +``` + +Después reiniciar para procesar los scripts de arranque. No volver a enrolar +una estación que ya tiene el canal seguro sano. Los equipos desconectados +reciben la configuración cuando vuelven a comunicarse con el dominio. + +Estado Wi-Fi sin claves: +`C:\ProgramData\LCI-Admin\CED-WiFi\machine-wifi-status.json`. +Respaldos de tareas retiradas: +`C:\ProgramData\LCI-Admin\PolicyConsolidation\*.before.xml`. + +## Publicación y reversión + +En el principal, con permisos administrativos, conservar una copia nativa de +las GPO mediante `Backup-GPO`. Ejecutar desde el conjunto completo de scripts: + +```powershell +.\Merge-SguClientPolicies.ps1 -WhatIf +.\Merge-SguClientPolicies.ps1 +``` + +Este comando consolida GPO existentes con identificadores conocidos del +laboratorio; no crea un bosque. Verifica el esquema de las tareas con Windows, +actualiza las versiones de AD y SYSVOL solo al cambiar archivos, y conserva el +paquete y SHA-256 previamente fijados para el proveedor. + +Para revertir, restaurar individualmente las GPO modificadas desde su BackupId, +actualizar políticas y reiniciar. Las tareas antiguas deshabilitadas pueden +habilitarse con `Enable-ScheduledTask`; antes de restaurar el guardián, retirar +`ProviderManagedByGpo` de +`HKLM:\SOFTWARE\Policies\LaSalle\ClientMaintenance`. El cambio de hosts tiene +copia en `C:\ProgramData\LCI-Admin\CED-WiFi\hosts.before-consolidation`. +Restaurar archivos de una estación usando exclusivamente su propia copia. + +Se conservan los lectores de permisos Wi-Fi, el mantenimiento DNS de Sala +Inmersiva, el procesamiento de altas Linux de RustDesk y la selección de origen +privado de DC02: atienden funciones vigentes. No se cambia su frecuencia sin +reemplazar esas funciones. Los fondos, restricciones de navegación, perfiles, +servicios y cuentas existentes permanecen bajo sus políticas actuales. diff --git a/docs/release-0.6.23.md b/docs/release-0.6.23.md new file mode 100644 index 0000000..425545a --- /dev/null +++ b/docs/release-0.6.23.md @@ -0,0 +1,25 @@ +# v0.6.23 — Consolidación de políticas + +Unifica el mantenimiento del laboratorio conservando la configuración útil: + +- DNS del adaptador y NRPT de CED prefieren SGU-DC01; DC02 queda como respaldo. + Una única configuración compartida evita que los auxiliares se contradigan. +- Wi-Fi de equipo antes de iniciar sesión y después de cerrarla, con recuperación + por eventos y selección manual de una red de emergencia. +- Una GPO mantiene el acceso remoto. El enrolamiento ConfigMgr antiguo de CED + deja de instalarse desde la GPO Wi-Fi. +- Las tareas de instalación ConfigMgr y SCOM pasan de cada 30 minutos a eventos + de registro por GPO, arranque y conexión de red. Conservan versiones objetivo, + configuración y dos reintentos limitados ante fallos. +- El guardián antiguo del proveedor se retira después de comprobar los servicios + y la configuración que lo sustituyen; sus archivos y tareas quedan respaldados. +- El inventario auxiliar de Azure pasa de cinco minutos a una hora; se conservan + SCOM, la retención de eventos, las políticas visuales y las de navegación. + +`Merge-SguClientPolicies.ps1` actualiza el dominio existente. No ejecute el +bootstrap de creación de bosque para aplicar esta consolidación. Consulte +`policy-consolidation.md` para responsables, aplicación, límites y reversión. + +La consolidación de GPO conserva el paquete y SHA-256 del proveedor ya fijados +en el dominio. Esta versión cambia los scripts de mantenimiento, sin modificar +el código de autenticación del proveedor. diff --git a/scripts/Enable-SguWorkstationRemoteAccess.ps1 b/scripts/Enable-SguWorkstationRemoteAccess.ps1 index 2db4eda..beb5742 100644 --- a/scripts/Enable-SguWorkstationRemoteAccess.ps1 +++ b/scripts/Enable-SguWorkstationRemoteAccess.ps1 @@ -12,7 +12,7 @@ if (-not $computer.PartOfDomain -or $computer.DomainRole -ne 1) { return } # A site-local DNS server is optional. Change only an adapter whose directly # connected subnet contains that server, after verifying its authoritative DNS # answer. Other sites, VPN adapters and Internet-only interfaces are preserved. -if ($LocalDnsServer) { +if ($LocalDnsServer -and $env:COMPUTERNAME -notmatch '^(AF|SD|SI)-') { $dnsBytes = ([Net.IPAddress]::Parse($LocalDnsServer)).GetAddressBytes() foreach ($ip in @(Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.AddressState -eq 'Preferred' -and $_.PrefixLength -gt 0 -and $_.PrefixLength -lt 32 diff --git a/scripts/Install-SguCedWifiMaintenance.ps1 b/scripts/Install-SguCedWifiMaintenance.ps1 index ef323dd..40b91f3 100644 --- a/scripts/Install-SguCedWifiMaintenance.ps1 +++ b/scripts/Install-SguCedWifiMaintenance.ps1 @@ -13,6 +13,14 @@ foreach ($sid in 'S-1-5-18','S-1-5-32-544') { [Security.Principal.SecurityIdentifier]::new($sid),'FullControl','ContainerInherit,ObjectInherit','None','Allow')) } if((Get-Acl -LiteralPath $destination).GetSecurityDescriptorSddlForm([Security.AccessControl.AccessControlSections]::Access) -ne $acl.GetSecurityDescriptorSddlForm([Security.AccessControl.AccessControlSections]::Access)){Set-Acl -LiteralPath $destination -AclObject $acl} +foreach($name in 'ced-network.json','Set-SguCedClientNetwork.ps1'){ + $source=Join-Path $PSScriptRoot $name + $target=Join-Path $destination $name + if($source -ine $target -and (-not(Test-Path -LiteralPath $target) -or (Get-FileHash -LiteralPath $source).Hash -ne (Get-FileHash -LiteralPath $target).Hash)){Copy-Item -LiteralPath $source -Destination $target -Force} +} +$networkConfiguration=[IO.File]::ReadAllText((Join-Path $destination 'ced-network.json'))|ConvertFrom-Json +$primaryDomainController=[string]$networkConfiguration.PrimaryController +& (Join-Path $destination 'Set-SguCedClientNetwork.ps1')|Out-Null $source=Join-Path $PSScriptRoot 'Repair-SguCedWifi.ps1' $helper=Join-Path $destination 'Repair-SguCedWifi.ps1' if($source -ine $helper -and (-not(Test-Path -LiteralPath $helper) -or (Get-FileHash -LiteralPath $source).Hash -ne (Get-FileHash -LiteralPath $helper).Hash)){Copy-Item -LiteralPath $source -Destination $helper -Force} @@ -44,22 +52,24 @@ $profileState=& $helper if(-not $profileState.MachineProfileReady){ # Computer authentication reads the existing restricted AD WLAN object. # The PSK stays in memory and Windows encrypts it into its machine store. - $searchRoot=$null;$searcher=$null + $searchRoot=$null;$searcher=$null;$found=$null try{ - # Serverless LDAP can select Azure's private DC address, which these clients - # cannot route to. Use the local DC with signed and sealed machine binding. + # The managed hosts entry directs this FQDN to the Azure public endpoint of + # the primary DC; the signed and sealed machine binding protects the read. $domainDn=($computer.Domain.Split('.')|ForEach-Object{'DC='+$_}) -join ',' - $searchRoot=[DirectoryServices.DirectoryEntry]::new('LDAP://192.168.54.211/CN=Policies,CN=System,'+$domainDn) - $searchRoot.AuthenticationType=[DirectoryServices.AuthenticationTypes]::Secure -bor [DirectoryServices.AuthenticationTypes]::Signing -bor [DirectoryServices.AuthenticationTypes]::Sealing + $authentication=[DirectoryServices.AuthenticationTypes]::Secure -bor [DirectoryServices.AuthenticationTypes]::Signing -bor [DirectoryServices.AuthenticationTypes]::Sealing + $searchRoot=[DirectoryServices.DirectoryEntry]::new("LDAP://$primaryDomainController/CN=Policies,CN=System,"+$domainDn,$null,$null,$authentication) $searcher=[DirectoryServices.DirectorySearcher]::new($searchRoot) + $searcher.ClientTimeout=[TimeSpan]::FromSeconds(10) + $searcher.ServerTimeLimit=[TimeSpan]::FromSeconds(10) $searcher.Filter='(&(objectClass=ms-net-ieee-80211-GroupPolicy)(cn=CED Wi-Fi))' [void]$searcher.PropertiesToLoad.Add('ms-net-ieee-80211-GP-PolicyData') - $found=@($searcher.FindAll()) + $found=$searcher.FindAll() if($found.Count -ne 1){throw 'Expected exactly one authorized CED WLAN policy.'} [xml]$policy=[string]$found[0].Properties['ms-net-ieee-80211-gp-policydata'][0] $profile=$policy.SelectSingleNode('//*[local-name()="WLANProfile"]') $profileState=& $helper -ProvisionXml $profile.OuterXml - }finally{if($searcher){$searcher.Dispose()};if($searchRoot){$searchRoot.Dispose()};$profile=$null;$policy=$null} + }finally{if($found){$found.Dispose()};if($searcher){$searcher.Dispose()};if($searchRoot){$searchRoot.psbase.Dispose()};$profile=$null;$policy=$null} } if(-not $profileState.MachineProfileReady){throw 'Machine Wi-Fi profile is not ready.'} -Start-ScheduledTask -TaskName $taskName +$profileState diff --git a/scripts/Install-SguCredentialProviderUpdatePolicy.ps1 b/scripts/Install-SguCredentialProviderUpdatePolicy.ps1 index 23bef9b..b457b62 100644 --- a/scripts/Install-SguCredentialProviderUpdatePolicy.ps1 +++ b/scripts/Install-SguCredentialProviderUpdatePolicy.ps1 @@ -23,6 +23,11 @@ if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administra Import-Module ActiveDirectory -ErrorAction Stop Import-Module GroupPolicy -ErrorAction Stop +if ($env:COMPUTERNAME -ine $DomainController.Split('.')[0]) { + throw 'Publish on the specified domain controller to keep AD and SYSVOL consistent.' +} +$consolidationSource = Join-Path $PSScriptRoot 'Invoke-SguWorkstationConsolidation.ps1' +if (-not (Test-Path -LiteralPath $consolidationSource)) { throw 'Invoke-SguWorkstationConsolidation.ps1 is required.' } $domain = Get-ADDomain -Server $DomainController -ErrorAction Stop $domainDnsRoot = $domain.DNSRoot @@ -83,7 +88,11 @@ Set-ItemProperty -Path `$logonUiPath -Name LastLoggedOnProvider -Value '{D789CFD `$updateRoot = Join-Path `$env:ProgramData "SGU\CredentialProviderUpdates\`$version" `$markerPath = Join-Path `$updateRoot 'complete.marker' -if (Test-Path -LiteralPath `$markerPath -PathType Leaf) { +`$registered = Get-Item 'HKLM:\SOFTWARE\Classes\CLSID\{D789CFD8-5AD4-489F-9B83-7EB5D9D09335}\InprocServer32' -ErrorAction SilentlyContinue +`$display = Get-Item 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers\{D789CFD8-5AD4-489F-9B83-7EB5D9D09335}' -ErrorAction SilentlyContinue +`$providerHealthy = `$registered -and (Test-Path -LiteralPath `$registered.GetValue('')) -and `$display -and `$display.GetValue('') -eq 'Acceso Institucional' +if ((Test-Path -LiteralPath `$markerPath -PathType Leaf) -and `$providerHealthy) { + & (Join-Path `$PSScriptRoot 'Invoke-SguWorkstationConsolidation.ps1') | Out-Null exit 0 } @@ -139,10 +148,12 @@ if (-not `$runtimeInstalled) { & `$installScript @installParameters | Out-Null [IO.File]::WriteAllText(`$markerPath, (Get-Date).ToUniversalTime().ToString('o'), [Text.UTF8Encoding]::new(`$false)) +& (Join-Path `$PSScriptRoot 'Invoke-SguWorkstationConsolidation.ps1') | Out-Null "@ if ($PSCmdlet.ShouldProcess($startupPath, "Install '$scriptName' as a computer startup script")) { New-Item -ItemType Directory -Path $startupPath -Force | Out-Null + Copy-Item -LiteralPath $consolidationSource -Destination (Join-Path $startupPath 'Invoke-SguWorkstationConsolidation.ps1') -Force [IO.File]::WriteAllText($scriptPath, $startupScript, [Text.UTF8Encoding]::new($false)) $scriptUncPath = "\\$domainDnsRoot\SYSVOL\$domainDnsRoot\Policies\{$($gpo.Id)}\Machine\Scripts\Startup\$scriptName" $scriptsIni = "[Startup]`r`n0CmdLine=powershell.exe`r`n0Parameters=-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$scriptUncPath`"`r`n" diff --git a/scripts/Install-SguDomainMonitoring.ps1 b/scripts/Install-SguDomainMonitoring.ps1 index 4828c64..5fd8371 100644 --- a/scripts/Install-SguDomainMonitoring.ps1 +++ b/scripts/Install-SguDomainMonitoring.ps1 @@ -4,6 +4,8 @@ param( [string]$CollectorFqdn = "$env:COMPUTERNAME.$env:USERDNSDOMAIN", [string]$ComputerOuDn = 'OU=Laboratorio,DC=lci,DC=lasalle,DC=mx', [string]$MonitoringRoot = 'C:\ProgramData\SGU\Monitoring', + [ValidateRange(5,1440)] + [int]$InventoryIntervalMinutes = 60, [ValidateRange(30, 730)] [int]$RetentionDays = 183 ) @@ -114,7 +116,7 @@ if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, 'Install the SGU domain monitorin "-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$maintenanceScript`" " + "-MonitoringRoot `"$MonitoringRoot`" -ComputerOuDn `"$ComputerOuDn`" -RetentionDays $RetentionDays -InventoryOnly") $inventoryTrigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) ` - -RepetitionInterval (New-TimeSpan -Minutes 5) ` + -RepetitionInterval (New-TimeSpan -Minutes $InventoryIntervalMinutes) ` -RepetitionDuration (New-TimeSpan -Days 3650) $taskSettings = New-ScheduledTaskSettingsSet -StartWhenAvailable ` -ExecutionTimeLimit (New-TimeSpan -Minutes 10) -RestartCount 2 ` diff --git a/scripts/Install-SguEnrollmentGuard.ps1 b/scripts/Install-SguEnrollmentGuard.ps1 index 2781a02..c079a46 100644 --- a/scripts/Install-SguEnrollmentGuard.ps1 +++ b/scripts/Install-SguEnrollmentGuard.ps1 @@ -25,6 +25,9 @@ param( ) $ErrorActionPreference = 'Stop' +if ((Get-ItemProperty 'HKLM:\SOFTWARE\Policies\LaSalle\ClientMaintenance' -Name ProviderManagedByGpo -ErrorAction SilentlyContinue).ProviderManagedByGpo -eq 1) { + return +} $taskName = 'SGU-CredentialProvider-EnrollmentGuard' $enrollmentRoot = Join-Path $env:ProgramData 'SGU\Enrollment' $sourceScripts = @( diff --git a/scripts/Invoke-SguCedClientEnrollment.ps1 b/scripts/Invoke-SguCedClientEnrollment.ps1 index 401d119..ca5df6c 100644 --- a/scripts/Invoke-SguCedClientEnrollment.ps1 +++ b/scripts/Invoke-SguCedClientEnrollment.ps1 @@ -1,45 +1,17 @@ [CmdletBinding()] param([switch]$InstallTask) -$ErrorActionPreference = 'Stop' -$directory = 'C:\ProgramData\LCI-Admin\CED-Client' -if ($InstallTask) { - New-Item $directory -ItemType Directory -Force | Out-Null - $acl = [Security.AccessControl.DirectorySecurity]::new() - $acl.SetAccessRuleProtection($true,$false) - foreach ($sid in 'S-1-5-18','S-1-5-32-544') { - $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new( - [Security.Principal.SecurityIdentifier]::new($sid),'FullControl','ContainerInherit,ObjectInherit','None','Allow')) - } - Set-Acl $directory $acl - $localScript = Join-Path $directory 'Invoke-SguCedClientEnrollment.ps1' - if ($PSCommandPath -ine $localScript) { Copy-Item $PSCommandPath $localScript -Force } - $action = New-ScheduledTaskAction -Execute powershell.exe -Argument ('-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "{0}"' -f $localScript) - $triggers = @((New-ScheduledTaskTrigger -AtStartup),(New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 30))) - $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 5) - Register-ScheduledTask 'CED Configuration Manager policy enrollment' -Action $action -Trigger $triggers -Settings $settings -User SYSTEM -RunLevel Highest -Force | Out-Null - Start-ScheduledTask 'CED Configuration Manager policy enrollment' +$ErrorActionPreference='Stop' +# Compatibility entry point for cached WLAN startup registrations. +# The global SYSTEMCENTER GPO owns installation, repair and version selection. +$canonical=Get-ScheduledTask -TaskName 'LCI-ConfigMgr2509-ClientRegistration' -ErrorAction SilentlyContinue +if(-not $canonical -or -not $canonical.Settings.Enabled -or $canonical.Actions.Arguments -notmatch 'SYSTEMCENTER\.lci\.lasalle\.mx.+Ensure-CMCurrentClient\.ps1'){ + Write-Warning 'Apply the global Configuration Manager policy with gpupdate /target:computer /force. The retired CED installer task is not recreated.' return } -if (Get-Service CcmExec -ErrorAction SilentlyContinue) { return } -if (Get-Process ccmsetup -ErrorAction SilentlyContinue) { return } -# Check the machine's current OU with its own domain identity. An offline DC -# defers enrollment; an existing Wi-Fi connection continues using its cached PSK. -$root = [ADSI]'LDAP://RootDSE' -$search = [DirectoryServices.DirectorySearcher]::new([ADSI]("LDAP://"+[string]$root.defaultNamingContext)) -try { - $search.Filter = '(&(objectClass=computer)(sAMAccountName='+$env:COMPUTERNAME+'$))' - [void]$search.PropertiesToLoad.Add('distinguishedName') - $result = $search.FindOne() - $dn = [string]$result.Properties['distinguishedname'][0] - $ou = 'OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx' - if (-not $dn.EndsWith(','+$ou,[StringComparison]::OrdinalIgnoreCase)) { return } -} finally { $search.Dispose() } -$source = '\\sgu-dc02.lci.lasalle.mx\CEDClient$' -$bootstrap = Join-Path $source 'ccmsetup.exe' -$signature = Get-AuthenticodeSignature $bootstrap -if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notlike '*Microsoft Corporation*') { - throw 'Client bootstrapper is not a valid Microsoft-signed binary.' +foreach($name in 'CED Configuration Manager enrollment','CED Configuration Manager policy enrollment'){ + $old=Get-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue + if($old -and $old.Settings.Enabled -and $old.State -ne 'Running'){Disable-ScheduledTask -InputObject $old|Out-Null} +} +if($InstallTask -and -not(Get-Service CcmExec -ErrorAction SilentlyContinue)){ + Start-ScheduledTask -InputObject $canonical } -Copy-Item $bootstrap (Join-Path $directory 'ccmsetup.exe') -Force -& (Join-Path $directory 'ccmsetup.exe') /service /source:$source SMSSITECODE=LCI SMSMP=sgu-dc02.lci.lasalle.mx -# ccmsetup/service runs asynchronously. Its own log and CcmExec verify completion. diff --git a/scripts/Invoke-SguCedPreparation.ps1 b/scripts/Invoke-SguCedPreparation.ps1 index 987d4a8..0bd7729 100644 --- a/scripts/Invoke-SguCedPreparation.ps1 +++ b/scripts/Invoke-SguCedPreparation.ps1 @@ -4,8 +4,8 @@ param( [Parameter(Mandatory)][PSCredential]$Credential, [string]$TargetOuDn = 'OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx', [string]$DomainController = $env:COMPUTERNAME, - [string]$DnsServer = '192.168.54.211', - [string]$FallbackDnsServer = '192.168.54.1', + [string]$DnsServer = '', + [string]$FallbackDnsServer = '', [switch]$InstallClient, [switch]$MigrateWifi, [switch]$RestartPendingInstall, @@ -17,13 +17,9 @@ $domain = Get-ADDomain -Server $DomainController Get-ADOrganizationalUnit -Identity $TargetOuDn -Server $DomainController | Out-Null $allowed = @(Get-ADComputer -SearchBase $TargetOuDn -Filter 'Enabled -eq $true' -Server $DomainController) $inventory = Get-Content -LiteralPath $InventoryPath -Raw | ConvertFrom-Json -$source = 'C:\Program Files\Microsoft Configuration Manager\Client\ccmsetup.exe' -if ($InstallClient) { - $signature = Get-AuthenticodeSignature -LiteralPath $source - if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notlike '*Microsoft Corporation*') { - throw 'The Configuration Manager installer is not a valid Microsoft signed binary.' - } -} +$networkConfiguration=[IO.File]::ReadAllText((Join-Path $PSScriptRoot 'ced-network.json'))|ConvertFrom-Json +if(-not $DnsServer){$DnsServer=[string]$networkConfiguration.DnsServers[0]} +if(-not $FallbackDnsServer){$FallbackDnsServer=[string]$networkConfiguration.DnsServers[1]} $options = New-PSSessionOption -OpenTimeout 10000 -OperationTimeout 180000 foreach ($item in $inventory) { if ($item.WinRM -eq $false) { continue } @@ -67,23 +63,14 @@ foreach ($item in $inventory) { } if (-not $state.WifiPolicyPresent) { throw 'Native CED Wi-Fi policy was not applied.' } if ($InstallClient -and -not $state.ClientPresent) { - Copy-Item -LiteralPath $source -Destination C:\ProgramData\LCI-Admin\ccmsetup.exe -ToSession $session - Invoke-Command -Session $session -ArgumentList $ClientSource,[bool]$RestartPendingInstall { - param($clientSource,$restartPending) - if (-not $restartPending -and (Get-Process ccmsetup -ErrorAction SilentlyContinue)) { return } - # Replace a pending installer that was waiting for an inaccessible source. - if (Get-Service ccmsetup -ErrorAction SilentlyContinue) { - Stop-Service ccmsetup -Force -ErrorAction SilentlyContinue - } - # /source alone forces the complete SMB media. Combining it with - # /mp gives MP/DP discovery priority and can leave setup waiting. - $action = New-ScheduledTaskAction -Execute C:\ProgramData\LCI-Admin\ccmsetup.exe -Argument ('/source:"{0}" SMSSITECODE=LCI SMSMP=sgu-dc02.lci.lasalle.mx' -f $clientSource) - Register-ScheduledTask -TaskName 'CED Configuration Manager enrollment' -Action $action -User SYSTEM -RunLevel Highest -Force | Out-Null - Start-ScheduledTask -TaskName 'CED Configuration Manager enrollment' + Invoke-Command -Session $session { + $task=Get-ScheduledTask -TaskName 'LCI-ConfigMgr2509-ClientRegistration' -ErrorAction SilentlyContinue + if(-not $task -or -not $task.Settings.Enabled){throw 'Apply the global SYSTEMCENTER Configuration Manager GPO before requesting client installation.'} + Start-ScheduledTask -InputObject $task } } if ($MigrateWifi) { - foreach ($file in 'Connect-SguCedWifi.ps1','Install-SguCedWifiMaintenance.ps1') { + foreach ($file in 'Install-SguCedWifiMaintenance.ps1','Repair-SguCedWifi.ps1','Set-SguCedClientNetwork.ps1','ced-network.json') { Copy-Item (Join-Path $PSScriptRoot $file) (Join-Path C:\ProgramData\LCI-Admin $file) -ToSession $session -Force } Invoke-Command -Session $session { diff --git a/scripts/Invoke-SguWorkstationConsolidation.ps1 b/scripts/Invoke-SguWorkstationConsolidation.ps1 new file mode 100644 index 0000000..b624024 --- /dev/null +++ b/scripts/Invoke-SguWorkstationConsolidation.ps1 @@ -0,0 +1,57 @@ +# Called by the existing provider-update GPO, after its verified installer. +[CmdletBinding()] +param() +$ErrorActionPreference = 'Stop' +$computer = Get-CimInstance Win32_ComputerSystem +if (-not $computer.PartOfDomain -or $computer.DomainRole -ne 1) { return } +$id = '{D789CFD8-5AD4-489F-9B83-7EB5D9D09335}' +$provider = Get-Item "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers\$id" -ErrorAction SilentlyContinue +$com = Get-Item "HKLM:\SOFTWARE\Classes\CLSID\$id\InprocServer32" -ErrorAction SilentlyContinue +$default = (Get-ItemProperty 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\System' -Name DefaultCredentialProvider -ErrorAction SilentlyContinue).DefaultCredentialProvider +$services = @(Get-Service WinRM,TermService -ErrorAction SilentlyContinue) +$ready = $provider -and $provider.GetValue('') -eq 'Acceso Institucional' -and $com -and $com.GetValue('') -and + (Test-Path -LiteralPath $com.GetValue('')) -and $default -eq $id -and + (Test-Path "$env:ProgramData\SGU\CredentialProvider\settings.json") -and + $services.Count -eq 2 -and @($services | Where-Object Status -ne Running).Count -eq 0 +$root = Join-Path $env:ProgramData 'LCI-Admin\PolicyConsolidation' +$changed = [Collections.Generic.List[string]]::new() +function Disable-OwnedTask([string]$Name) { + $task = Get-ScheduledTask -TaskPath '\' -TaskName $Name -ErrorAction SilentlyContinue + if (-not $task -or -not $task.Settings.Enabled) { return } + # Preserve XML and installed files. Never interrupt an installation in flight. + if ($task.State -eq 'Running') { Write-Warning "Retirement deferred while $Name runs."; return } + if (-not (Test-Path -LiteralPath $root)) { New-Item $root -ItemType Directory -Force | Out-Null } + $backup = Join-Path $root ($Name+'.before.xml') + if (-not (Test-Path -LiteralPath $backup)) { Export-ScheduledTask -InputObject $task | Set-Content -LiteralPath $backup -Encoding Unicode } + Disable-ScheduledTask -InputObject $task | Out-Null + $changed.Add($Name) +} +if ($ready) { + # Preserve the enrollment guard until its other features are present. + $enrollmentPath = Join-Path $env:ProgramData 'SGU\Enrollment\enrollment.json' + $rustDeskReady = $true + if (Test-Path -LiteralPath $enrollmentPath) { + $enrollment = [IO.File]::ReadAllText($enrollmentPath) | ConvertFrom-Json + if ($enrollment.RustDeskServerAddress) { $rustDeskReady = (Get-Service RustDesk -ErrorAction SilentlyContinue).Status -eq 'Running' } + } + $forwardingReady = Test-Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager' + if ($rustDeskReady -and $forwardingReady) { + Disable-OwnedTask 'SGU-CredentialProvider-EnrollmentGuard' + $guard = Get-ScheduledTask -TaskName 'SGU-CredentialProvider-EnrollmentGuard' -ErrorAction SilentlyContinue + if (-not $guard -or -not $guard.Settings.Enabled) { + $key = 'HKLM:\SOFTWARE\Policies\LaSalle\ClientMaintenance' + if (-not (Test-Path $key)) { New-Item $key -Force | Out-Null } + if ((Get-ItemProperty $key -Name ProviderManagedByGpo -ErrorAction SilentlyContinue).ProviderManagedByGpo -ne 1) { + New-ItemProperty $key -Name ProviderManagedByGpo -Value 1 -PropertyType DWord -Force | Out-Null + } + } + } +} +# The global SYSTEMCENTER GPO owns installation/repair from now on. +$canonical = Get-ScheduledTask -TaskName 'LCI-ConfigMgr2509-ClientRegistration' -ErrorAction SilentlyContinue +if ($canonical -and $canonical.Settings.Enabled -and $canonical.Actions.Arguments -match 'SYSTEMCENTER\.lci\.lasalle\.mx.+Ensure-CMCurrentClient\.ps1') { + Disable-OwnedTask 'CED Configuration Manager enrollment' + Disable-OwnedTask 'CED Configuration Manager policy enrollment' +} +if ((Get-Service HealthService -ErrorAction SilentlyContinue).Status -eq 'Running') { Disable-OwnedTask 'LCI-SCOM-AgentInstallNow' } +[pscustomobject]@{Computer=$env:COMPUTERNAME;ProviderReady=[bool]$ready;Disabled=@($changed.ToArray())} diff --git a/scripts/Merge-SguClientPolicies.ps1 b/scripts/Merge-SguClientPolicies.ps1 new file mode 100644 index 0000000..c28a743 --- /dev/null +++ b/scripts/Merge-SguClientPolicies.ps1 @@ -0,0 +1,135 @@ +#Requires -Version 5.1 +[CmdletBinding(SupportsShouldProcess)] +param([string]$DomainController = 'SGU-DC01.lci.lasalle.mx') +$ErrorActionPreference = 'Stop' +if ($env:COMPUTERNAME -ine $DomainController.Split('.')[0]) { throw 'Run on the specified primary DC so AD and SYSVOL are updated together.' } +Import-Module ActiveDirectory +Import-Module GroupPolicy +$domain = Get-ADDomain -Server $DomainController +$dn = $domain.DistinguishedName +$changes = [Collections.Generic.List[string]]::new() +$modified = @{} +$ids = @{ + Wifi='0f62e905-dacb-4721-9f02-2e21423bb82e' + Provider='3b13538e-f7bf-4c26-9dd1-bf261a3378ae' + Remote='dddd0dcb-95f2-420a-bfbb-2e179c414ae4' + Experience='6332a4e0-2b6d-4b4c-8d88-0a758ba17fb3' + ConfigMgr='d882e45d-5e11-4460-98a3-d9ddc6d04bf3' + Scom='3437c619-254f-4afe-bbd5-5cbe23116c5d' +} +$roots = @{} +foreach ($key in $ids.Keys) { + Get-GPO -Guid $ids[$key] -Domain $domain.DNSRoot -Server $DomainController | Out-Null + $roots[$key] = Join-Path $env:WINDIR ("SYSVOL\domain\Policies\{"+$ids[$key]+'}') +} +function Set-PolicyText([string]$Owner,[string]$Relative,[string]$Text,[Text.Encoding]$Encoding=[Text.UTF8Encoding]::new($false)) { + $path = Join-Path $roots[$Owner] $Relative + if ((Test-Path -LiteralPath $path) -and [IO.File]::ReadAllText($path) -ceq $Text) { return } + if ($PSCmdlet.ShouldProcess($path,'Update consolidated policy file')) { + [IO.Directory]::CreateDirectory((Split-Path $path)) | Out-Null + [IO.File]::WriteAllText($path,$Text,$Encoding) + $modified[$Owner]=$true + $changes.Add("$Owner : $Relative") + } +} +foreach ($file in 'Install-SguCedWifiMaintenance.ps1','Repair-SguCedWifi.ps1','Set-SguCedClientNetwork.ps1','ced-network.json','Invoke-SguCedClientEnrollment.ps1') { + Set-PolicyText Wifi ('Machine\Scripts\Startup\'+$file) ([IO.File]::ReadAllText((Join-Path $PSScriptRoot $file))) +} +$wifiScript = "\\$($domain.DNSRoot)\SYSVOL\$($domain.DNSRoot)\Policies\{$($ids.Wifi)}\Machine\Scripts\Startup\Install-SguCedWifiMaintenance.ps1" +Set-PolicyText Wifi 'Machine\Scripts\scripts.ini' ("[Startup]`r`n0CmdLine=powershell.exe`r`n0Parameters=-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$wifiScript`"`r`n") ([Text.Encoding]::Unicode) + +# Keep the administrators helper and all UI/branding values in this GPO; +# remote-access configuration belongs exclusively to the domain-wide GPO. +$experienceIni = [IO.File]::ReadAllText((Join-Path $roots.Experience 'Machine\Scripts\scripts.ini')) +$startupSection = [regex]::Match($experienceIni,'(?ms)^\[Startup\]\r?\n(?.*?)(?=^\[|\z)') +if (-not $startupSection.Success) { throw 'Missing workstation-experience Startup section.' } +$entries = @([regex]::Matches($startupSection.Groups['Body'].Value,'(?m)^(\d+)CmdLine=(.*)\r?\n\1Parameters=(.*)\r?$')) +if (-not $entries.Count) { throw 'Unexpected workstation-experience startup registration.' } +$ini = "[Startup]`r`n"; $index=0 +foreach ($entry in $entries) { + if ($entry.Groups[3].Value -match 'Enable-SguWorkstationRemoteAccess\.ps1') { continue } + $ini += "$($index)CmdLine=$($entry.Groups[2].Value.TrimEnd())`r`n$($index)Parameters=$($entry.Groups[3].Value.TrimEnd())`r`n" + $index++ +} +$experienceUpdated = $experienceIni.Remove($startupSection.Index,$startupSection.Length).Insert($startupSection.Index,$ini) +Set-PolicyText Experience 'Machine\Scripts\scripts.ini' $experienceUpdated ([Text.Encoding]::Unicode) +$remoteIni = [IO.File]::ReadAllText((Join-Path $roots.Remote 'Machine\Scripts\scripts.ini')) +$remoteIni = $remoteIni -replace ' -LocalDnsServer [^\s]+','' -replace ' -FallbackDnsServer [^\s]+','' +Set-PolicyText Remote 'Machine\Scripts\scripts.ini' $remoteIni ([Text.Encoding]::Unicode) +Set-PolicyText Remote 'Machine\Scripts\Startup\Enable-SguWorkstationRemoteAccess.ps1' ([IO.File]::ReadAllText((Join-Path $PSScriptRoot 'Enable-SguWorkstationRemoteAccess.ps1'))) + +$providerIni = [IO.File]::ReadAllText((Join-Path $roots.Provider 'Machine\Scripts\scripts.ini')) +$match = [regex]::Match($providerIni,'Update-SguCredentialProvider-[0-9.]+\.ps1') +if (-not $match.Success) { throw 'Expected one existing verified provider updater.' } +$providerRelative = 'Machine\Scripts\Startup\'+$match.Value +$updater = [IO.File]::ReadAllText((Join-Path $roots.Provider $providerRelative)) +$retirement = '& (Join-Path $PSScriptRoot ''Invoke-SguWorkstationConsolidation.ps1'') | Out-Null' +if ($updater -notmatch 'Invoke-SguWorkstationConsolidation') { + # Reuse the already pinned package/hash, certificates and version. A marker + # alone must not hide a missing COM binary or an obsolete display name. + $old = 'if (Test-Path -LiteralPath $markerPath -PathType Leaf) {' + $new = @' +$providerId = '{D789CFD8-5AD4-489F-9B83-7EB5D9D09335}' +$registered = Get-Item "HKLM:\SOFTWARE\Classes\CLSID\$providerId\InprocServer32" -ErrorAction SilentlyContinue +$display = Get-Item "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers\$providerId" -ErrorAction SilentlyContinue +$providerHealthy = $registered -and (Test-Path -LiteralPath $registered.GetValue('')) -and $display -and $display.GetValue('') -eq 'Acceso Institucional' +if ((Test-Path -LiteralPath $markerPath -PathType Leaf) -and $providerHealthy) { + & (Join-Path $PSScriptRoot 'Invoke-SguWorkstationConsolidation.ps1') | Out-Null +'@ + if (-not $updater.Contains($old)) { throw 'Provider updater layout changed; inspect before merging.' } + $updater = $updater.Replace($old,$new)+"`r`n$retirement`r`n" +} +Set-PolicyText Provider $providerRelative $updater +Set-PolicyText Provider 'Machine\Scripts\Startup\Invoke-SguWorkstationConsolidation.ps1' ([IO.File]::ReadAllText((Join-Path $PSScriptRoot 'Invoke-SguWorkstationConsolidation.ps1'))) + +foreach ($owner in 'ConfigMgr','Scom') { + $relative = 'Machine\Preferences\ScheduledTasks\ScheduledTasks.xml' + [xml]$xml = [IO.File]::ReadAllText((Join-Path $roots[$owner] $relative)) + $task = $xml.SelectSingleNode('//*[local-name()="Task"]') + $triggers = $task.SelectSingleNode('*[local-name()="Triggers"]') + if (-not $triggers -or $task.SelectSingleNode('.//*[local-name()="Arguments"]').InnerText -notmatch 'SYSTEMCENTER\.lci\.lasalle\.mx') { throw 'Unexpected agent deployment policy.' } + foreach ($time in @($triggers.SelectNodes('*[local-name()="TimeTrigger"]'))) { [void]$triggers.RemoveChild($time) } + if (-not $triggers.SelectSingleNode('*[local-name()="EventTrigger"]')) { + $event = $xml.CreateElement('EventTrigger',$task.NamespaceURI) + $enabled=$xml.CreateElement('Enabled',$task.NamespaceURI);$enabled.InnerText='true';[void]$event.AppendChild($enabled) + $subscription=$xml.CreateElement('Subscription',$task.NamespaceURI) + $subscription.InnerText='' + [void]$event.AppendChild($subscription) + $delay=$xml.CreateElement('Delay',$task.NamespaceURI);$delay.InnerText='PT1M';[void]$event.AppendChild($delay) + [void]$triggers.AppendChild($event) + } + $settings=$task.SelectSingleNode('*[local-name()="Settings"]') + if (-not $settings.SelectSingleNode('*[local-name()="RestartOnFailure"]')) { + $restart=$xml.CreateElement('RestartOnFailure',$task.NamespaceURI) + foreach ($pair in @(@('Interval','PT5M'),@('Count','2'))) {$child=$xml.CreateElement($pair[0],$task.NamespaceURI);$child.InnerText=$pair[1];[void]$restart.AppendChild($child)} + [void]$settings.AppendChild($restart) + } + # Ask Windows to validate the actual task schema before writing the GPP. + # TASK_VALIDATE_ONLY (1) never registers or launches a task. + $scheduler=New-Object -ComObject Schedule.Service + $scheduler.Connect() + [void]$scheduler.GetFolder('\').RegisterTask('LCI-Consolidation-SchemaValidation',$task.OuterXml,1,'SYSTEM',$null,5,$null) + Set-PolicyText $owner $relative $xml.OuterXml +} + +foreach ($owner in @($modified.Keys)) { + $gpoDn="CN={$($ids[$owner])},CN=Policies,CN=System,$dn" + $ad=Get-ADObject $gpoDn -Server $DomainController -Properties versionNumber + $gpt=Join-Path $roots[$owner] 'GPT.INI' + $text=[IO.File]::ReadAllText($gpt) + $gptVersion=[long]([regex]::Match($text,'(?m)^Version=(\d+)\r?$').Groups[1].Value) + $base=[Math]::Max([long]$ad.versionNumber,$gptVersion) + $version=($base -band 0xFFFF0000L) -bor (($base+1) -band 0xFFFFL) + [IO.File]::WriteAllText($gpt,([regex]::Replace($text,'(?m)^Version=\d+\r?$',"Version=$version")),[Text.Encoding]::ASCII) + Set-ADObject $gpoDn -Server $DomainController -Replace @{versionNumber=[int]$version} +} +if ($PSCmdlet.ShouldProcess('CED - DNS de dominio','Align domain NRPT with the shared CED network configuration')) { + & (Join-Path $PSScriptRoot 'Set-SguCedDnsPolicy.ps1') -DomainController $DomainController | Out-Null +} +$configurationKey='HKLM\Software\Policies\LaSalle\CEDWifi' +$currentConfiguration=Get-GPRegistryValue -Guid $ids.Wifi -Domain $domain.DNSRoot -Server $DomainController -Key $configurationKey -ValueName ConfigurationVersion -ErrorAction SilentlyContinue +if ((-not $currentConfiguration -or $currentConfiguration.Value -ne 4) -and $PSCmdlet.ShouldProcess('CED - Wi-Fi de salas','Set configuration version 4')) { + Set-GPRegistryValue -Guid $ids.Wifi -Domain $domain.DNSRoot -Server $DomainController -Key $configurationKey -ValueName ConfigurationVersion -Type DWord -Value 4 | Out-Null + $changes.Add('Wifi : ConfigurationVersion=4') +} +[pscustomobject]@{Changed=($changes.Count -gt 0);Files=@($changes.ToArray());Gpos=@($modified.Keys);PrimaryController=$DomainController} diff --git a/scripts/New-SguBootstrapPackages.ps1 b/scripts/New-SguBootstrapPackages.ps1 index 560e933..9892094 100644 --- a/scripts/New-SguBootstrapPackages.ps1 +++ b/scripts/New-SguBootstrapPackages.ps1 @@ -209,6 +209,11 @@ Copy-RequiredFile -Source (Join-Path $PSScriptRoot 'Start-SguAzureServerBootstra -Destination (Join-Path $serverRoot 'Start-SguAzureServerBootstrap.cmd') $serverScripts = @( 'Set-SguCedWifiPolicy.ps1', + 'Set-SguCedClientNetwork.ps1', + 'ced-network.json', + 'Set-SguCedDnsPolicy.ps1', + 'Invoke-SguWorkstationConsolidation.ps1', + 'Merge-SguClientPolicies.ps1', 'Install-SguCedWifiMaintenance.ps1', 'Repair-SguCedWifi.ps1', 'Sync-SguCedWifiReaders.ps1', @@ -275,7 +280,7 @@ foreach ($fontName in $welcomeFontNames) { Copy-RequiredFile -Source (Join-Path $repositoryRoot "assets\branding\fonts\$fontName") ` -Destination (Join-Path $serverContentTarget "welcome-wallpaper\fonts\$fontName") } -foreach ($documentation in @('user-roaming.md', 'laboratorio-wallpaper-policy.md')) { +foreach ($documentation in @('user-roaming.md', 'laboratorio-wallpaper-policy.md','policy-consolidation.md')) { Copy-RequiredFile -Source (Join-Path $repositoryRoot "docs\$documentation") ` -Destination (Join-Path $serverRoot "docs\$documentation") } @@ -308,7 +313,13 @@ Compress-Archive -Path (Join-Path $azureRoot '*') -DestinationPath $azureZip ` # Existing domains can publish the WLAN correction without running forest setup. foreach ($scriptName in @( + 'Enable-SguWorkstationRemoteAccess.ps1', 'Set-SguCedWifiPolicy.ps1', + 'Set-SguCedClientNetwork.ps1', + 'ced-network.json', + 'Set-SguCedDnsPolicy.ps1', + 'Invoke-SguWorkstationConsolidation.ps1', + 'Merge-SguClientPolicies.ps1', 'Install-SguCedWifiMaintenance.ps1', 'Repair-SguCedWifi.ps1', 'Sync-SguCedWifiReaders.ps1', @@ -321,6 +332,8 @@ Copy-RequiredFile -Source (Join-Path $repositoryRoot 'docs\ced-wifi-release.md') -Destination (Join-Path $wifiRoot 'README.md') Copy-RequiredFile -Source (Join-Path $repositoryRoot 'docs\ced-network-operations.md') ` -Destination (Join-Path $wifiRoot 'ced-network-operations.md') +Copy-RequiredFile -Source (Join-Path $repositoryRoot 'docs\policy-consolidation.md') ` + -Destination (Join-Path $wifiRoot 'policy-consolidation.md') Write-PackageManifest -PackageRoot $wifiRoot -PackageVersion $Version -PackageKind CedWifiPolicy Compress-Archive -Path (Join-Path $wifiRoot '*') -DestinationPath $wifiZip ` -CompressionLevel Optimal diff --git a/scripts/Repair-SguCedWifi.ps1 b/scripts/Repair-SguCedWifi.ps1 index 42e5f48..54a7453 100644 --- a/scripts/Repair-SguCedWifi.ps1 +++ b/scripts/Repair-SguCedWifi.ps1 @@ -88,20 +88,7 @@ if($requested){ $rolledBack=$true } }else{$state=$before} -foreach($r in $state){ - $adapter=Get-NetAdapter|Where-Object{[guid]$_.InterfaceGuid -eq [guid]$r.Interface} - if(-not $adapter -or -not $r.Ssid){continue} - if($r.Ssid -eq 'Centro de Experiencia Digital'){ - $desired=@('192.168.54.211','192.168.54.1') - $actual=@((Get-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4).ServerAddresses) - if(($actual -join ',') -ne ($desired -join ',')){Set-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -ServerAddresses $desired} - }else{ - # Emergency Wi-Fi must obtain its own DNS; the internal domain NRPT stays intact. - $localKey='HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\'+([guid]$adapter.InterfaceGuid).ToString('B') - $manual=(Get-ItemProperty -LiteralPath $localKey -Name NameServer -ErrorAction SilentlyContinue).NameServer - if($manual){Set-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -ResetServerAddresses} - } -} +$network=& (Join-Path $PSScriptRoot 'Set-SguCedClientNetwork.ps1') -ConnectedInterface @($state.Interface) -ConnectedSsid @($state.Ssid) if($requested -and -not $rolledBack){Register-DnsClient -ErrorAction SilentlyContinue} $result=[pscustomobject]@{Utc=[DateTime]::UtcNow.ToString('o');Computer=[string]$env:COMPUTERNAME;Identity=[string][Security.Principal.WindowsIdentity]::GetCurrent().Name;UserSessions=[Sgu.CedMachineWifi]::UserSessions();MachineProfileReady=(@($state|Where-Object MachineProfileReady).Count -gt 0);ConnectedToCed=($state.Ssid -contains 'Centro de Experiencia Digital');RolledBack=$rolledBack;Interfaces=@($state|Select-Object Interface,Ssid,Profile,MachineProfileReady,GroupProfileRepaired,MachineProfileCreated,OtherProfilesMadeManual,ConnectionRequested,QueryError);PeriodicPolling=$false} if(Test-Path -LiteralPath $destination){$result|ConvertTo-Json -Depth 5|Set-Content -LiteralPath(Join-Path $destination 'machine-wifi-status.json') -Encoding UTF8} diff --git a/scripts/Repair-SguClientEnrollment.ps1 b/scripts/Repair-SguClientEnrollment.ps1 index 672e8bd..125b283 100644 --- a/scripts/Repair-SguClientEnrollment.ps1 +++ b/scripts/Repair-SguClientEnrollment.ps1 @@ -4,6 +4,12 @@ param( ) $ErrorActionPreference = 'Stop' +# Domain GPO owns repair once the migration has completed. Keep this check in +# the old entry point too, so a cached bootstrap cannot undo a newer package. +$consolidationKey = 'HKLM:\SOFTWARE\Policies\LaSalle\ClientMaintenance' +if ((Get-ItemProperty $consolidationKey -Name ProviderManagedByGpo -ErrorAction SilentlyContinue).ProviderManagedByGpo -eq 1) { + return +} $configuration = Get-Content -LiteralPath $ConfigurationPath -Raw | ConvertFrom-Json $enrollmentRoot = Split-Path $ConfigurationPath -Parent $testScript = Join-Path $enrollmentRoot 'Test-SguClientEnrollment.ps1' diff --git a/scripts/Set-SguCedClientNetwork.ps1 b/scripts/Set-SguCedClientNetwork.ps1 new file mode 100644 index 0000000..11ee8fe --- /dev/null +++ b/scripts/Set-SguCedClientNetwork.ps1 @@ -0,0 +1,68 @@ +[CmdletBinding()] +param( + [string]$ConfigurationPath = (Join-Path $PSScriptRoot 'ced-network.json'), + [string[]]$ConnectedInterface = @(), + [string[]]$ConnectedSsid = @() +) +$ErrorActionPreference = 'Stop' +$configuration = [IO.File]::ReadAllText($ConfigurationPath) | ConvertFrom-Json +$computer = Get-CimInstance Win32_ComputerSystem +if (-not $computer.PartOfDomain -or $computer.DomainRole -ne 1 -or + $computer.Domain -ine $configuration.Domain -or $env:COMPUTERNAME -notmatch $configuration.ComputerPattern) { return } +if ($ConnectedInterface.Count -ne $ConnectedSsid.Count) { throw 'Interface and SSID lists differ.' } +[Net.IPAddress]::Parse($configuration.PrimaryAddress) | Out-Null +foreach ($server in $configuration.DnsServers) { [Net.IPAddress]::Parse($server) | Out-Null } + +# Preserve unrelated aliases (broker/RustDesk included). Consolidate only our +# previously managed entries; an unmanaged conflicting entry requires review. +$path = Join-Path $env:WINDIR 'System32\drivers\etc\hosts' +$begin = '# LCI CED primary domain controller - begin' +$end = '# LCI CED primary domain controller - end' +$current = [IO.File]::ReadAllText($path) +$without = [regex]::Replace($current, "(?ms)^$([regex]::Escape($begin))\r?\n.*?^$([regex]::Escape($end))\r?\n?", '') +$aliases = @([string]$configuration.PrimaryController, ($configuration.PrimaryController -split '\.')[0], [string]$configuration.Domain) +$coveredAliases = @() +$lines = [Collections.Generic.List[string]]::new() +foreach ($line in ($without -split '\r?\n')) { + $parts = $line -split '#', 2 + $tokens = @($parts[0].Trim() -split '\s+' | Where-Object { $_ }) + if ($tokens.Count -gt 1 -and @($tokens[1..($tokens.Count-1)] | Where-Object { $_ -in $aliases }).Count) { + if ($line -match '# SGU managed direct enrollment\s*$') { + $remaining = @($tokens[1..($tokens.Count-1)] | Where-Object { $_ -notin $aliases }) + if ($remaining.Count) { $lines.Add($tokens[0]+' '+($remaining -join ' ')+' # SGU managed direct enrollment') } + continue + } + if ($tokens[0] -ne $configuration.PrimaryAddress) { throw 'An unmanaged hosts entry conflicts with the primary controller. No hosts changes made.' } + $coveredAliases += @($tokens[1..($tokens.Count-1)] | Where-Object { $_ -in $aliases }) + } + $lines.Add($line) +} +$prefix = ($lines -join "`r`n").TrimEnd([char[]]"`r`n") +$missingAliases = @($aliases | Where-Object { $_ -notin $coveredAliases }) +$entry = $configuration.PrimaryAddress+' '+($missingAliases -join ' ') +$updated = $(if ($prefix) { $prefix+"`r`n" } else { '' })+$(if ($missingAliases.Count) { "$begin`r`n$entry`r`n$end`r`n" } else { '' }) +$hostChanged = $updated -cne $current +if ($hostChanged) { + $backup = Join-Path $env:ProgramData 'LCI-Admin\CED-WiFi\hosts.before-consolidation' + if (-not (Test-Path -LiteralPath $backup)) { Copy-Item -LiteralPath $path -Destination $backup } + [IO.File]::WriteAllText($path, $updated, [Text.UTF8Encoding]::new($false)) + Clear-DnsClientCache +} +$dnsChanges = 0 +for ($i=0; $i -lt $ConnectedInterface.Count; $i++) { + $adapter = Get-NetAdapter | Where-Object { [guid]$_.InterfaceGuid -eq [guid]$ConnectedInterface[$i] } + if (-not $adapter -or -not $ConnectedSsid[$i]) { continue } + if ($ConnectedSsid[$i] -eq $configuration.Ssid) { + $actual = @((Get-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4).ServerAddresses) + if (($actual -join ',') -ne ($configuration.DnsServers -join ',')) { + Set-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -ServerAddresses $configuration.DnsServers + $dnsChanges++ + } + } else { + # Emergency Wi-Fi retains DHCP DNS. The domain NRPT is owned by GPO. + $key = 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\'+([guid]$adapter.InterfaceGuid).ToString('B') + $manual = (Get-ItemProperty -LiteralPath $key -Name NameServer -ErrorAction SilentlyContinue).NameServer + if ($manual) { Set-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -ResetServerAddresses; $dnsChanges++ } + } +} +[pscustomobject]@{HostsChanged=$hostChanged;DnsChanges=$dnsChanges;PrimaryController=$configuration.PrimaryController;DnsServers=@($configuration.DnsServers)} diff --git a/scripts/Set-SguCedDnsPolicy.ps1 b/scripts/Set-SguCedDnsPolicy.ps1 index 51f7dc3..1c56b6a 100644 --- a/scripts/Set-SguCedDnsPolicy.ps1 +++ b/scripts/Set-SguCedDnsPolicy.ps1 @@ -2,10 +2,14 @@ param( [string]$TargetOuDn = 'OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx', [string]$GpoName = 'CED - DNS de dominio', - [string]$DnsServer = '192.168.54.211', + [string[]]$DnsServer = @(), [string]$DomainController = $env:COMPUTERNAME ) $ErrorActionPreference = 'Stop' +if (-not $DnsServer.Count) { + $configuration = [IO.File]::ReadAllText((Join-Path $PSScriptRoot 'ced-network.json')) | ConvertFrom-Json + $DnsServer = @($configuration.DnsServers) +} Import-Module ActiveDirectory Import-Module GroupPolicy $domain = Get-ADDomain -Server $DomainController @@ -20,7 +24,7 @@ $rule = @($rules | Where-Object { $_.Namespace -contains $namespace }) if ($rule.Count -gt 1) { throw 'Duplicate domain DNS policy rules.' } if (-not $rule.Count) { Add-DnsClientNrptRule -GpoName $name -Server $DomainController -Namespace $namespace -NameServers $DnsServer -DisplayName 'CED internal domain DNS' | Out-Null -} elseif ($rule[0].NameServers -ne $DnsServer) { +} elseif ((@($rule[0].NameServers -split '[;,\s]+' | Where-Object { $_ }) -join ',') -ne ($DnsServer -join ',')) { Set-DnsClientNrptRule -GpoName $name -Server $DomainController -Name $rule[0].Name -NameServers $DnsServer } $link = (Get-GPInheritance -Target $TargetOuDn -Domain $domain.DNSRoot -Server $DomainController).GpoLinks | Where-Object GpoId -eq $gpo.Id diff --git a/scripts/Set-SguCedWifiPolicy.ps1 b/scripts/Set-SguCedWifiPolicy.ps1 index 2c78cc4..c3e9a41 100644 --- a/scripts/Set-SguCedWifiPolicy.ps1 +++ b/scripts/Set-SguCedWifiPolicy.ps1 @@ -8,7 +8,8 @@ param( [string]$ReaderGroup = 'CED-WiFi-Equipos' ) $ErrorActionPreference = 'Stop' -foreach ($file in 'Install-SguCedWifiMaintenance.ps1','Connect-SguCedWifi.ps1','Repair-SguCedWifi.ps1','Invoke-SguCedClientEnrollment.ps1') { +if($env:COMPUTERNAME -ine $DomainController.Split('.')[0]){throw 'Publish this policy on its specified domain controller to keep AD and SYSVOL consistent.'} +foreach ($file in 'Install-SguCedWifiMaintenance.ps1','Connect-SguCedWifi.ps1','Repair-SguCedWifi.ps1','Set-SguCedClientNetwork.ps1','ced-network.json') { if (-not (Test-Path (Join-Path $PSScriptRoot $file))) { throw "Deploy the complete script set; missing $file." } } Import-Module ActiveDirectory @@ -85,7 +86,9 @@ try { foreach ($rule in @($security.GetAccessRules($true,$false,[Security.Principal.SecurityIdentifier]))) { $security.RemoveAccessRuleSpecific($rule) } $forestRoot = Get-ADDomain -Identity (Get-ADForest -Server $DomainController).RootDomain -Server $DomainController $controller = Get-ADComputer -Identity ($DomainController.Split('.')[0]) -Server $DomainController - foreach ($sid in @('S-1-5-18', "$($domain.DomainSID)-512", "$($forestRoot.DomainSID)-519", $controller.SID.Value)) { + # Either replica can run the delegated Wi-Fi reader refresh. Publishing + # from DC01 must preserve DC02's maintenance access to this one object. + foreach ($sid in @('S-1-5-18', "$($domain.DomainSID)-512", "$($forestRoot.DomainSID)-519", "$($domain.DomainSID)-516", $controller.SID.Value)) { $security.AddAccessRule([DirectoryServices.ActiveDirectoryAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),[DirectoryServices.ActiveDirectoryRights]::GenericAll,[Security.AccessControl.AccessControlType]::Allow)) } $security.AddAccessRule([DirectoryServices.ActiveDirectoryAccessRule]::new($group.SID,[DirectoryServices.ActiveDirectoryRights]::GenericRead,[Security.AccessControl.AccessControlType]::Allow)) @@ -100,7 +103,7 @@ $adGpo = Get-ADObject $gpoDn -Server $DomainController -Properties versionNumber $root = Join-Path $env:WINDIR "SYSVOL\domain\Policies\{$($gpo.Id)}" $startup = Join-Path $root 'Machine\Scripts\Startup' New-Item $startup -ItemType Directory -Force | Out-Null -foreach ($file in 'Install-SguCedWifiMaintenance.ps1','Connect-SguCedWifi.ps1','Repair-SguCedWifi.ps1','Invoke-SguCedClientEnrollment.ps1') { +foreach ($file in 'Install-SguCedWifiMaintenance.ps1','Connect-SguCedWifi.ps1','Repair-SguCedWifi.ps1','Set-SguCedClientNetwork.ps1','ced-network.json') { $source = Join-Path $PSScriptRoot $file $destination = Join-Path $startup $file if (-not (Test-Path $destination) -or (Get-FileHash $source).Hash -ne (Get-FileHash $destination).Hash) { @@ -109,8 +112,7 @@ foreach ($file in 'Install-SguCedWifiMaintenance.ps1','Connect-SguCedWifi.ps1',' } } $scriptPath = "\\$($domain.DNSRoot)\SYSVOL\$($domain.DNSRoot)\Policies\{$($gpo.Id)}\Machine\Scripts\Startup\Install-SguCedWifiMaintenance.ps1" -$clientScriptPath = $scriptPath.Replace('Install-SguCedWifiMaintenance.ps1','Invoke-SguCedClientEnrollment.ps1') -$ini = "[Startup]`r`n0CmdLine=powershell.exe`r`n0Parameters=-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$scriptPath`"`r`n1CmdLine=powershell.exe`r`n1Parameters=-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$clientScriptPath`" -InstallTask`r`n" +$ini = "[Startup]`r`n0CmdLine=powershell.exe`r`n0Parameters=-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$scriptPath`"`r`n" $iniPath = Join-Path $root 'Machine\Scripts\scripts.ini' if (-not (Test-Path $iniPath) -or (Get-Content $iniPath -Raw) -cne $ini) { [IO.File]::WriteAllText($iniPath,$ini,[Text.Encoding]::Unicode) @@ -147,7 +149,7 @@ foreach($setting in @( @{Key='HKLM\Software\Policies\Microsoft\Windows\System';Name='DontDisplayNetworkSelectionUI';Value=0}, @{Key='HKLM\Software\Policies\Microsoft\Windows\WcmSvc\GroupPolicy';Name='fBlockNonDomain';Value=0}, @{Key='HKLM\SYSTEM\CurrentControlSet\Services\WlanSvc';Name='Start';Value=2}, - @{Key='HKLM\Software\Policies\LaSalle\CEDWifi';Name='ConfigurationVersion';Value=2} + @{Key='HKLM\Software\Policies\LaSalle\CEDWifi';Name='ConfigurationVersion';Value=4} )){ $old=Get-GPRegistryValue -Guid $gpo.Id -Server $DomainController -Key $setting.Key -ValueName $setting.Name -ErrorAction SilentlyContinue if(-not $old -or [string]$old.Value -ne [string]$setting.Value){Set-GPRegistryValue -Guid $gpo.Id -Server $DomainController -Key $setting.Key -ValueName $setting.Name -Type DWord -Value $setting.Value|Out-Null;$changed=$true} diff --git a/scripts/ced-network.json b/scripts/ced-network.json new file mode 100644 index 0000000..1728c5b --- /dev/null +++ b/scripts/ced-network.json @@ -0,0 +1,9 @@ +{ + "Version": 1, + "Domain": "lci.lasalle.mx", + "ComputerPattern": "^(AF|SD|SI)-", + "Ssid": "Centro de Experiencia Digital", + "PrimaryController": "SGU-DC01.lci.lasalle.mx", + "PrimaryAddress": "20.9.81.130", + "DnsServers": ["20.9.81.130", "192.168.54.211"] +} diff --git a/tests/CedNetworkConsolidation.Tests.ps1 b/tests/CedNetworkConsolidation.Tests.ps1 new file mode 100644 index 0000000..a175fca --- /dev/null +++ b/tests/CedNetworkConsolidation.Tests.ps1 @@ -0,0 +1,36 @@ +$ErrorActionPreference='Stop' +$script=Join-Path $PSScriptRoot '..\scripts\Set-SguCedClientNetwork.ps1' +$root=Join-Path ([IO.Path]::GetTempPath()) ('ced-network-test-'+[guid]::NewGuid().ToString('N')) +$priorWindows=$env:WINDIR;$priorData=$env:ProgramData;$priorName=$env:COMPUTERNAME +function Assert($Condition,$Message){if(-not $Condition){throw $Message}} +try{ + $env:WINDIR=$root;$env:ProgramData=$root;$env:COMPUTERNAME='AF-99' + New-Item (Join-Path $root 'System32\drivers\etc'),(Join-Path $root 'LCI-Admin\CED-WiFi') -ItemType Directory -Force|Out-Null + $hosts=Join-Path $root 'System32\drivers\etc\hosts' + function Get-CimInstance { [pscustomobject]@{PartOfDomain=$true;DomainRole=1;Domain='lci.lasalle.mx'} } + function Clear-DnsClientCache {} + [IO.File]::WriteAllText($hosts,"127.0.0.1 localhost`r`n20.9.81.130 sgu-dc01.lci.lasalle.mx lci.lasalle.mx sgu-auth.lci.lasalle.mx rustdesk.lci.lasalle.mx # SGU managed direct enrollment`r`n") + $first=& $script + $text=[IO.File]::ReadAllText($hosts) + Assert $first.HostsChanged 'Expected legacy entry migration.' + Assert ($text.Contains('sgu-auth.lci.lasalle.mx rustdesk.lci.lasalle.mx # SGU managed direct enrollment')) 'Broker and remote-access aliases were lost.' + Assert (([regex]::Matches($text,'(?i)sgu-dc01\.lci\.lasalle\.mx')).Count -eq 1) 'Duplicate DC host aliases.' + $second=& $script + Assert (-not $second.HostsChanged) 'Repeated application modified hosts.' + [IO.File]::WriteAllText($hosts,"192.168.1.1 SGU-DC01.lci.lasalle.mx`r`n") + $conflict=$false + try{& $script|Out-Null}catch{$conflict=$true} + Assert $conflict 'Unmanaged host conflict was silently overwritten.' + Assert ([IO.File]::ReadAllText($hosts) -eq "192.168.1.1 SGU-DC01.lci.lasalle.mx`r`n") 'Conflict changed hosts.' + $env:COMPUTERNAME='APPS-01' + & $script|Out-Null + Assert ([IO.File]::ReadAllText($hosts) -eq "192.168.1.1 SGU-DC01.lci.lasalle.mx`r`n") 'Ethernet workstation was changed.' + 'CED network tests passed: migration, preservation, idempotence, conflict and scope.' +}finally{ + $env:WINDIR=$priorWindows;$env:ProgramData=$priorData;$env:COMPUTERNAME=$priorName + # Remove only the freshly created, validated temporary test directory. + $resolved=[IO.Path]::GetFullPath($root) + if($resolved.StartsWith([IO.Path]::GetTempPath(),[StringComparison]::OrdinalIgnoreCase) -and (Split-Path $resolved -Leaf) -like 'ced-network-test-*'){ + Remove-Item -LiteralPath $resolved -Recurse -Force + } +}