-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenable-av-redirection.ps1
More file actions
232 lines (206 loc) · 10.8 KB
/
Copy pathenable-av-redirection.ps1
File metadata and controls
232 lines (206 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
$ErrorActionPreference = "Stop"; $scriptArgs = $args
function ArgValue($name) {
for ($i = 0; $i -lt $scriptArgs.Count; $i++) {
if ($scriptArgs[$i] -in @("-$name", "--$name")) {
if ($i + 1 -ge $scriptArgs.Count) { throw "Argument '$($scriptArgs[$i])' requires a value." }
return $scriptArgs[$i + 1]
}
}
return ""
}
function AssertKnownArguments {
for ($i = 0; $i -lt $scriptArgs.Count; $i++) {
$argument = [string]$scriptArgs[$i]
if ($argument -in @("-config", "--config")) {
if ($i + 1 -ge $scriptArgs.Count) { throw "Argument '$argument' requires a value." }
$i++
continue
}
throw "Unknown argument '$argument'."
}
}
function FullPath($path) {
$path = [Environment]::ExpandEnvironmentVariables([string]$path)
if ($path -match '^~[\\/](.*)$') { return (Join-Path $HOME $Matches[1]) }
if ([IO.Path]::IsPathRooted($path)) { return $path }
return (Join-Path $PSScriptRoot $path)
}
function Default($cfg, $name, $value) {
if ($null -eq $cfg.$name) { $cfg | Add-Member -Force NoteProperty $name $value }
}
function SecureText($text) {
$secure = [Security.SecureString]::new()
foreach ($character in ([string]$text).ToCharArray()) { $secure.AppendChar($character) }
$secure.MakeReadOnly()
return $secure
}
function GuestCredential($baseDir) {
$path = Join-Path $baseDir "credentials.txt"
if (-not (Test-Path -LiteralPath $path)) { throw "Credentials file '$path' was not found." }
$content = Get-Content -LiteralPath $path
$user = [regex]::Match(($content | Where-Object { $_ -match '^User:\s*' } | Select-Object -First 1), '^User:\s*(.+)$').Groups[1].Value
$password = [regex]::Match(($content | Where-Object { $_ -match '^Password:\s*' } | Select-Object -First 1), '^Password:\s*(.+)$').Groups[1].Value
if ([string]::IsNullOrWhiteSpace($user) -or [string]::IsNullOrWhiteSpace($password)) {
throw "Credentials file '$path' does not contain User and Password lines."
}
return [pscredential]::new($user, (SecureText $password))
}
function GuestBootTime($vmName, $credential) {
Invoke-Command -VMName $vmName -Credential $credential -ScriptBlock {
(Get-CimInstance Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString("o")
} -ErrorAction Stop
}
function WaitForGuest($vmName, $credential, $timeoutSeconds = 300) {
$deadline = (Get-Date).AddSeconds($timeoutSeconds)
while ((Get-Date) -lt $deadline) {
try {
GuestBootTime $vmName $credential | Out-Null
return
} catch {
Start-Sleep -Seconds 5
}
}
throw "VM '$vmName' did not answer over PowerShell Direct within $timeoutSeconds seconds."
}
function EnsureVmRunning($vmName, $credential) {
$vm = Get-VM -Name $vmName -ErrorAction Stop
switch ([string]$vm.State) {
"Off" {
Start-VM -Name $vmName | Out-Null
Write-Host "Configured: VM started"
}
"Saved" {
Start-VM -Name $vmName | Out-Null
Write-Host "Configured: VM resumed"
}
"Paused" {
Resume-VM -Name $vmName | Out-Null
Write-Host "Configured: VM resumed"
}
"Running" {
Write-Host "Already configured: VM running"
}
default {
throw "VM '$vmName' is in unsupported state '$($vm.State)'."
}
}
WaitForGuest $vmName $credential
}
function ConfigureGuest($vmName, $credential) {
Invoke-Command -VMName $vmName -Credential $credential -ScriptBlock {
$policyPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services"
$winStationsPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations"
$listenerPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp"
if (-not (Test-Path -LiteralPath $policyPath)) { New-Item -Path $policyPath -Force | Out-Null }
if (-not (Test-Path -LiteralPath $winStationsPath)) { throw "RDP WinStations registry path '$winStationsPath' was not found." }
if (-not (Test-Path -LiteralPath $listenerPath)) { throw "RDP listener registry path '$listenerPath' was not found." }
function ConvertFrom-HexString([string]$hex) {
[byte[]]$bytes = for ($i = 0; $i -lt $hex.Length; $i += 2) {
[Convert]::ToByte($hex.Substring($i, 2), 16)
}
return $bytes
}
$settings = @(
[pscustomobject]@{ Path = $policyPath; Name = "fDisableCam"; Type = "DWord"; Value = 0; Label = "RDP audio playback policy" }
[pscustomobject]@{ Path = $policyPath; Name = "fDisableAudioCapture"; Type = "DWord"; Value = 0; Label = "RDP microphone policy" }
[pscustomobject]@{ Path = $policyPath; Name = "fDisableCameraRedir"; Type = "DWord"; Value = 0; Label = "RDP camera policy" }
[pscustomobject]@{ Path = $listenerPath; Name = "fDisableCam"; Type = "DWord"; Value = 0; Label = "RDP audio playback listener" }
[pscustomobject]@{ Path = $listenerPath; Name = "fDisableAudioCapture"; Type = "DWord"; Value = 0; Label = "RDP microphone listener" }
[pscustomobject]@{ Path = $listenerPath; Name = "AudioEnumeratorDll"; Type = "String"; Value = "rdpendp.dll"; Label = "RDP audio endpoint enumerator" }
)
foreach ($setting in $settings) {
$current = Get-ItemProperty -LiteralPath $setting.Path -Name $setting.Name -ErrorAction SilentlyContinue
$changed = $null -eq $current -or [string]$current.$($setting.Name) -ne [string]$setting.Value
if ($changed) {
New-ItemProperty -Path $setting.Path -Name $setting.Name -PropertyType $setting.Type -Value $setting.Value -Force | Out-Null
}
[pscustomobject]@{ Label = $setting.Label; Changed = $changed; RestartRequired = $changed }
}
# Older bootstrap versions recreated WinStations with New-Item -Force and
# removed these stock security descriptors. Without them, Audiosrv cannot
# classify an RDP session and exposes no redirected playback or mic endpoint.
$stockSecurityDescriptors = @(
[pscustomobject]@{
Name = "ConsoleSecurity"
Label = "RDP console security descriptor"
Hex = "010014809C000000A800000000000000140000000200880006000000000014000100000001010000000000050400000000001400BF030F000101000000000005120000000000140089000F00010100000000000513000000000014008100000001010000000000051400000000001800BF030F000102000000000005200000002002000000001800210100000102000000000005200000002B020000010100000000000512000000010100000000000512000000"
}
[pscustomobject]@{
Name = "DefaultSecurity"
Label = "RDP default security descriptor"
Hex = "01001480B8000000C4000000140000003000000002001C000100000002801400210100000101000000000001000000000200880006000000000014000100000001010000000000050400000000001400BF030F000101000000000005120000000000140089000F00010100000000000513000000000014008100000001010000000000051400000000001800BF030F000102000000000005200000002002000000001800210100000102000000000005200000002B020000010100000000000512000000010100000000000512000000"
}
)
foreach ($descriptor in $stockSecurityDescriptors) {
$winStationsProperties = Get-ItemProperty -LiteralPath $winStationsPath
$currentProperty = $winStationsProperties.PSObject.Properties[$descriptor.Name]
$current = if ($null -ne $currentProperty) { $currentProperty.Value } else { $null }
$changed = $null -eq $current -or $current.Length -eq 0
if ($changed) {
New-ItemProperty -Path $winStationsPath -Name $descriptor.Name -PropertyType Binary -Value (ConvertFrom-HexString $descriptor.Hex) -Force | Out-Null
}
[pscustomobject]@{ Label = $descriptor.Label; Changed = $changed; RestartRequired = $changed }
}
foreach ($serviceName in @("AudioEndpointBuilder", "Audiosrv")) {
$service = Get-Service -Name $serviceName -ErrorAction Stop
$changed = $service.Status -ne "Running"
if ($changed) { Start-Service -Name $serviceName }
[pscustomobject]@{ Label = "Guest service $serviceName"; Changed = $changed; RestartRequired = $false }
}
}
}
function RestartGuest($vmName, $credential, $bootTimeBefore, $timeoutSeconds = 600) {
Write-Host "Configured: restarting VM to apply RDP policy"
try {
Invoke-Command -VMName $vmName -Credential $credential -ScriptBlock { Restart-Computer -Force } -ErrorAction Stop | Out-Null
} catch {
}
$deadline = (Get-Date).AddSeconds($timeoutSeconds)
$restartDeadline = (Get-Date).AddSeconds(30)
$unavailable = $false
while ((Get-Date) -lt $deadline) {
Start-Sleep -Seconds 5
try {
$bootTimeAfter = [string](GuestBootTime $vmName $credential)
if ($bootTimeAfter -ne $bootTimeBefore) { return }
if (-not $unavailable -and (Get-Date) -ge $restartDeadline) {
throw "VM '$vmName' did not begin restarting within 30 seconds."
}
} catch {
if ($_.Exception.Message -like "VM '$vmName' did not begin restarting*") { throw }
$unavailable = $true
}
}
throw "VM '$vmName' did not complete a verified restart within $timeoutSeconds seconds."
}
AssertKnownArguments
$configPath = ArgValue "config"
if ([string]::IsNullOrWhiteSpace($configPath)) {
throw "Usage: .\enable-av-redirection.ps1 --config config\windows.json"
}
$configPath = FullPath $configPath
$cfg = Get-Content -Raw -LiteralPath $configPath | ConvertFrom-Json
@{
vmName = "WorkstationW11"
baseDir = "~/VMs/WorkstationW11"
}.GetEnumerator() | ForEach-Object { Default $cfg $_.Key $_.Value }
if ($null -eq $cfg.avRedirection -or -not [bool]$cfg.avRedirection.enabled) {
throw "Set avRedirection.enabled to true in '$configPath' before running this helper."
}
$credential = GuestCredential (FullPath $cfg.baseDir)
EnsureVmRunning $cfg.vmName $credential
$bootTimeBefore = [string](GuestBootTime $cfg.vmName $credential)
$results = @(ConfigureGuest $cfg.vmName $credential)
foreach ($result in $results) {
$prefix = if ([bool]$result.Changed) { "Configured" } else { "Already configured" }
Write-Host "${prefix}: $($result.Label)"
}
if (@($results | Where-Object { [bool]$_.RestartRequired }).Count -gt 0) {
RestartGuest $cfg.vmName $credential $bootTimeBefore
WaitForGuest $cfg.vmName $credential
} else {
Write-Host "Already configured: guest restart not required"
}
$writer = Join-Path $PSScriptRoot "write-rdp-file.ps1"
& $writer --config $configPath
Write-Host "RDP audio, microphone and all cameras are ready for VM '$($cfg.vmName)'."