143 lines
7.6 KiB
PowerShell
143 lines
7.6 KiB
PowerShell
[CmdletBinding()]
|
|
param(
|
|
[string]$RemoteDesktopPrincipal = 'LCI\SG-Laboratorio-Usuarios-RDP',
|
|
[string]$LocalDnsServer = '',
|
|
[string]$FallbackDnsServer = ''
|
|
)
|
|
|
|
$ErrorActionPreference = 'Stop'
|
|
$computer = Get-CimInstance Win32_ComputerSystem
|
|
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 -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
|
|
})) {
|
|
$ipBytes = ([Net.IPAddress]::Parse($ip.IPAddress)).GetAddressBytes()
|
|
$sameSubnet = $true
|
|
for ($bit = 0; $bit -lt $ip.PrefixLength; $bit++) {
|
|
$mask = 1 -shl (7 - ($bit % 8))
|
|
$index = [int][Math]::Floor($bit / 8)
|
|
if (($ipBytes[$index] -band $mask) -ne ($dnsBytes[$index] -band $mask)) {
|
|
$sameSubnet = $false; break
|
|
}
|
|
}
|
|
if (-not $sameSubnet) { continue }
|
|
try {
|
|
$authority = @(Resolve-DnsName -Name $computer.Domain -Type SOA -Server $LocalDnsServer -DnsOnly -ErrorAction Stop |
|
|
Where-Object { $_.Name -ieq $computer.Domain -and $_.Type -eq 'SOA' })
|
|
if (-not $authority) { throw 'The DNS server did not return the domain SOA.' }
|
|
$desiredServers = @($LocalDnsServer)
|
|
if ($FallbackDnsServer) {
|
|
[Net.IPAddress]::Parse($FallbackDnsServer) | Out-Null
|
|
$fallbackAuthority = @(Resolve-DnsName -Name $computer.Domain -Type SOA -Server $FallbackDnsServer -DnsOnly -ErrorAction Stop |
|
|
Where-Object { $_.Name -ieq $computer.Domain -and $_.Type -eq 'SOA' })
|
|
if (-not $fallbackAuthority) { throw 'Fallback DNS is not authoritative for this domain.' }
|
|
$desiredServers += $FallbackDnsServer
|
|
}
|
|
$current = (Get-DnsClientServerAddress -InterfaceIndex $ip.InterfaceIndex -AddressFamily IPv4).ServerAddresses
|
|
if ((@($current) -join ',') -ne ($desiredServers -join ',')) {
|
|
Set-DnsClientServerAddress -InterfaceIndex $ip.InterfaceIndex -ServerAddresses $desiredServers
|
|
}
|
|
Set-DnsClient -InterfaceIndex $ip.InterfaceIndex -RegisterThisConnectionsAddress $true
|
|
Register-DnsClient
|
|
} catch { Write-Warning "Site DNS configuration failed: $($_.Exception.Message)" }
|
|
}
|
|
}
|
|
|
|
$terminalKey = 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server'
|
|
$rdpKey = Join-Path $terminalKey 'WinStations\RDP-Tcp'
|
|
if ((Get-ItemPropertyValue -Path $terminalKey -Name fDenyTSConnections) -ne 0) {
|
|
Set-ItemProperty -Path $terminalKey -Name fDenyTSConnections -Value 0
|
|
}
|
|
if ((Get-ItemPropertyValue -Path $rdpKey -Name UserAuthentication) -ne 1) {
|
|
Set-ItemProperty -Path $rdpKey -Name UserAuthentication -Value 1
|
|
}
|
|
|
|
foreach ($name in @('TermService', 'WinRM')) {
|
|
$service = Get-Service -Name $name
|
|
if ($service.StartType -ne 'Automatic') { Set-Service -Name $name -StartupType Automatic }
|
|
if ($service.Status -ne 'Running') { Start-Service -Name $name }
|
|
}
|
|
|
|
# Each domain refresh carries this script through SYSVOL. Apply only the
|
|
# narrowly scoped inbound rules required by an administrator on the same LAN.
|
|
$rules = @(
|
|
@{ Name = 'SGU-Workstation-WinRM-HTTP'; Protocol = 'TCP'; Port = '5985' },
|
|
@{ Name = 'SGU-Workstation-RDP-TCP'; Protocol = 'TCP'; Port = '3389' },
|
|
@{ Name = 'SGU-Workstation-RDP-UDP'; Protocol = 'UDP'; Port = '3389' }
|
|
)
|
|
foreach ($rule in $rules) {
|
|
$existing = Get-NetFirewallRule -Name $rule.Name -ErrorAction SilentlyContinue
|
|
if ($existing) {
|
|
$port = $existing | Get-NetFirewallPortFilter
|
|
$address = $existing | Get-NetFirewallAddressFilter
|
|
$valid = $existing.Enabled -eq 'True' -and $existing.Action -eq 'Allow' -and
|
|
$existing.Direction -eq 'Inbound' -and $existing.Profile -eq 'Any' -and
|
|
$port.Protocol -eq $rule.Protocol -and [string]$port.LocalPort -eq $rule.Port -and
|
|
@($address.RemoteAddress).Count -eq 1 -and $address.RemoteAddress -eq 'LocalSubnet'
|
|
if ($valid) { continue }
|
|
$existing | Remove-NetFirewallRule
|
|
}
|
|
New-NetFirewallRule -Name $rule.Name -DisplayName $rule.Name -Enabled True `
|
|
-Direction Inbound -Action Allow -Profile Any -Protocol $rule.Protocol `
|
|
-LocalPort $rule.Port -RemoteAddress LocalSubnet | Out-Null
|
|
}
|
|
|
|
# WinRM's administrative-template policy creates the listener. This also
|
|
# restores the Windows PowerShell session endpoint when it was disabled.
|
|
$listener = @(Get-ChildItem WSMan:\localhost\Listener -ErrorAction SilentlyContinue |
|
|
Where-Object { $_.Keys -contains 'Transport=HTTP' })
|
|
$endpoint = Get-PSSessionConfiguration -Name Microsoft.PowerShell -ErrorAction SilentlyContinue
|
|
$endpointEnabled = Get-Item 'WSMan:\localhost\Plugin\Microsoft.PowerShell\Enabled' -ErrorAction SilentlyContinue
|
|
if (-not $listener -or -not $endpoint -or $endpointEnabled.Value -eq 'false') {
|
|
Enable-PSRemoting -Force -SkipNetworkProfileCheck | Out-Null
|
|
}
|
|
|
|
# Native, language-independent rule names. The domain policy also distributes
|
|
# these rules through the firewall CSE, so background gpupdate can repair them.
|
|
$managementPatterns = @('RemoteEventLogSvc-*', 'RemoteSvcAdmin-*', 'WMI-*',
|
|
'RemoteTask-*', 'RemoteFwAdmin-*', 'RVM-*', 'PerfLogsAlerts-*', 'FPS-SMB-In-TCP*')
|
|
foreach ($pattern in $managementPatterns) {
|
|
foreach ($nativeRule in @(Get-NetFirewallRule -Name $pattern -ErrorAction SilentlyContinue |
|
|
Where-Object Direction -eq 'Inbound')) {
|
|
# Do not try to mutate policy-owned rules in the workstation local store.
|
|
if ($nativeRule.PolicyStoreSourceType -ne 'Local') { continue }
|
|
$address = $nativeRule | Get-NetFirewallAddressFilter
|
|
if ($nativeRule.Enabled -ne 'True' -or $nativeRule.Profile -ne 'Any' -or
|
|
@($address.RemoteAddress).Count -ne 1 -or $address.RemoteAddress[0] -ne 'LocalSubnet') {
|
|
$nativeRule | Set-NetFirewallRule -Enabled True -Profile Any -RemoteAddress LocalSubnet
|
|
}
|
|
}
|
|
}
|
|
$remoteRegistry = Get-Service RemoteRegistry
|
|
if ($remoteRegistry.StartType -ne 'Manual') { Set-Service RemoteRegistry -StartupType Manual }
|
|
|
|
# The built-in local group has a stable SID across Windows display languages.
|
|
$groupSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-555')
|
|
$groupName = ($groupSid.Translate([Security.Principal.NTAccount]).Value -split '\\', 2)[1]
|
|
try {
|
|
$principalSid = ([Security.Principal.NTAccount]::new($RemoteDesktopPrincipal)).Translate(
|
|
[Security.Principal.SecurityIdentifier]).Value
|
|
$group = [ADSI]("WinNT://$env:COMPUTERNAME/$groupName,group")
|
|
$memberSids = @($group.psbase.Invoke('Members') | ForEach-Object {
|
|
try {
|
|
$bytes = $_.GetType().InvokeMember('objectSid',
|
|
[Reflection.BindingFlags]::GetProperty, $null, $_, $null)
|
|
if ($bytes) { ([Security.Principal.SecurityIdentifier]::new([byte[]]$bytes, 0)).Value }
|
|
}
|
|
catch { }
|
|
})
|
|
if ($memberSids -notcontains $principalSid) {
|
|
Add-LocalGroupMember -Group $groupName -Member $principalSid
|
|
}
|
|
}
|
|
catch {
|
|
# A temporarily unavailable DC must not prevent RDP and WinRM from starting.
|
|
Write-Warning "Remote Desktop group membership could not be verified: $($_.Exception.Message)"
|
|
}
|