158 lines
13 KiB
PowerShell
158 lines
13 KiB
PowerShell
[CmdletBinding(DefaultParameterSetName='File')]
|
|
param(
|
|
[Parameter(Mandatory,ParameterSetName='File')][string]$ProfilePath,
|
|
[Parameter(Mandatory,ParameterSetName='Xml')][xml]$ProfileDocument,
|
|
[string]$TargetOuDn = 'OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx',
|
|
[string]$GpoName = 'CED - Wi-Fi de salas',
|
|
[string]$DomainController = $env:COMPUTERNAME,
|
|
[string]$ReaderGroup = 'CED-WiFi-Equipos'
|
|
)
|
|
$ErrorActionPreference = 'Stop'
|
|
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
|
|
Import-Module GroupPolicy
|
|
$domain = Get-ADDomain -Server $DomainController
|
|
$ou = Get-ADOrganizationalUnit -Identity $TargetOuDn -Server $DomainController
|
|
if ($ou.DistinguishedName -notlike "*,$($domain.DistinguishedName)") { throw 'OU is outside this domain.' }
|
|
[xml]$profile = if($PSCmdlet.ParameterSetName -eq 'Xml'){$ProfileDocument.Clone()}else{Get-Content -LiteralPath $ProfilePath -Raw}
|
|
$ns = [Xml.XmlNamespaceManager]::new($profile.NameTable)
|
|
$ns.AddNamespace('w', 'http://www.microsoft.com/networking/WLAN/profile/v1')
|
|
$ssid = $profile.SelectSingleNode('//w:SSID/w:name', $ns).InnerText
|
|
$auth = $profile.SelectSingleNode('//w:authEncryption/w:authentication', $ns).InnerText
|
|
if ($auth -notin 'WPA2PSK','WPA3SAE' -or $profile.SelectSingleNode('//w:authEncryption/w:encryption', $ns).InnerText -ne 'AES') {
|
|
throw 'Only WPA2/WPA3 Personal with AES is supported.'
|
|
}
|
|
if ($profile.SelectSingleNode('//w:sharedKey/w:protected', $ns).InnerText -ne 'false') {
|
|
throw 'Supply a privately stored export with key=clear. Never commit that XML.'
|
|
}
|
|
$keyLength = $profile.SelectSingleNode('//w:sharedKey/w:keyMaterial', $ns).InnerText.Length
|
|
$keyType = $profile.SelectSingleNode('//w:sharedKey/w:keyType', $ns).InnerText
|
|
if ($keyType -eq 'networkKey') {
|
|
if ($auth -ne 'WPA2PSK' -or $profile.SelectSingleNode('//w:sharedKey/w:keyMaterial', $ns).InnerText -notmatch '^[0-9A-Fa-f]{64}$') { throw 'Invalid WPA2 network key.' }
|
|
} elseif ($keyType -ne 'passPhrase' -or $keyLength -lt 8 -or $keyLength -gt 63) { throw 'Invalid passphrase length.' }
|
|
$profile.SelectSingleNode('/w:WLANProfile/w:name', $ns).InnerText = $ssid
|
|
$profile.SelectSingleNode('//w:connectionMode', $ns).InnerText = 'auto'
|
|
$switch=$profile.SelectSingleNode('/w:WLANProfile/w:autoSwitch',$ns)
|
|
if(-not $switch){$switch=$profile.CreateElement('autoSwitch',$profile.DocumentElement.NamespaceURI);[void]$profile.DocumentElement.InsertAfter($switch,$profile.SelectSingleNode('/w:WLANProfile/w:connectionMode',$ns))}
|
|
$switch.InnerText='false'
|
|
$group = Get-ADGroup -Filter "SamAccountName -eq '$ReaderGroup'" -Server $DomainController
|
|
if (-not $group) {
|
|
$group = New-ADGroup -Name $ReaderGroup -SamAccountName $ReaderGroup -GroupCategory Security -GroupScope Global -Path $TargetOuDn -Server $DomainController -PassThru
|
|
}
|
|
if (-not $group.DistinguishedName.EndsWith(",$TargetOuDn",[StringComparison]::OrdinalIgnoreCase)) { throw 'Reader group is outside the target OU.' }
|
|
$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 })
|
|
if ($add.Count) { Add-ADGroupMember $group -Members $add -Server $DomainController }
|
|
if ($remove.Count) { Remove-ADGroupMember $group -Members $remove -Server $DomainController -Confirm:$false }
|
|
$gpo = Get-GPO -Name $GpoName -Server $DomainController -Domain $domain.DNSRoot -ErrorAction SilentlyContinue
|
|
if (-not $gpo) { $gpo = New-GPO -Name $GpoName -Server $DomainController -Domain $domain.DNSRoot }
|
|
if ($gpo.GpoStatus -ne 'UserSettingsDisabled') { $gpo.GpoStatus = [Microsoft.GroupPolicy.GpoStatus]::UserSettingsDisabled }
|
|
$gpoDn = "CN={$($gpo.Id)},CN=Policies,CN=System,$($domain.DistinguishedName)"
|
|
$parent = "CN=Machine,$gpoDn"
|
|
foreach ($name in 'Microsoft','Windows','IEEE80211') {
|
|
$dn = "CN=$name,$parent"
|
|
if (-not (Get-ADObject -SearchBase $parent -SearchScope OneLevel -LDAPFilter "(cn=$name)" -Server $DomainController)) {
|
|
New-ADObject -Name $name -Type container -Path $parent -Server $DomainController
|
|
}
|
|
$parent = $dn
|
|
}
|
|
$policyDn = "CN=CED Wi-Fi,$parent"
|
|
$escapedName = [Security.SecurityElement]::Escape($ssid)
|
|
$policyXml = '<WLANPolicy xmlns="http://www.microsoft.com/networking/WLAN/policy/v1">' +
|
|
"<name>$escapedName</name><description>Wi-Fi administrado exclusivamente para la OU CED.</description>" +
|
|
'<globalFlags><enableAutoConfig>true</enableAutoConfig><showDeniedNetwork>false</showDeniedNetwork><allowEveryoneToCreateAllUserProfiles>true</allowEveryoneToCreateAllUserProfiles></globalFlags>' +
|
|
'<networkFilter><denyAllIBSS>true</denyAllIBSS><denyAllESS>false</denyAllESS></networkFilter>' +
|
|
'<profileList>' + $profile.DocumentElement.OuterXml + '</profileList></WLANPolicy>'
|
|
$policy = Get-ADObject -SearchBase $parent -SearchScope OneLevel -LDAPFilter '(cn=CED Wi-Fi)' -Server $DomainController -Properties ms-net-ieee-80211-GP-PolicyData
|
|
$changed = -not $policy -or $policy.'ms-net-ieee-80211-GP-PolicyData' -cne $policyXml -or $add.Count -gt 0 -or $remove.Count -gt 0
|
|
if (-not $policy) {
|
|
# The native WLAN CSE reads this AD object (MS-GPWL), not a startup-script profile.
|
|
New-ADObject -Name 'CED Wi-Fi' -Type ms-net-ieee-80211-GroupPolicy -Path $parent -Server $DomainController -OtherAttributes @{
|
|
'ms-net-ieee-80211-GP-PolicyGUID' = ([guid]::NewGuid()).ToString('B')
|
|
'description' = 'CED managed wireless profile. Contains a PSK; restricted computer read access.'
|
|
}
|
|
}
|
|
# Remove inherited read access BEFORE publishing/updating any existing PSK.
|
|
$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
|
|
$controller = Get-ADComputer -Identity ($DomainController.Split('.')[0]) -Server $DomainController
|
|
# 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))
|
|
# Direct computer ACEs avoid needing a reboot to refresh machine group tokens.
|
|
foreach ($computer in $computers) {
|
|
$security.AddAccessRule([DirectoryServices.ActiveDirectoryAccessRule]::new($computer.SID,[DirectoryServices.ActiveDirectoryRights]::GenericRead,[Security.AccessControl.AccessControlType]::Allow))
|
|
}
|
|
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','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) {
|
|
Copy-Item $source $destination -Force
|
|
$changed = $true
|
|
}
|
|
}
|
|
$scriptPath = "\\$($domain.DNSRoot)\SYSVOL\$($domain.DNSRoot)\Policies\{$($gpo.Id)}\Machine\Scripts\Startup\Install-SguCedWifiMaintenance.ps1"
|
|
$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)
|
|
$changed = $true
|
|
}
|
|
$extension = '[{0ACDD40C-75AC-47AB-BAA0-BF6DE7E7FE63}{2DA6AA7F-8C88-4194-A558-0D36E7FD3E64}]'
|
|
$names = [string]$adGpo.gPCMachineExtensionNames
|
|
if ($names.IndexOf($extension, [StringComparison]::OrdinalIgnoreCase) -lt 0) { $names += $extension; $changed = $true }
|
|
$scriptsExtension = '[{42B5FAAE-6536-11D2-AE5A-0000F87571E3}{40B6664F-4972-11D1-A7CA-0000F87571E3}]'
|
|
if ($names.IndexOf($scriptsExtension, [StringComparison]::OrdinalIgnoreCase) -lt 0) { $names += $scriptsExtension; $changed = $true }
|
|
if ($changed) {
|
|
$names = ([regex]::Matches($names, '\[[^\]]+\]') | ForEach-Object Value | Sort-Object -Unique) -join ''
|
|
$v = ([long]$adGpo.versionNumber -band 0xFFFF0000L) -bor (([long]$adGpo.versionNumber + 1) -band 0xFFFFL)
|
|
Set-ADObject $gpoDn -Server $DomainController -Replace @{gPCMachineExtensionNames=$names;versionNumber=[int]$v}
|
|
[IO.File]::WriteAllText((Join-Path $root 'GPT.INI'), "[General]`r`nVersion=$v`r`n", [Text.Encoding]::ASCII)
|
|
}
|
|
$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=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}
|
|
}
|
|
[pscustomobject]@{Gpo=$GpoName;Id=$gpo.Id;SSID=$ssid;TargetOu=$TargetOuDn;Computers=$computers.Count;ReaderGroup=$ReaderGroup;Changed=$changed}
|