-
Notifications
You must be signed in to change notification settings - Fork 253
/
Copy pathPowerRemoteDesktop_Viewer.psm1
2213 lines (1792 loc) · 72.4 KB
/
PowerRemoteDesktop_Viewer.psm1
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#-------------------------------------------------------------------------------
Power Remote Desktop
In loving memory of my father.
Thanks for all you've done.
you will remain in my heart forever.
.Developer
Jean-Pierre LESUEUR (@DarkCoderSc)
https://www.twitter.com/darkcodersc
https://github.com/DarkCoderSc
www.phrozen.io
jplesueur@phrozen.io
PHROZEN
.License
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
.Disclaimer
We are doing our best to prepare the content of this app. However, PHROZEN SASU and / or
Jean-Pierre LESUEUR cannot warranty the expressions and suggestions of the contents,
as well as its accuracy. In addition, to the extent permitted by the law,
PHROZEN SASU and / or Jean-Pierre LESUEUR shall not be responsible for any losses
and/or damages due to the usage of the information on our app.
By using our app, you hereby consent to our disclaimer and agree to its terms.
Any links contained in our app may lead to external sites are provided for
convenience only. Any information or statements that appeared in these sites
or app are not sponsored, endorsed, or otherwise approved by PHROZEN SASU and / or
Jean-Pierre LESUEUR. For these external sites, PHROZEN SASU and / or Jean-Pierre LESUEUR
cannot be held liable for the availability of, or the content located on or through it.
Plus, any losses or damages occurred from using these contents or the internet
generally.
-------------------------------------------------------------------------------#>
Add-Type -Assembly System.Windows.Forms
Add-Type @"
using System;
using System.Runtime.InteropServices;
public static class User32
{
[DllImport("User32.dll")]
public static extern bool SetProcessDPIAware();
}
"@
$global:PowerRemoteDesktopVersion = "4.0.0"
$global:HostSyncHash = [HashTable]::Synchronized(@{
host = $host
ClipboardText = (Get-Clipboard -Raw)
})
$global:EphemeralTrustedServers = @()
$global:LocalStoragePath = "HKCU:\SOFTWARE\PowerRemoteDesktop_Viewer"
$global:LocalStoragePath_TrustedServers = -join($global:LocalStoragePath, "\TrustedServers")
enum ClipboardMode {
Disabled = 1
Receive = 2
Send = 3
Both = 4
}
enum ProtocolCommand {
Success = 1
Fail = 2
RequestSession = 3
AttachToSession = 4
BadRequest = 5
ResourceFound = 6
ResourceNotFound = 7
LogonUIAccessDenied = 8
LogonUIWrongSession = 9
}
enum WorkerKind {
Desktop = 1
Events = 2
}
enum BlockSize {
Size32 = 32
Size64 = 64
Size96 = 96
Size128 = 128
Size256 = 256
Size512 = 512
}
enum PacketSize {
Size1024 = 1024
Size2048 = 2048
Size4096 = 4096
Size8192 = 8192
Size9216 = 9216
Size12288 = 12288
Size16384 = 16384
}
function Write-Banner
{
<#
.SYNOPSIS
Output cool information about current PowerShell module to terminal.
#>
Write-Host ""
Write-Host "Power Remote Desktop - Version " -NoNewLine
Write-Host $global:PowerRemoteDesktopVersion -ForegroundColor Cyan
Write-Host "Jean-Pierre LESUEUR (" -NoNewLine
Write-Host "@DarkCoderSc" -NoNewLine -ForegroundColor Green
Write-Host ") " -NoNewLine
Write-Host "#" -NoNewLine -ForegroundColor Blue
Write-Host "#" -NoNewLine -ForegroundColor White
Write-Host "#" -ForegroundColor Red
Write-Host "https://" -NoNewLine -ForegroundColor Green
Write-Host "www.github.com/darkcodersc"
Write-Host "https://" -NoNewLine -ForegroundColor Green
Write-Host "www.phrozen.io"
Write-Host ""
Write-Host "License: Apache License (Version 2.0, January 2004)"
Write-Host "https://" -NoNewLine -ForegroundColor Green
Write-Host "www.apache.org/licenses/"
Write-Host ""
}
function Get-BooleanAnswer
{
<#
.SYNOPSIS
As user to make a boolean choice. Return True if Y and False if N.
#>
while ($true)
{
$choice = Read-Host "[Y] Yes [N] No (Default is ""N"")"
if (-not $choice)
{
$choice = "N"
}
switch ($choice)
{
"Y"
{
return $true
}
"N"
{
return $false
}
default
{
Write-Host "Invalid Answer, available options are ""Y , N""" -ForegroundColor Red
}
}
}
}
function New-RegistryStorage
{
<#
.SYNOPSIS
Create required registry keys for storing persistent data between viewer
sessions.
.DESCRIPTION
Users doesn't share this storage. If you really wish to, replace HKCU by HKLM (Requires Admin Privilege)
#>
try
{
if (-not (Test-Path -Path $global:LocalStoragePath))
{
Write-Verbose "Create local storage root at ""${global:LocalStoragePath}""..."
New-Item -Path $global:LocalStoragePath
}
if (-not (Test-Path -Path $global:LocalStoragePath_TrustedServers))
{
Write-Verbose "Create local storage child: ""${global:LocalStoragePath}""..."
New-Item -Path $global:LocalStoragePath_TrustedServers
}
}
catch
{
Write-Verbose "Could not write server fingerprint to local storage with error: ""$($_)"""
}
}
function Write-ServerFingerprintToLocalStorage
{
<#
.SYNOPSIS
Write a trusted server certificate fingerprint to our local storage.
.PARAMETER Fingerprint
Type: String
Default: None
Description: Fingerprint to store in local storage.
#>
param (
[Parameter(Mandatory=$True)]
[string] $Fingerprint
)
New-RegistryStorage
# Value is stored as a JSON Object to be easily upgraded and extended in future.
$value = New-Object -TypeName PSCustomObject -Property @{
FirstSeen = (Get-Date).ToString()
}
New-ItemProperty -Path $global:LocalStoragePath_TrustedServers -Name $Fingerprint -PropertyType "String" -Value ($value | ConvertTo-Json -Compress) -ErrorAction Ignore
}
function Remove-TrustedServer
{
<#
.SYNOPSIS
Remove trusted server from local storage.
.PARAMETER Fingerprint
Type: String
Default: None
Description: Fingerprint to remove from local storage.
#>
param (
[Parameter(Mandatory=$True)]
[string] $Fingerprint
)
if (-not (Test-ServerFingerprintFromLocalStorage -Fingerprint $Fingerprint))
{
throw "Could not find fingerprint on trusted server list."
}
Write-Host "You are about to permanently delete trusted server -> """ -NoNewline
Write-Host $Fingerprint -NoNewLine -ForegroundColor Green
Write-Host """"
Write-Host "Are you sure ?"
if (Get-BooleanAnswer)
{
Remove-ItemProperty -Path $global:LocalStoragePath_TrustedServers -Name $Fingerprint
Write-Host "Server successfully untrusted."
}
}
function Get-TrustedServers
{
<#
.SYNOPSIS
Return a list of trusted servers fingerprints from local storage.
#>
$list = @()
Get-Item -Path $global:LocalStoragePath_TrustedServers -ErrorAction Ignore | Select-Object -ExpandProperty Property | ForEach-Object {
try
{
$list += New-Object -TypeName PSCustomObject -Property @{
Fingerprint = $_
Detail = (Get-ItemPropertyValue -Path $global:LocalStoragePath_TrustedServers -Name $_) | ConvertFrom-Json
}
}
catch
{ }
}
return $list
}
function Clear-TrustedServers
{
<#
.SYNOPSIS
Remove all trusted servers from local storage.
#>
$trustedServers = Get-TrustedServers
if (@($trustedServers).Length -eq 0)
{
throw "No trusted servers so far."
}
Write-Host "You are about to permanently delete $(@(trustedServers).Length) trusted servers."
Write-Host "Are you sure ?"
if (Get-BooleanAnswer)
{
Remove-Item -Path $global:LocalStoragePath_TrustedServers -Force -Verbose
Write-Host "Servers successfully untrusted."
}
}
function Test-ServerFingerprintFromLocalStorage
{
<#
.SYNOPSIS
Check if a server certificate fingerprint was saved to local storage.
.PARAMETER Fingerprint
Type: String
Default: None
Description: Fingerprint to check in local storage.
#>
param (
[Parameter(Mandatory=$True)]
[string] $Fingerprint
)
return (Get-ItemProperty -Path $global:LocalStoragePath_TrustedServers -Name $Fingerprint -ErrorAction Ignore)
}
function Get-SHA512FromString
{
<#
.SYNOPSIS
Return the SHA512 value from string.
.PARAMETER String
Type: String
Default : None
Description: A String to hash.
.EXAMPLE
Get-SHA512FromString -String "Hello, World"
#>
param (
[Parameter(Mandatory=$True)]
[string] $String
)
$buffer = [IO.MemoryStream]::new([byte[]][char[]]$String)
return (Get-FileHash -InputStream $buffer -Algorithm SHA512).Hash
}
function Resolve-AuthenticationChallenge
{
<#
.SYNOPSIS
Algorithm to solve the server challenge during password authentication.
.DESCRIPTION
Server needs to resolve the challenge and keep the solution in memory before sending
the candidate to remote peer.
.PARAMETER Password
Type: SecureString
Default: None
Description: Secure String object containing the password for resolving challenge.
.PARAMETER Candidate
Type: String
Default: None
Description:
Random string used to solve the challenge. This string is public and is set across network by server.
Each time a new connection is requested to server, a new candidate is generated.
.EXAMPLE
Resolve-AuthenticationChallenge -Password "s3cr3t!" -Candidate "rKcjdh154@]=Ldc"
#>
param (
[Parameter(Mandatory=$True)]
[SecureString] $SecurePassword,
[Parameter(Mandatory=$True)]
[string] $Candidate
)
$BSTR = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
try
{
$solution = -join($Candidate, ":", [Runtime.InteropServices.Marshal]::PtrToStringBSTR($BSTR))
for ([int] $i = 0; $i -le 1000; $i++)
{
$solution = Get-SHA512FromString -String $solution
}
return $solution
}
finally
{
[Runtime.InteropServices.Marshal]::FreeBSTR($BSTR)
}
}
class ClientIO {
[string] $RemoteAddress
[int] $RemotePort
[bool] $UseTLSv1_3
[System.Net.Sockets.TcpClient] $Client = $null
[System.Net.Security.SslStream] $SSLStream = $null
[System.IO.StreamWriter] $Writer = $null
[System.IO.StreamReader] $Reader = $null
[System.IO.BinaryReader] $BinaryReader = $null
ClientIO(
[string] $RemoteAddress = "127.0.0.1",
[int] $RemotePort = 2801,
[bool] $UseTLSv1_3 = $false
) {
$this.RemoteAddress = $RemoteAddress
$this.RemotePort = $RemotePort
$this.UseTLSv1_3 = $UseTLSv1_3
}
[void]Connect() {
<#
.SYNOPSIS
Open a new connection to remote server.
Create required streams and open a new secure connection with peer.
#>
Write-Verbose "Connect: ""$($this.RemoteAddress):$($this.RemotePort)..."""
$this.Client = New-Object System.Net.Sockets.TcpClient($this.RemoteAddress, $this.RemotePort)
Write-Verbose "Connected."
if ($this.UseTLSv1_3)
{
$TLSVersion = [System.Security.Authentication.SslProtocols]::TLS13
}
else {
$TLSVersion = [System.Security.Authentication.SslProtocols]::TLS12
}
Write-Verbose "Establish an encrypted tunnel using: ${TLSVersion}..."
$this.SSLStream = New-object System.Net.Security.SslStream(
$this.Client.GetStream(),
$false,
{
param(
$Sendr,
$Certificate,
$Chain,
$Policy
)
if (
(Test-ServerFingerprintFromLocalStorage -Fingerprint $Certificate.Thumbprint) -or
$global:EphemeralTrustedServers -contains $Certificate.Thumbprint
)
{
Write-Verbose "Fingerprint already known and trusted: ""$($Certificate.Thumbprint)"""
return $true
}
else
{
Write-Verbose "@Remote Server Certificate:"
Write-Verbose $Certificate
Write-Verbose "---"
Write-Host "Untrusted Server Certificate Fingerprint: """ -NoNewLine
Write-Host $Certificate.Thumbprint -NoNewline -ForegroundColor Green
Write-Host """"
while ($true)
{
Write-Host "`r`nDo you want to trust current server ?"
$choice = Read-Host "[A] Always [Y] Yes [N] No [?] Help (Default is ""N"")"
if (-not $choice)
{
$choice = "N"
}
switch ($choice)
{
"?"
{
Write-Host ""
Write-Host "[" -NoNewLine
Write-Host "A" -NoNewLine -ForegroundColor Cyan
Write-Host "] Always trust current server (Persistent between PowerShell Instances)"
Write-Host "[" -NoNewLine
Write-Host "Y" -NoNewLine -ForegroundColor Cyan
Write-Host "] Trust current server during current PowerShell Instance lifetime (Temporary)."
Write-Host "[" -NoNewLine
Write-Host "N" -NoNewLine -ForegroundColor Cyan
Write-Host "] Don't trust current server. Connection is aborted (Recommeneded if you don't recognize server fingerprint)."
Write-Host "[" -NoNewLine
Write-Host "?" -NoNewLine -ForegroundColor Cyan
Write-Host "] Current help output."
Write-Host ""
}
"A"
{
Write-ServerFingerprintToLocalStorage -Fingerprint $Certificate.Thumbprint
return $true
}
"Y"
{
$global:EphemeralTrustedServers += $Certificate.Thumbprint
return $true
}
"N"
{
return $false
}
default
{
Write-Host "Invalid Answer, available options are ""A , Y , N , H""" -ForegroundColor Red
}
}
}
}
}
)
$this.SSLStream.AuthenticateAsClient(
"PowerRemoteDesktop",
$null,
$TLSVersion,
$null
)
if (-not $this.SSLStream.IsEncrypted)
{
throw "Could not establish a secure communication channel with remote server."
}
$this.SSLStream.WriteTimeout = 5000
$this.Writer = New-Object System.IO.StreamWriter($this.SSLStream)
$this.Writer.AutoFlush = $true
$this.Reader = New-Object System.IO.StreamReader($this.SSLStream)
$this.BinaryReader = New-Object System.IO.BinaryReader($this.SSLStream)
Write-Verbose "Encrypted tunnel opened and ready for use."
}
[void]Authentify([SecureString] $SecurePassword) {
<#
.SYNOPSIS
Handle authentication process with remote peer.
.PARAMETER Password
Type: SecureString
Default: None
Description: Secure String object containing the password.
.EXAMPLE
.Authentify((ConvertTo-SecureString -String "urCompl3xP@ssw0rd" -AsPlainText -Force))
#>
Write-Verbose "Authentify with remote server (Challenged-Based Authentication)..."
$candidate = $this.Reader.ReadLine()
$challengeSolution = Resolve-AuthenticationChallenge -Candidate $candidate -SecurePassword $SecurePassword
Write-Verbose "@Challenge:"
Write-Verbose "Candidate: ""${candidate}"""
Write-Verbose "Solution: ""${challengeSolution}"""
Write-Verbose "---"
$this.Writer.WriteLine($challengeSolution)
$result = $this.Reader.ReadLine()
if ($result -eq [ProtocolCommand]::Success)
{
Write-Verbose "Solution accepted. Authentication success."
}
else
{
throw "Solution declined. Authentication failed."
}
}
[string] RemoteAddress() {
return $this.Client.Client.RemoteEndPoint.Address
}
[int] RemotePort() {
return $this.Client.Client.RemoteEndPoint.Port
}
[string] LocalAddress() {
return $this.Client.Client.LocalEndPoint.Address
}
[int] LocalPort() {
return $this.Client.Client.LocalEndPoint.Port
}
[string] ReadLine([int] $Timeout)
{
<#
.SYNOPSIS
Read string message from remote peer with timeout support.
.PARAMETER Timeout
Type: Integer
Description: Maximum period of time to wait for incomming data.
#>
$defautTimeout = $this.SSLStream.ReadTimeout
try
{
$this.SSLStream.ReadTimeout = $Timeout
return $this.Reader.ReadLine()
}
finally
{
$this.SSLStream.ReadTimeout = $defautTimeout
}
}
[string] ReadLine()
{
<#
.SYNOPSIS
Shortcut to Reader ReadLine method. No timeout support.
#>
return $this.Reader.ReadLine()
}
[void] WriteJson([PSCustomObject] $Object)
{
<#
.SYNOPSIS
Transform a PowerShell Object as a JSON Representation then send to remote
peer.
.PARAMETER Object
Type: PSCustomObject
Description: Object to be serialized in JSON.
#>
$this.Writer.WriteLine(($Object | ConvertTo-Json -Compress))
}
[void] WriteLine([string] $Value)
{
$this.Writer.WriteLine($Value)
}
[PSCustomObject] ReadJson([int] $Timeout)
{
<#
.SYNOPSIS
Read json string from remote peer and attempt to deserialize as a PowerShell Object.
.PARAMETER Timeout
Type: Integer
Description: Maximum period of time to wait for incomming data.
#>
return ($this.ReadLine($Timeout) | ConvertFrom-Json)
}
[PSCustomObject] ReadJson()
{
<#
.SYNOPSIS
Alternative to ReadJson without timeout support.
#>
return ($this.ReadLine() | ConvertFrom-Json)
}
[void]Close() {
<#
.SYNOPSIS
Release Streams and Connections.
#>
if ($this.Writer)
{
$this.Writer.Close()
}
if ($this.Reader)
{
$this.Reader.Close()
}
if ($this.BinaryReader)
{
$this.BinaryReader.Close()
}
if ($this.SSLStream)
{
$this.SSLStream.Close()
}
if ($this.Client)
{
$this.Client.Close()
}
}
}
class ViewerConfiguration
{
[bool] $RequireResize = $false
[int] $RemoteDesktopWidth = 0
[int] $RemoteDesktopHeight = 0
[int] $VirtualDesktopWidth = 0
[int] $VirtualDesktopHeight = 0
[int] $ScreenX_Delta = 0
[int] $ScreenY_Delta = 0
[float] $ScreenX_Ratio = 1
[float] $ScreenY_Ratio = 1
}
class ViewerSession
{
[PSCustomObject] $ServerInformation = $null
[ViewerConfiguration] $ViewerConfiguration = $null
[string] $ServerAddress = "127.0.0.1"
[string] $ServerPort = 2801
[SecureString] $SecurePassword = $null
[bool] $UseTLSv1_3 = $false
[int] $ImageCompressionQuality = 100
[int] $ResizeRatio = 0
[PacketSize] $PacketSize = [PacketSize]::Size9216
[BlockSize] $BlockSize = [BlockSize]::Size64
[bool] $LogonUI = $false
[ClientIO] $ClientDesktop = $null
[ClientIO] $ClientEvents = $null
ViewerSession(
[string] $ServerAddress,
[int] $ServerPort,
[SecureString] $SecurePassword
)
{
# Or: System.Management.Automation.Runspaces.MaxPort (High(Word))
if ($ServerPort -lt 0 -and $ServerPort -gt 65535)
{
throw "Invalid TCP Port (0-65535)"
}
$this.ServerAddress = $ServerAddress
$this.ServerPort = $ServerPort
$this.SecurePassword = $SecurePassword
}
[void] OpenSession() {
<#
.SYNOPSIS
Request a new session with remote server.
#>
Write-Verbose "Request new session with remote server: ""$($this.ServerAddress):$($this.ServerPort)""..."
if ($this.ServerInformation)
{
throw "A session already exists."
}
Write-Verbose "Establish first contact with remote server..."
$client = [ClientIO]::New($this.ServerAddress, $this.ServerPort, $this.UseTLSv1_3)
try
{
$client.Connect()
$client.Authentify($this.SecurePassword)
Write-Verbose "Request session..."
$client.WriteLine(([ProtocolCommand]::RequestSession))
$this.ServerInformation = $client.ReadJson()
Write-Verbose "@ServerInformation:"
Write-Verbose $this.ServerInformation
Write-Verbose "---"
if (
(-not ($this.ServerInformation.PSobject.Properties.name -contains "SessionId")) -or
(-not ($this.ServerInformation.PSobject.Properties.name -contains "Version")) -or
(-not ($this.ServerInformation.PSobject.Properties.name -contains "ViewOnly")) -or
(-not ($this.ServerInformation.PSobject.Properties.name -contains "MachineName")) -or
(-not ($this.ServerInformation.PSobject.Properties.name -contains "Username")) -or
(-not ($this.ServerInformation.PSobject.Properties.name -contains "WindowsVersion")) -or
(-not ($this.ServerInformation.PSobject.Properties.name -contains "Screens"))
)
{
throw "Invalid server information object."
}
Write-Verbose "Server informations acknowledged, prepare and send our expectation..."
if ($this.ServerInformation.Version -ne $global:PowerRemoteDesktopVersion)
{
throw "Server and Viewer version mismatch.`r`n`
Local: ""${global:PowerRemoteDesktopVersion}""`r`n`
Remote: ""$($this.ServerInformation.Version)""`r`n`
You cannot use two different version between Viewer and Server."
}
if ($this.ServerInformation.ViewOnly)
{
Write-Host "You are accessing a read-only desktop." -ForegroundColor Cyan
}
# Define which screen we want to capture
$selectedScreen = $null
if ($this.ServerInformation.Screens.Length -gt 1)
{
Write-Verbose "Remote server have $($this.ServerInformation.Screens.Length) screens."
Write-Host "Remote server have " -NoNewLine
Write-Host $($this.ServerInformation.Screens.Length) -NoNewLine -ForegroundColor Green
Write-Host " different screens:`r`n"
foreach ($screen in $this.ServerInformation.Screens)
{
Write-Host $screen.Id -NoNewLine -ForegroundColor Cyan
Write-Host " - $($screen.Name)" -NoNewLine
if ($screen.Primary)
{
Write-Host " (" -NoNewLine
Write-Host "Primary" -NoNewLine -ForegroundColor Cyan
Write-Host ")" -NoNewLine
}
Write-Host ""
}
while ($true)
{
$choice = Read-Host "`r`nPlease choose which screen index to capture (Default: Primary)"
if (-not $choice)
{
# Select-Object -First 1 should also grab the Primary Screen (Since it is ordered).
$selectedScreen = $this.ServerInformation.Screens | Where-Object -FilterScript { $_.Primary -eq $true }
}
else
{
if (-not $choice -is [int]) {
Write-Host "You must enter a valid index (integer), starting at 1."
continue
}
$selectedScreen = $this.ServerInformation.Screens | Where-Object -FilterScript { $_.Id -eq $choice }
if (-not $selectedScreen)
{
Write-Host "Invalid choice, please choose an existing screen index." -ForegroundColor Red
}
}
if ($selectedScreen)
{
break
}
}
}
else
{
$selectedScreen = $this.ServerInformation.Screens | Select-Object -First 1
}
# Define our Virtual Desktop Form constraints
$localScreenWidth = Get-LocalScreenWidth
$localScreenHeight = (Get-LocalScreenHeight) - (Get-WindowCaptionHeight)
$this.ViewerConfiguration = [ViewerConfiguration]::New()
$this.ViewerConfiguration.RemoteDesktopWidth = $selectedScreen.Width
$this.ViewerConfiguration.RemoteDesktopHeight = $selectedScreen.Height
# If remote screen is bigger than local screen, we will resize remote screen to fit 90% of local screen.
# Supports screen orientation (Horizontal / Vertical)
if ($localScreenWidth -le $selectedScreen.Width -or $localScreenHeight -le $selectedScreen.Height)
{
$adjustRatio = 90
$adjustVertically = $localScreenWidth -gt $localScreenHeight
if ($adjustVertically)
{
$this.ViewerConfiguration.VirtualDesktopWidth = [math]::Round(($localScreenWidth * $adjustRatio) / 100)
$remoteResizedRatio = [math]::Round(($this.ViewerConfiguration.VirtualDesktopWidth * 100) / $selectedScreen.Width)
$this.ViewerConfiguration.VirtualDesktopHeight = [math]::Round(($selectedScreen.Height * $remoteResizedRatio) / 100)
}
else
{
$this.ViewerConfiguration.VirtualDesktopHeight = [math]::Round(($localScreenHeight * $adjustRatio) / 100)
$remoteResizedRatio = [math]::Round(($this.ViewerConfiguration.VirtualDesktopHeight * 100) / $selectedScreen.Height)
$this.ViewerConfiguration.VirtualDesktopWidth = [math]::Round(($selectedScreen.Width * $remoteResizedRatio) / 100)
}
}
else
{
$this.ViewerConfiguration.VirtualDesktopWidth = $selectedScreen.Width
$this.ViewerConfiguration.VirtualDesktopHeight = $selectedScreen.Height
}
# If remote desktop resize is forced, we apply defined ratio to current configuration
if ($this.ResizeRatio -ge 30 -and $this.ResizeRatio -le 99)
{
$this.ViewerConfiguration.VirtualDesktopWidth = ($selectedScreen.Width * $this.ResizeRatio) / 100
$this.ViewerConfiguration.VirtualDesktopHeight = ($selectedScreen.Height * $this.ResizeRatio) / 100
}
$this.ViewerConfiguration.RequireResize = $this.ViewerConfiguration.VirtualDesktopWidth -ne $selectedScreen.Width -or
$this.ViewerConfiguration.VirtualDesktopHeight -ne $selectedScreen.Height
$this.ViewerConfiguration.ScreenX_Delta = $selectedScreen.X
$this.ViewerConfiguration.ScreenY_Delta = $selectedScreen.Y
if ($this.ViewerConfiguration.RequireResize)
{
$this.ViewerConfiguration.ScreenX_Ratio = $selectedScreen.Width / $this.ViewerConfiguration.VirtualDesktopWidth
$this.ViewerConfiguration.ScreenY_Ratio = $selectedScreen.Height / $this.ViewerConfiguration.VirtualDesktopHeight
}
$viewerExpectation = New-Object PSCustomObject -Property @{
ScreenName = $selectedScreen.Name
ImageCompressionQuality = $this.ImageCompressionQuality
PacketSize = $this.PacketSize
BlockSize = $this.BlockSize
LogonUI = $this.LogonUI
}
Write-Verbose "@ViewerExpectation:"
Write-Verbose $viewerExpectation
Write-Verbose "---"
$client.WriteJson($viewerExpectation)
switch ([ProtocolCommand] $client.ReadLine(5 * 1000))
{
([ProtocolCommand]::Success)
{
break
}
([ProtocolCommand]::LogonUIAccessDenied)
{
throw "Could not access LogonUI / Winlogon desktop.`r`n" +
"To access LogonUI desktop, you must have ""NT AUTHORITY/System"" privilege in current active session."
break
}
([ProtocolCommand]::LogonUIWrongSession)
{
throw "Could not access LogonUI / Winlogon desktop.`r`n"
"To access LogonUI desktop, server process must be running under active Windows Session."
break
}
default
{
throw "Remote server did not acknoledged our expectation in time."
}
}
}
catch