diff --git a/docs/ced-network-operations.md b/docs/ced-network-operations.md index 49284a8..b32a0c6 100644 --- a/docs/ced-network-operations.md +++ b/docs/ced-network-operations.md @@ -8,9 +8,10 @@ Configuration is scoped to: OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx ``` -The rollout targets AF-02 through AF-06, AF-08 through AF-11, and SD-01 through -SD-30: 39 domain computers. LCI-77 uses a local Wi-Fi profile and remains outside -the domain. Its Ethernet connection is retained. +The current Wi-Fi policy targets member workstations with names beginning +`AF-`, `SD-`, or `SI-` in this OU: 47 enabled domain computers on October 14, +2026. Its WMI filter excludes servers and `APPS-` Ethernet workstations. +LCI-77 uses a local profile and remains outside the domain. ## Router configuration @@ -37,9 +38,12 @@ repeat Apply while waiting for recovery. ## Group Policy and future computers `Set-SguCedWifiPolicy.ps1` publishes a native computer WLAN policy in -**CED - Wi-Fi de salas**. The profile remains a read-only Group Policy profile; -it is not a manually imported all-user profile. The GPO is linked only to the -CED OU and disables user settings. +**CED - Wi-Fi de salas**. The GPO is enforced on the CED OU, disables user +settings, and filters for AF, SD, and SI member workstations. The native +**Centro de Experiencia Digital** profile remains a read-only Group Policy +profile. An additional **CED - Equipo** all-user profile caches the same network +credentials in Windows' protected machine profile store. This cache is available +before any user signs in and survives sign-out. The Personal shared key is stored in the native AD WLAN policy object. Its ACL permits the CED computer reader group and direct CED computer SIDs, plus the @@ -47,34 +51,51 @@ administrative/system identities needed to maintain it. The key is not stored in SYSVOL scripts or in this repository. Exported profiles containing the key must remain in an administrator-only private directory. -On the tested Windows clients, the native CSE left the Personal key unprotected -and connection attempts failed. `Connect-SguCedWifi.ps1` uses the documented -Native Wi-Fi `WlanSetProfile` API to protect that key on the client while keeping -the Group Policy profile flag. It then connects and requires a successful WLAN -event for both the expected profile name and SSID. No location privacy setting -is changed. Successful live connections are left running. +On some Windows clients the native CSE left the Personal key unprotected; +others did not have the CED profile at all. `Repair-SguCedWifi.ps1` uses the +documented Native Wi-Fi API to repair local key protection and prepare the cached +all-user profile. Initial provisioning can read the existing restricted AD WLAN +object using the computer account; no administrator password is stored on the +client. The cached profile subsequently works without an AD connection. +The helper combines native interface state with WLAN service events when Windows +denies querying the current SSID. It does not change location privacy consent. The computer startup policy installs **CED WiFi policy connection**, a SYSTEM -task that runs at startup and every 15 minutes. The task requires the native -Group Policy profile. Its code directory permits writes only by SYSTEM and -local administrators. **CED WiFi OU readers refresh** on SGU-DC02 updates the -reader group and direct policy ACLs every 15 minutes, removing computers that -leave the OU. No domain administrator password is stored in these tasks. +task triggered by boot, computer policy completion, sign-out, and successful +Wi-Fi connection events. It replaces the previous 15-minute reconnection loop. +WLAN AutoConfig performs normal automatic connections. The repair helper exits +after reconciling the cached profile; there is no client polling interval. +Its code directory permits writes only by SYSTEM and local administrators. +**CED WiFi OU readers refresh** on SGU-DC02 still updates the reader group and +direct policy ACLs every 15 minutes, restricted to AF, SD, and SI computers. New domain computers in the OU receive policy automatically after reader refresh and normal Group Policy processing. They still need an initial path to a domain controller, such as Ethernet or an existing Wi-Fi profile, to join the domain -and receive their first policy. A cached Personal profile can reconnect without -RADIUS or a certificate authority. Domain DNS and management services still -depend on their servers being available. +and receive their first policy. Existing disconnected computers likewise need +one initial connection to fetch the correction. The cached Personal profile +does not require user credentials, RADIUS, or a certificate authority. Domain +DNS and management services still depend on their servers being available. + +CED profiles use automatic connection with automatic switching disabled. +Other saved all-user Wi-Fi profiles are retained and changed to manual +connection. The sign-in network selector stays available and the policy allows +creating an all-user emergency profile. A manually selected alternate connection +is preserved by routine repair; explicit `-PreferCedNow` requests migration and +attempts to restore the previous profile if CED does not connect. Emergency +connectivity does not itself provide a route to the domain controller. `Set-SguCedDnsPolicy.ps1` creates **CED - DNS de dominio**, linked only to the same OU. Its NRPT rule directs the internal domain namespace to 192.168.54.211. This avoids public Ethernet DNS competing with Wi-Fi domain DNS on multihomed PCs. Public namespaces retain their normal resolution settings. -The managed Wi-Fi adapter also has 192.168.54.1 as a secondary resolver for -public names if the domain DNS server is unavailable. Internal names continue +On CED, the managed Wi-Fi adapter uses 192.168.54.211 and 192.168.54.1 as its +resolvers. On a manually chosen alternate Wi-Fi, the helper restores DHCP DNS +instead of leaving CED's resolver addresses pinned. Internal names continue to use the NRPT domain rule; public fallback does not provide domain services. +The seven pre-existing SI DNS records originally created for workgroup hosts +also permit their respective domain computer accounts to update their own +records securely after a subnet change. Secure-only zone updates are preserved. ## Windows Admin Center diff --git a/docs/ced-wifi-release.md b/docs/ced-wifi-release.md new file mode 100644 index 0000000..81ce091 --- /dev/null +++ b/docs/ced-wifi-release.md @@ -0,0 +1,50 @@ +# Actualización Wi-Fi para el dominio existente + +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 +**Centro de Experiencia Digital**. Para otra infraestructura, revise estas +direcciones y los nombres en los scripts antes de publicar. + +En el laboratorio actual la actualización ya está publicada en ambos +controladores. Las estaciones desconectadas necesitan una conexión inicial al +dominio para obtenerla. Una vez conectadas, en PowerShell como administrador: + +```powershell +gpupdate.exe /target:computer /force +``` + +Si Windows solicita reiniciar para ejecutar la instalación de equipo, reinicie. +La política instala un perfil Wi-Fi de todos los usuarios, protegido por Windows, +que funciona antes del inicio de sesión y después de cerrarla. Conserva el +selector de redes para emergencias. Las otras redes guardadas se conectan +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 +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 +``` + +La publicación usa WLAN nativo de Windows y un script de inicio de equipo de +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. + +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. + +El estado sin secretos queda en +`C:\ProgramData\LCI-Admin\CED-WiFi\machine-wifi-status.json`. +Consulte `ced-network-operations.md` para alcance, DNS y recuperación. diff --git a/docs/release-0.6.22.md b/docs/release-0.6.22.md new file mode 100644 index 0000000..ff9786c --- /dev/null +++ b/docs/release-0.6.22.md @@ -0,0 +1,54 @@ +# v0.6.22 — Wi-Fi de equipo antes del inicio de sesión + +Corrige las estaciones de Centro de Experiencia Digital que perdían Wi-Fi al +cerrar sesión y no podían contactar al dominio para el primer acceso de un +usuario. + +- La GPO **CED - Wi-Fi de salas** prepara un perfil de todos los usuarios + **CED - Equipo**, con conexión automática a **Centro de Experiencia Digital**. + Windows protege la clave en su almacén de perfiles de equipo. +- Alcance: estaciones miembro `AF-*`, `SD-*` y `SI-*` bajo la OU Centro de + Experiencia Digital dentro de Laboratorio. Los servidores y `APPS-*`, que usan + Ethernet, quedan excluidos por filtro WMI y comprobación local. +- Conserva el selector de redes en el inicio de sesión. Las demás redes guardadas + se conectan manualmente para emergencias; la recuperación habitual respeta una + conexión alternativa elegida por el usuario y restaura su DNS por DHCP. +- Sustituye la reconexión periódica del cliente por recuperación ante eventos de + arranque, políticas, cierre de sesión y conexión Wi-Fi. Una configuración ya + correcta no reinstala el perfil ni vuelve a registrar la tarea. +- La provisión inicial consulta el controlador local mediante LDAP con firma y + cifrado, usando la cuenta del equipo. Evita intentar acceder a la IP privada + del controlador Azure desde estaciones sin esa ruta. +- Identifica la conexión mediante estado nativo y eventos WLAN cuando Windows + restringe la consulta del SSID, sin cambiar el consentimiento de ubicación. +- La publicación de la GPO es idempotente y mantiene la clave fuera de SYSVOL y + de los archivos del release. + +## Paquetes + +- **sgu-ced-wifi-policy-0.6.22.zip**: scripts y guía para actualizar la política + Wi-Fi de este dominio existente. No requiere ejecutar el bootstrap del bosque. +- Se mantienen los paquetes de bootstrap Windows, servidor, Linux e + infraestructura Azure. El paquete de servidor incluye también los scripts + necesarios para publicar esta corrección Wi-Fi. +- **SHA256SUMS-0.6.22.txt** permite verificar los cinco ZIP. + +La política ya está publicada en los dos controladores del laboratorio. Una +estación desconectada necesita conectividad inicial al dominio para obtenerla; +después puede ejecutar `gpupdate /target:computer /force` y reiniciar si Windows +lo solicita. El perfil de equipo queda disponible sin sesión iniciada. + +El paquete específico Wi-Fi está configurado para `lci.lasalle.mx`, el SSID CED y +el controlador local `192.168.54.211`; revise sus parámetros antes de reutilizarlo +en otra infraestructura. El bootstrap de servidor crea un bosque nuevo: para +actualizar el dominio existente use el paquete Wi-Fi y su README. + +## Validación + +- Compilación Release de Auth Broker y Credential Provider. +- 71 pruebas correctas: 42 del núcleo, 22 del broker y 7 del proveedor. +- Análisis sintáctico de los scripts y compilación del auxiliar nativo en + Windows PowerShell 5.1. +- Verificación SHA-256 de cada archivo de los manifiestos y de los cinco ZIP. +- Segunda publicación idéntica de la GPO sin cambios y archivos de política + coincidentes en SYSVOL de ambos controladores. diff --git a/scripts/Install-SguCedWifiMaintenance.ps1 b/scripts/Install-SguCedWifiMaintenance.ps1 index da21d92..ef323dd 100644 --- a/scripts/Install-SguCedWifiMaintenance.ps1 +++ b/scripts/Install-SguCedWifiMaintenance.ps1 @@ -1,32 +1,65 @@ [CmdletBinding()] param() $ErrorActionPreference = 'Stop' -# Invoked by the CED computer startup policy, after the native WLAN CSE. +# Native WLAN AutoConfig holds the machine profile before interactive logon. +$computer=Get-CimInstance Win32_ComputerSystem +if(-not $computer.PartOfDomain -or $computer.DomainRole -ne 1 -or $env:COMPUTERNAME -notmatch '^(AF|SD|SI)-'){return} $destination = 'C:\ProgramData\LCI-Admin\CED-WiFi' New-Item $destination -ItemType Directory -Force | Out-Null -$dnsBackup = 'C:\ProgramData\LCI-Admin\CED-dns-before.json' -if (-not (Test-Path $dnsBackup)) { - Get-DnsClientServerAddress -AddressFamily IPv4 | Select-Object InterfaceAlias,InterfaceIndex,ServerAddresses | - ConvertTo-Json -Depth 3 | Set-Content -LiteralPath $dnsBackup -} -# Keep public DNS available through the router if the domain DNS server is -# offline. The separate CED NRPT GPO still pins internal names to domain DNS. -$wifi = @(Get-NetAdapter | Where-Object { $_.NdisPhysicalMedium -eq 9 -and $_.Status -eq 'Up' }) -foreach ($adapter in $wifi) { - Set-DnsClientServerAddress -InterfaceIndex $adapter.InterfaceIndex -ServerAddresses '192.168.54.211','192.168.54.1' -} $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 -LiteralPath $destination -AclObject $acl -Copy-Item (Join-Path $PSScriptRoot 'Connect-SguCedWifi.ps1') $destination -Force -$helper = Join-Path $destination 'Connect-SguCedWifi.ps1' -$arguments = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "{0}" -RequireGroupPolicy -TimeoutMinutes 2 -StatusPath "{1}"' -f $helper,(Join-Path $destination 'status.json') -$action = New-ScheduledTaskAction -Execute "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument $arguments -$triggers = @((New-ScheduledTaskTrigger -AtStartup),(New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 15))) -$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 5) -Register-ScheduledTask -TaskName 'CED WiFi policy connection' -Action $action -Trigger $triggers -Settings $settings -User SYSTEM -RunLevel Highest -Force | Out-Null -Start-ScheduledTask 'CED WiFi policy connection' +if((Get-Acl -LiteralPath $destination).GetSecurityDescriptorSddlForm([Security.AccessControl.AccessControlSections]::Access) -ne $acl.GetSecurityDescriptorSddlForm([Security.AccessControl.AccessControlSections]::Access)){Set-Acl -LiteralPath $destination -AclObject $acl} +$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} +$service=Get-Service WlanSvc +if($service.StartType -ne 'Automatic'){Set-Service WlanSvc -StartupType Automatic} +if($service.Status -ne 'Running'){Start-Service WlanSvc} +$subscription='' +$subscription=[Security.SecurityElement]::Escape($subscription) +$command=[Security.SecurityElement]::Escape("$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe") +$arguments=[Security.SecurityElement]::Escape('-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "'+$helper+'"') +$taskXml=@" + + + La SalleComputer Wi-Fi recovery after boot, computer policy, logoff or network change. No periodic polling. + truePT10Strue$subscriptionPT3S + S-1-5-18HighestAvailable + IgnoreNewfalsefalsetruefalsetruePT1M + $command$arguments + +"@ +$taskName='CED WiFi policy connection' +$existing=Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue +$versionFile=Join-Path $destination 'maintenance-v2.sha256' +$sha=[Security.Cryptography.SHA256]::Create() +try{$hash=[BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($taskXml))).Replace('-','')}finally{$sha.Dispose()} +$valid=$existing -and $existing.Triggers.Count -eq 2 -and @($existing.Triggers|Where-Object{$_.Repetition.Interval}).Count -eq 0 -and $existing.Principal.UserId -in 'SYSTEM','S-1-5-18' -and (Test-Path -LiteralPath $versionFile) -and (Get-Content -LiteralPath $versionFile -Raw).Trim() -eq $hash +if(-not $valid){Register-ScheduledTask -TaskName $taskName -Xml $taskXml -Force|Out-Null;$hash|Set-Content -LiteralPath $versionFile -Encoding ASCII} +$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 + 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. + $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 + $searcher=[DirectoryServices.DirectorySearcher]::new($searchRoot) + $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()) + 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} +} +if(-not $profileState.MachineProfileReady){throw 'Machine Wi-Fi profile is not ready.'} +Start-ScheduledTask -TaskName $taskName diff --git a/scripts/New-SguBootstrapPackages.ps1 b/scripts/New-SguBootstrapPackages.ps1 index 7b79fa0..560e933 100644 --- a/scripts/New-SguBootstrapPackages.ps1 +++ b/scripts/New-SguBootstrapPackages.ps1 @@ -91,20 +91,22 @@ $clientRoot = Join-Path $resolvedOutputRoot "sgu-windows-client-bootstrap-$Versi $serverRoot = Join-Path $resolvedOutputRoot "sgu-server-bootstrap-$Version" $linuxClientRoot = Join-Path $resolvedOutputRoot "sgu-linux-client-bootstrap-$Version" $azureRoot = Join-Path $resolvedOutputRoot "sgu-azure-infrastructure-$Version" +$wifiRoot = Join-Path $resolvedOutputRoot "sgu-ced-wifi-policy-$Version" $clientZip = "$clientRoot.zip" $serverZip = "$serverRoot.zip" $linuxClientZip = "$linuxClientRoot.zip" $azureZip = "$azureRoot.zip" +$wifiZip = "$wifiRoot.zip" foreach ($target in @( - $clientRoot,$serverRoot,$linuxClientRoot,$azureRoot, - $clientZip,$serverZip,$linuxClientZip,$azureZip)) { + $clientRoot,$serverRoot,$linuxClientRoot,$azureRoot,$wifiRoot, + $clientZip,$serverZip,$linuxClientZip,$azureZip,$wifiZip)) { if (Test-Path -LiteralPath $target) { throw "Release target already exists: $target" } } New-Item -ItemType Directory ` - -Path $clientRoot,$serverRoot,$linuxClientRoot,$azureRoot ` + -Path $clientRoot,$serverRoot,$linuxClientRoot,$azureRoot,$wifiRoot ` -Force | Out-Null $welcomeFontNames = @( 'IndivisaTextSans-Regular.otf', @@ -206,6 +208,12 @@ Copy-RequiredFile -Source (Join-Path $PSScriptRoot 'Start-SguServerBootstrap.cmd Copy-RequiredFile -Source (Join-Path $PSScriptRoot 'Start-SguAzureServerBootstrap.cmd') ` -Destination (Join-Path $serverRoot 'Start-SguAzureServerBootstrap.cmd') $serverScripts = @( + 'Set-SguCedWifiPolicy.ps1', + 'Install-SguCedWifiMaintenance.ps1', + 'Repair-SguCedWifi.ps1', + 'Sync-SguCedWifiReaders.ps1', + 'Connect-SguCedWifi.ps1', + 'Invoke-SguCedClientEnrollment.ps1', 'Deploy-AuthBroker.ps1', 'Disable-SguAzureUserRoaming.ps1', 'Enable-SguAzureUserRoaming.ps1', @@ -298,11 +306,31 @@ Write-PackageManifest -PackageRoot $azureRoot -PackageVersion $Version -PackageK Compress-Archive -Path (Join-Path $azureRoot '*') -DestinationPath $azureZip ` -CompressionLevel Optimal +# Existing domains can publish the WLAN correction without running forest setup. +foreach ($scriptName in @( + 'Set-SguCedWifiPolicy.ps1', + 'Install-SguCedWifiMaintenance.ps1', + 'Repair-SguCedWifi.ps1', + 'Sync-SguCedWifiReaders.ps1', + 'Connect-SguCedWifi.ps1', + 'Invoke-SguCedClientEnrollment.ps1')) { + Copy-RequiredFile -Source (Join-Path $PSScriptRoot $scriptName) ` + -Destination (Join-Path $wifiRoot $scriptName) +} +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') +Write-PackageManifest -PackageRoot $wifiRoot -PackageVersion $Version -PackageKind CedWifiPolicy +Compress-Archive -Path (Join-Path $wifiRoot '*') -DestinationPath $wifiZip ` + -CompressionLevel Optimal + $checksums = @( ("{0} {1}" -f (Get-FileHash -LiteralPath $clientZip -Algorithm SHA256).Hash, (Split-Path $clientZip -Leaf)) ("{0} {1}" -f (Get-FileHash -LiteralPath $serverZip -Algorithm SHA256).Hash, (Split-Path $serverZip -Leaf)) ("{0} {1}" -f (Get-FileHash -LiteralPath $linuxClientZip -Algorithm SHA256).Hash, (Split-Path $linuxClientZip -Leaf)) ("{0} {1}" -f (Get-FileHash -LiteralPath $azureZip -Algorithm SHA256).Hash, (Split-Path $azureZip -Leaf)) + ("{0} {1}" -f (Get-FileHash -LiteralPath $wifiZip -Algorithm SHA256).Hash, (Split-Path $wifiZip -Leaf)) ) $checksumsPath = Join-Path $resolvedOutputRoot "SHA256SUMS-$Version.txt" [IO.File]::WriteAllLines($checksumsPath, $checksums, [Text.UTF8Encoding]::new($false)) @@ -317,6 +345,8 @@ $checksumsPath = Join-Path $resolvedOutputRoot "SHA256SUMS-$Version.txt" ServerSha256 = (Get-FileHash -LiteralPath $serverZip -Algorithm SHA256).Hash AzureInfrastructurePackage = $azureZip AzureInfrastructureSha256 = (Get-FileHash -LiteralPath $azureZip -Algorithm SHA256).Hash + CedWifiPolicyPackage = $wifiZip + CedWifiPolicySha256 = (Get-FileHash -LiteralPath $wifiZip -Algorithm SHA256).Hash Checksums = $checksumsPath RuntimeInstaller = $runtimeInstaller.Name } diff --git a/scripts/Publish-GiteaRelease.ps1 b/scripts/Publish-GiteaRelease.ps1 index 72c2c6a..2985eb4 100644 --- a/scripts/Publish-GiteaRelease.ps1 +++ b/scripts/Publish-GiteaRelease.ps1 @@ -23,6 +23,7 @@ $assetPaths = @( (Join-Path $ReleaseDirectory "sgu-server-bootstrap-$Version.zip"), (Join-Path $ReleaseDirectory "sgu-linux-client-bootstrap-$Version.zip"), (Join-Path $ReleaseDirectory "sgu-azure-infrastructure-$Version.zip"), + (Join-Path $ReleaseDirectory "sgu-ced-wifi-policy-$Version.zip"), (Join-Path $ReleaseDirectory "SHA256SUMS-$Version.txt") ) foreach ($assetPath in $assetPaths) { @@ -143,7 +144,8 @@ Las contraseñas se solicitan de forma interactiva y no se escriben en archivos target_commitish = $TargetCommitish name = "SGU Credential Provider $Version" body = $releaseNotes - draft = [bool]$Draft + # Keep the release private until every attachment has uploaded. + draft = $true prerelease = $Version -match '-' } @@ -175,6 +177,11 @@ Las contraseñas se solicitan de forma interactiva y no se escriben en archivos } } + if (-not $Draft) { + $release = Invoke-GiteaJson -Method ([Net.Http.HttpMethod]::Patch) ` + -RelativeUri "$repositoryPath/releases/$($release.id)" -Body @{draft=$false} + } + [pscustomobject]@{ Tag = $tagName ReleaseName = $release.name diff --git a/scripts/Repair-SguCedWifi.ps1 b/scripts/Repair-SguCedWifi.ps1 new file mode 100644 index 0000000..42e5f48 --- /dev/null +++ b/scripts/Repair-SguCedWifi.ps1 @@ -0,0 +1,108 @@ +[CmdletBinding()] +param([switch]$PreferCedNow,[string]$ProvisionXml='') +$ErrorActionPreference='Stop' +$computer=Get-CimInstance Win32_ComputerSystem +if(-not $computer.PartOfDomain -or $computer.DomainRole -ne 1 -or $env:COMPUTERNAME -notmatch '^(AF|SD|SI)-'){return} +$destination='C:\ProgramData\LCI-Admin\CED-WiFi' +if(-not ('Sgu.CedMachineWifi' -as [type])){ +Add-Type -ReferencedAssemblies System.dll,System.Xml.dll -TypeDefinition @' +using System; +using System.Collections.Generic; +using System.Collections; +using System.Runtime.InteropServices; +using System.Text; +using System.Xml; +namespace Sgu { + public class CedWifiResult { public string Interface; public string Ssid; public string Profile; public bool MachineProfileReady; public bool GroupProfileRepaired; public bool MachineProfileCreated; public int OtherProfilesMadeManual; public bool ConnectionRequested; public uint QueryError; } + public static class CedMachineWifi { + [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)] struct Connection { public int Mode; [MarshalAs(UnmanagedType.LPWStr)] public string Profile; public IntPtr Ssid; public IntPtr Bssids; public int BssType; public uint Flags; } + [StructLayout(LayoutKind.Sequential)] struct Session { public int Id; public IntPtr Name; public int State; } + [DllImport("wlanapi.dll")] static extern uint WlanOpenHandle(uint v,IntPtr r,out uint n,out IntPtr h); + [DllImport("wlanapi.dll")] static extern uint WlanEnumInterfaces(IntPtr h,IntPtr r,out IntPtr p); + [DllImport("wlanapi.dll")] static extern uint WlanGetProfileList(IntPtr h,ref Guid i,IntPtr r,out IntPtr p); + [DllImport("wlanapi.dll",CharSet=CharSet.Unicode)] static extern uint WlanGetProfile(IntPtr h,ref Guid i,string name,IntPtr r,out IntPtr xml,ref uint flags,out uint access); + [DllImport("wlanapi.dll",CharSet=CharSet.Unicode)] static extern uint WlanSetProfile(IntPtr h,ref Guid i,uint flags,string xml,string security,[MarshalAs(UnmanagedType.Bool)]bool overwrite,IntPtr r,out uint reason); + [DllImport("wlanapi.dll",CharSet=CharSet.Unicode)] static extern uint WlanSetProfilePosition(IntPtr h,ref Guid i,string name,uint position,IntPtr r); + [DllImport("wlanapi.dll")] static extern uint WlanQueryInterface(IntPtr h,ref Guid i,int opcode,IntPtr r,out uint size,out IntPtr data,out int type); + [DllImport("wlanapi.dll")] static extern uint WlanSetInterface(IntPtr h,ref Guid i,int opcode,uint size,ref int data,IntPtr r); + [DllImport("wlanapi.dll",CharSet=CharSet.Unicode)] static extern uint WlanConnect(IntPtr h,ref Guid i,ref Connection c,IntPtr r); + [DllImport("wlanapi.dll")] static extern uint WlanCloseHandle(IntPtr h,IntPtr r); + [DllImport("wlanapi.dll")] static extern void WlanFreeMemory(IntPtr p); + [DllImport("wtsapi32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern bool WTSEnumerateSessions(IntPtr h,int reserved,int version,out IntPtr list,out int count); + [DllImport("wtsapi32.dll",CharSet=CharSet.Unicode)] static extern bool WTSQuerySessionInformation(IntPtr h,int id,int type,out IntPtr data,out int bytes); + [DllImport("wtsapi32.dll")] static extern void WTSFreeMemory(IntPtr p); + static void Check(uint e){if(e!=0)throw new System.ComponentModel.Win32Exception((int)e);} + static XmlDocument Read(IntPtr h,ref Guid id,string name,out uint flags){IntPtr p=IntPtr.Zero;uint access;flags=0;uint e=WlanGetProfile(h,ref id,name,IntPtr.Zero,out p,ref flags,out access);if(e!=0)return null;try{var x=new XmlDocument();x.LoadXml(Marshal.PtrToStringUni(p));return x;}finally{WlanFreeMemory(p);}} + static string Text(XmlDocument x,string name){XmlNode n=x.SelectSingleNode("//*[local-name()='"+name+"']");return n==null?"":n.InnerText;} + static bool Auto(XmlDocument x){bool changed=false;XmlElement root=x.DocumentElement;XmlNode mode=root.SelectSingleNode("*[local-name()='connectionMode']");if(mode==null)throw new InvalidOperationException("Missing connection mode.");if(mode.InnerText!="auto"){mode.InnerText="auto";changed=true;}XmlNode sw=root.SelectSingleNode("*[local-name()='autoSwitch']");if(sw==null){sw=x.CreateElement("autoSwitch",root.NamespaceURI);root.InsertAfter(sw,mode);changed=true;}if(sw.InnerText!="false"){sw.InnerText="false";changed=true;}return changed;} + static void Save(IntPtr h,ref Guid id,uint flags,XmlDocument x){uint reason;uint e=WlanSetProfile(h,ref id,flags,x.OuterXml,null,true,IntPtr.Zero,out reason);if(e!=0)throw new InvalidOperationException("Cannot save WLAN profile: "+e+", reason="+reason);} + static void Connected(IntPtr h,ref Guid id,CedWifiResult result){IntPtr p=IntPtr.Zero;uint size;int type;uint e=WlanQueryInterface(h,ref id,7,IntPtr.Zero,out size,out p,out type);result.QueryError=e;try{if(e==0&&size>=556){result.Profile=Marshal.PtrToStringUni(IntPtr.Add(p,8));int len=Marshal.ReadInt32(p,520);if(len>=0&&len<=32){byte[] ssid=new byte[len];Marshal.Copy(IntPtr.Add(p,524),ssid,0,len);result.Ssid=Encoding.UTF8.GetString(ssid);}}}finally{if(p!=IntPtr.Zero)WlanFreeMemory(p);}} + static void Connect(IntPtr h,ref Guid id,string name){Connection c=new Connection{Mode=0,Profile=name,BssType=1};Check(WlanConnect(h,ref id,ref c,IntPtr.Zero));} + public static int UserSessions(){IntPtr list=IntPtr.Zero;int count,result=0;if(!WTSEnumerateSessions(IntPtr.Zero,0,1,out list,out count))throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());try{int size=Marshal.SizeOf(typeof(Session));for(int i=0;i2&&!String.IsNullOrEmpty(Marshal.PtrToStringUni(p)))result++;}finally{if(p!=IntPtr.Zero)WTSFreeMemory(p);}}}finally{WTSFreeMemory(list);}return result;} + public static CedWifiResult[] Ensure(string provision,bool prefer,bool rollback,string prior,IDictionary facts){ + const string ssid="Centro de Experiencia Digital", backup="CED - Equipo";IntPtr h=IntPtr.Zero,list=IntPtr.Zero;uint v;var results=new List();Check(WlanOpenHandle(2,IntPtr.Zero,out v,out h)); + try{Check(WlanEnumInterfaces(h,IntPtr.Zero,out list));int count=Marshal.ReadInt32(list);for(int i=0;i$escapedNameWi-Fi administrado exclusivamente para la OU CED." + - 'truefalsefalse' + + 'truefalsetrue' + 'truefalse' + '' + $profile.DocumentElement.OuterXml + '' $policy = Get-ADObject -SearchBase $parent -SearchScope OneLevel -LDAPFilter '(cn=CED Wi-Fi)' -Server $DomainController -Properties ms-net-ieee-80211-GP-PolicyData @@ -76,6 +80,7 @@ if (-not $policy) { $entry = [DirectoryServices.DirectoryEntry]::new("LDAP://$DomainController/$policyDn") try { $security = $entry.ObjectSecurity + $beforeSecurity=$security.GetSecurityDescriptorSddlForm([Security.AccessControl.AccessControlSections]::Access) $security.SetAccessRuleProtection($true, $false) foreach ($rule in @($security.GetAccessRules($true,$false,[Security.Principal.SecurityIdentifier]))) { $security.RemoveAccessRuleSpecific($rule) } $forestRoot = Get-ADDomain -Identity (Get-ADForest -Server $DomainController).RootDomain -Server $DomainController @@ -88,15 +93,14 @@ try { foreach ($computer in $computers) { $security.AddAccessRule([DirectoryServices.ActiveDirectoryAccessRule]::new($computer.SID,[DirectoryServices.ActiveDirectoryRights]::GenericRead,[Security.AccessControl.AccessControlType]::Allow)) } - $entry.ObjectSecurity = $security - $entry.CommitChanges() + if($beforeSecurity -ne $security.GetSecurityDescriptorSddlForm([Security.AccessControl.AccessControlSections]::Access)){$entry.ObjectSecurity = $security;$entry.CommitChanges()} } finally { $entry.Dispose() } if ($changed) { Set-ADObject $policyDn -Server $DomainController -Replace @{'ms-net-ieee-80211-GP-PolicyData'=$policyXml} } $adGpo = Get-ADObject $gpoDn -Server $DomainController -Properties versionNumber,gPCMachineExtensionNames $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','Invoke-SguCedClientEnrollment.ps1') { +foreach ($file in 'Install-SguCedWifiMaintenance.ps1','Connect-SguCedWifi.ps1','Repair-SguCedWifi.ps1','Invoke-SguCedClientEnrollment.ps1') { $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) { @@ -126,4 +130,26 @@ if ($changed) { $link = (Get-GPInheritance -Target $TargetOuDn -Domain $domain.DNSRoot -Server $DomainController).GpoLinks | Where-Object GpoId -eq $gpo.Id if (-not $link) { New-GPLink -Guid $gpo.Id -Target $TargetOuDn -Domain $domain.DNSRoot -Server $DomainController -LinkEnabled Yes | Out-Null } elseif (-not $link.Enabled) { Set-GPLink -Guid $gpo.Id -Target $TargetOuDn -Domain $domain.DNSRoot -Server $DomainController -LinkEnabled Yes | Out-Null } +$filterName='CED - Wi-Fi AF SD SI' +$query="SELECT * FROM Win32_ComputerSystem WHERE DomainRole = 1 AND (Name LIKE 'AF-%' OR Name LIKE 'SD-%' OR Name LIKE 'SI-%')" +$encodedQuery="1;3;10;$($query.Length);WQL;root\CIMv2;$query;" +$filter=@(Get-ADObject -SearchBase "CN=SOM,CN=WMIPolicy,CN=System,$($domain.DistinguishedName)" -LDAPFilter '(objectClass=msWMI-Som)' -Server $DomainController -Properties msWMI-Name,msWMI-ID,msWMI-Parm2|Where-Object {$_.'msWMI-Name' -eq $filterName}) +if($filter.Count -gt 1){throw 'Duplicate CED wireless WMI filters.'} +if(-not $filter.Count){ + $id=([guid]::NewGuid()).ToString('B').ToUpperInvariant();$timestamp=[DateTime]::UtcNow.ToString('yyyyMMddHHmmss.ffffff-000') + $created=New-ADObject -Name $id -Type msWMI-Som -Path "CN=SOM,CN=WMIPolicy,CN=System,$($domain.DistinguishedName)" -Server $DomainController -OtherAttributes @{'msWMI-Name'=$filterName;'msWMI-ID'=$id;'msWMI-Parm1'='Wi-Fi clients AF, SD and SI only; excludes APPS and all servers.';'msWMI-Parm2'=$encodedQuery;'msWMI-Author'='La Salle';'msWMI-CreationDate'=$timestamp;'msWMI-ChangeDate'=$timestamp} -PassThru + $filter=@(Get-ADObject -Identity $created.DistinguishedName -Server $DomainController -Properties msWMI-ID,msWMI-Parm2) +}elseif($filter[0].'msWMI-Parm2' -ne $encodedQuery){throw 'CED wireless WMI query differs; inspect before modifying.'} +$reference="[$($domain.DNSRoot);$($filter[0].'msWMI-ID');0]" +$current=Get-ADObject -Identity $gpoDn -Server $DomainController -Properties gPCWQLFilter +if($current.gPCWQLFilter -ne $reference){Set-ADObject -Identity $gpoDn -Server $DomainController -Replace @{gPCWQLFilter=$reference};$changed=$true} +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} +)){ + $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} +} [pscustomobject]@{Gpo=$GpoName;Id=$gpo.Id;SSID=$ssid;TargetOu=$TargetOuDn;Computers=$computers.Count;ReaderGroup=$ReaderGroup;Changed=$changed} diff --git a/scripts/Sync-SguCedWifiReaders.ps1 b/scripts/Sync-SguCedWifiReaders.ps1 index fe4c516..784edda 100644 --- a/scripts/Sync-SguCedWifiReaders.ps1 +++ b/scripts/Sync-SguCedWifiReaders.ps1 @@ -49,7 +49,7 @@ if ($InstallRefreshTask) { $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 15) Register-ScheduledTask -TaskName 'CED WiFi OU readers refresh' -Action $action -Trigger $trigger -User SYSTEM -RunLevel Highest -Force | Out-Null } -$computers = @(Get-ADComputer -SearchBase $TargetOuDn -Filter 'Enabled -eq $true' -Server $DomainController) +$computers = @(Get-ADComputer -SearchBase $TargetOuDn -Filter 'Enabled -eq $true' -Server $DomainController | Where-Object Name -match '^(AF|SD|SI)-') $members = @(Get-ADGroupMember $group -Server $DomainController) $add = @($computers | Where-Object DistinguishedName -notin $members.DistinguishedName) $remove = @($members | Where-Object DistinguishedName -notin $computers.DistinguishedName)