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='