-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathsafeguard-ps.psm1
2048 lines (1835 loc) · 75 KB
/
safeguard-ps.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
# Global session variable for login information, including SPS
Remove-Variable -Name "SafeguardSession" -Scope Global -ErrorAction "SilentlyContinue"
New-Variable -Name "SafeguardSession" -Scope Global -Value $null
Remove-Variable -Name "SafeguardSpsSession" -Scope Global -ErrorAction "SilentlyContinue"
New-Variable -Name "SafeguardSpsSession" -Scope Global -Value $null
$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
Set-Variable -Name "SafeguardSession" -Scope Global -Value $null -ErrorAction "SilentlyContinue"
Set-Variable -Name "SafeguardSpsSession" -Scope Global -Value $null -ErrorAction "SilentlyContinue"
}
Edit-SslVersionSupport
function Get-SessionConnectionIdentifier
{
[CmdletBinding()]
Param(
)
if (-not $SafeguardSession)
{
"Not Connected"
}
else
{
if ($SafeguardSession["Gui"])
{
"$($SafeguardSession["Appliance"]) (GUI)"
}
else
{
$local:Identifier = "$($SafeguardSession["Appliance"]) ($($SafeguardSession["IdentityProvider"])"
if (($SafeguardSession["IdentityProvider"]) -ieq "certificate")
{
if ($SafeguardSession["Thumbprint"])
{
$local:Identifier = "$($local:Identifier)\$($SafeguardSession["Thumbprint"]))"
}
else
{
$local:Identifier = "$($local:Identifier)\$($SafeguardSession["CertificateFile"]))"
}
}
else
{
$local:Identifier = "$($local:Identifier)\$($SafeguardSession["Username"]))"
}
$local:Identifier
}
}
}
function Get-RstsTokenFromBrowser
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Appliance,
[Parameter(Mandatory=$false,Position=1)]
[string]$Username = "",
[Parameter(Mandatory=$false,Position=2)]
[int]$Port = 8400
)
if (-not $PSBoundParameters.ContainsKey("ErrorAction")) { $ErrorActionPreference = "Stop" }
if (-not $PSBoundParameters.ContainsKey("Verbose")) { $VerbosePreference = $PSCmdlet.GetVariableValue("VerbosePreference") }
if (-not ([System.Management.Automation.PSTypeName]"RstsAccessTokenExtractor").Type)
{
Write-Verbose "Adding the PSType for RstsAccessTokenExtractor"
if ($PSVersionTable.PSEdition -eq "Core")
{
$local:Assemblies = ("System.Web.dll","System.Net.Primitives.dll","System.Net.Sockets.dll","System.Text.RegularExpressions.dll",
"System.Web.HttpUtility.dll","System.Diagnostics.Process.dll","System.ComponentModel.Primitives.dll",
"System.Runtime.InteropServices.RuntimeInformation.dll","System.Collections.Specialized","System.Console.dll","System.Security.Cryptography.dll")
}
else
{
$local:Assemblies = ("System.Web.dll","System.Net.Primitives.dll","System.Net.Sockets.dll","System.Text.RegularExpressions.dll",
"System.Diagnostics.Process.dll","System.ComponentModel.Primitives.dll",
"System.Runtime.InteropServices.RuntimeInformation.dll","System.Collections.Specialized","System.Security.Cryptography.dll")
}
Add-Type -ReferencedAssemblies $local:Assemblies -TypeDefinition @"
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
public class RstsAccessTokenExtractor {
private readonly string _appliance;
public RstsAccessTokenExtractor(string appliance) { _appliance = appliance; }
public string AuthorizationCode { get; set; }
public string CodeVerifier { get; set; }
public string Error { get; set; }
public bool Show(string username = "", int port = 8400) {
var tcpListener = new TcpListener(IPAddress.Loopback, port);
tcpListener.Start();
try {
CodeVerifier = OAuthCodeVerifier();
string redirectUri = "urn:InstalledApplicationTcpListener";
string accessTokenUri = $"https://{_appliance}/RSTS/Login?response_type=code&code_challenge_method=S256&code_challenge={OAuthCodeChallenge(CodeVerifier)}&redirect_uri={redirectUri}&port={port}";
if (!string.IsNullOrEmpty(username)) redirectUri += string.Format("&login_hint={0}", Uri.EscapeDataString(username));
try {
var psi = new ProcessStartInfo { FileName = accessTokenUri, UseShellExecute = true };
Process.Start(psi);
}
catch {
// hack because of this: https://github.com/dotnet/corefx/issues/10361
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
accessTokenUri = accessTokenUri.Replace("&", "^&");
Process.Start(new ProcessStartInfo("cmd", "/c start " + accessTokenUri) { CreateNoWindow = true });
} else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
Process.Start("xdg-open", accessTokenUri);
} else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
Process.Start("open", accessTokenUri);
}
else { throw; }
}
}
catch (System.Exception) {
throw;
}
var source = new CancellationTokenSource();
Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => {
source.Cancel();
};
try {
var listenTask = tcpListener.AcceptTcpClientAsync().ContinueWith<Task<string>>(async t => {
if (t.IsFaulted || t.IsCanceled) return null;
var tcpClient = t.Result;
using (var networkStream = tcpClient.GetStream())
{
var readBuffer = new byte[1024];
var sb = new StringBuilder();
do {
var numberOfBytesRead = await networkStream.ReadAsync(readBuffer, 0, readBuffer.Length, source.Token).ConfigureAwait(false);
var s = Encoding.ASCII.GetString(readBuffer, 0, numberOfBytesRead);
sb.Append(s);
} while (networkStream.DataAvailable);
var fullResponse = "HTTP/1.1 200 OK\r\n\r\n<html><head><title>Authentication Complete</title></head><body><h2>Authentication complete.</h2><p>You can return to PowerShell.</p><p>Feel free to close this browser tab.</p></body></html>\r\n";
var response = Encoding.ASCII.GetBytes(fullResponse);
await networkStream.WriteAsync(response, 0, response.Length, source.Token);
await networkStream.FlushAsync();
return sb.ToString();
}
});
listenTask.Wait(source.Token);
var innerTask = listenTask.Result;
if (innerTask != null) {
innerTask.Wait(source.Token);
if (!innerTask.IsFaulted && innerTask.Result != null)
AuthorizationCode = HttpUtility.ParseQueryString(ExtractUriFromHttpRequest(innerTask.Result)).Get("oauth");
else if (innerTask.Result != null)
Error = innerTask.Result;
else
Error = "No HTTP redirect";
}
return true;
}
finally {
tcpListener.Stop();
}
}
private string OAuthCodeVerifier()
{
var bytes = new byte[60];
RandomNumberGenerator.Create().GetBytes(bytes);
return ToBase64Url(bytes);
}
private string OAuthCodeChallenge(string codeVerifier)
{
using (var sha = SHA256.Create())
{
var hash = sha.ComputeHash(Encoding.ASCII.GetBytes(codeVerifier));
return ToBase64Url(hash);
}
}
// https://172.21.21.1/RSTS/Login?
// response_type=code&
// redirect_uri=https%3a%2f%2flocalhost%3a7035%2f%3fserver%3d172.21.21.1%26auth%3dresume&
// code_challenge=Ullteua8nkpbqkCUpKSxqPfTqrZvZfnmpV3YTGEPUfQ&
// code_challenge_method=S256&
// state=w5mtmJUPPMhHEW-qo4PyyX4pGDsevgTN2QNRC0aWiaxd8weEQdgiHoieLe4NDeuAkL63Q6-ipG1nIOwY
/// <summary>Creates a Base64 string with the trailing equal signs removed and any plus signs replaced with
/// minus signs and any forward slashes replaced with underscores.</summary>
/// <param name="data">Any byte array to be Base64 encoded.</param>
/// <returns>A special Base64 string that is URL safe. Used in JWTs, OAuth2.0 and other things.</returns>
private string ToBase64Url(byte[] data)
{
return Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
private string ExtractUriFromHttpRequest(string httpRequest) {
string regexp = @"GET \/\?(.*) HTTP";
Regex r1 = new Regex(regexp);
Match match = r1.Match(httpRequest);
if (!match.Success) { throw new InvalidOperationException("Not a GET query"); }
return match.Groups[1].Value;
}
}
"@
}
if (-not $global:Browser)
{
$local:Browser = New-Object -TypeName RstsAccessTokenExtractor -ArgumentList $Appliance
}
if (!$local:Browser.Show($Username, $Port))
{
throw "Unable to correctly manipulate browser"
}
if (-not $local:Browser.AuthorizationCode)
{
throw "Unable to obtain authorization code"
}
try
{
Write-Verbose "Redeeming RSTS authorization code..."
$local:RstsResponse = (Invoke-RestMethod -Method POST -Headers @{
"Accept" = "application/json";
"Content-type" = "application/json"
} -Uri "https://$Appliance/RSTS/oauth2/token" -Body ([System.Text.Encoding]::UTF8.GetBytes(@"
{
"grant_type": "authorization_code",
"redirect_uri": "urn:InstalledApplication",
"code": "$($local:Browser.AuthorizationCode)",
"code_verifier": "$($local:Browser.CodeVerifier)"
}
"@)))
}
catch
{
throw "Unable to obtain access token"
}
# Return as a hashtable object because other parts of the code later on will expect it.
@{access_token=$local:RstsResponse.access_token}
}
function Submit-RstsMultifactorPost
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Appliance,
[Parameter(Mandatory=$true,Position=1)]
[string]$PrimaryProviderId,
[Parameter(Mandatory=$true,Position=2)]
[string]$Username,
[Parameter(Mandatory=$true,Position=3)]
[securestring]$Password,
[Parameter(Mandatory=$true,Position=4)]
[object]$CsrfToken,
[Parameter(Mandatory=$false,Position=5)]
[string]$SecondaryAuthState,
[Parameter(Mandatory=$false,Position=6)]
[string]$SecondaryLogin
)
if (-not $PSBoundParameters.ContainsKey("ErrorAction")) { $ErrorActionPreference = "Stop" }
if (-not $PSBoundParameters.ContainsKey("Verbose")) { $VerbosePreference = $PSCmdlet.GetVariableValue("VerbosePreference") }
$local:PasswordPlainText = [System.Net.NetworkCredential]::new("", $Password).Password
$local:Response = (Invoke-RestMethod -Method POST "https://$Appliance/RSTS/UserLogin/LoginController?response_type=token&redirect_uri=urn%3aInstalledApplication&loginRequestStep=5" `
-WebSession $HttpSession -Headers @{ "Accept" = "application/json"; "Content-type" = "application/x-www-form-urlencoded" } -Body @{
directoryComboBox = "$PrimaryProviderId";
usernameTextbox = "$Username";
passwordTextbox = "$($local:PasswordPlainText)";
csrfTokenTextbox = "$CsrfToken";
secondaryAuthenticationStateTextbox = "$SecondaryAuthState";
secondaryLoginTextbox = "$SecondaryLogin"
})
$local:Response
}
function Submit-RstsMultiFactorCredential
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Appliance,
[Parameter(Mandatory=$true,Position=1)]
[string]$PrimaryProviderId,
[Parameter(Mandatory=$true,Position=2)]
[string]$Username,
[Parameter(Mandatory=$true,Position=3)]
[securestring]$Password,
[Parameter(Mandatory=$true,Position=4)]
[object]$CsrfToken
)
if (-not $PSBoundParameters.ContainsKey("ErrorAction")) { $ErrorActionPreference = "Stop" }
if (-not $PSBoundParameters.ContainsKey("Verbose")) { $VerbosePreference = $PSCmdlet.GetVariableValue("VerbosePreference") }
Import-Module -Name "$PSScriptRoot\ps-utilities.psm1" -Scope Local
# MFA preauthenticate
$local:PasswordPlainText = [System.Net.NetworkCredential]::new("", $Password).Password
$local:Response = (Invoke-RestMethod -Method POST "https://$Appliance/RSTS/UserLogin/LoginController?response_type=token&redirect_uri=urn%3aInstalledApplication&loginRequestStep=7" `
-WebSession $HttpSession -Headers @{ "Accept" = "application/json"; "Content-type" = "application/x-www-form-urlencoded" } -Body @{
directoryComboBox = "$PrimaryProviderId";
usernameTextbox = "$Username";
passwordTextbox = "$($local:PasswordPlainText)";
csrfTokenTextbox = "$CsrfToken"
})
$local:SecondaryAuthState = $local:Response.State
$local:Message = $local:Response.Message
$local:ShouldEcho = $local:Response.Echo
if ($local:ShouldEcho)
{
Write-Host $local:Message
}
# Looping is to handle push to authenticate
while ($local:SecondaryAuthState -or $local:SecondaryLogin)
{
$local:Response = (Submit-RstsMultifactorPost $Appliance $PrimaryProviderId $Username $Password $CsrfToken $local:SecondaryAuthState $local:SecondaryLogin)
$local:SecondaryAuthState = $local:Response.State
$local:Message = $local:Response.Message
$local:ShouldEcho = $local:Response.Echo
$local:SecondaryLogin = ""
if ($local:ShouldEcho)
{
Write-Host $local:Message
}
if ($local:SecondaryAuthState)
{
if ($local:SecondaryAuthState.StartsWith("DefenderCloudOneTouch:"))
{
Write-Host -NoNewline " Press any key to use OTP instead... "
Start-Sleep -Milliseconds 100;
$Host.UI.RawUI.FlushInputBuffer()
$local:i = 0;
while (-not $Host.UI.RawUI.KeyAvailable -and $local:i -lt 25)
{
Write-Host -NoNewline ("`r{0}" -f '/-\|'[($local:i++ % 4)]);
Start-Sleep -Milliseconds 200
}
if ($Host.UI.RawUI.KeyAvailable)
{
Write-Host "" # line feed to to not write prompt over top of previous message
$local:SecondaryAuthState = "UseOtpInstead"
$Host.UI.RawUI.FlushInputBuffer()
Start-Sleep -Milliseconds 100
}
else
{
Write-Host ""
}
}
elseif ($local:SecondaryAuthState -eq "ShowDefenderCloud")
{
$local:SecondaryAuthState = ""
$local:SecondaryLogin = (Read-Host ":")
}
elseif ($local:SecondaryAuthState -eq "OneTouchExpired")
{
throw "The OneTouch push notification has expired."
}
elseif ($local:SecondaryAuthState.StartsWith("Fido2:"))
{
throw "FIDO2 is not supported."
}
else
{
$local:SecondaryAuthState = ""
$local:SecondaryLogin = (Read-Host ":")
}
}
}
# Get final response
$local:Response = (Invoke-RestMethod -Method POST "https://$Appliance/RSTS/UserLogin/LoginController?response_type=token&redirect_uri=urn%3aInstalledApplication&loginRequestStep=6" `
-WebSession $HttpSession -Headers @{ "Accept" = "application/json"; "Content-type" = "application/x-www-form-urlencoded" } -Body @{
directoryComboBox = "$PrimaryProviderId";
usernameTextbox = "$Username";
passwordTextbox = "$($local:PasswordPlainText)";
csrfTokenTextbox = "$CsrfToken"
})
$local:Uri = ([Uri]$local:Response.RelyingPartyUrl)
$local:Fragment = ($local:Uri.Fragment.SubString(1))
$local:Parts = [System.Web.HttpUtility]::ParseQueryString($local:Fragment)
(New-Object -TypeName PSObject -Property @{
access_token = $local:Parts["access_token"];
token_type = $local:Parts["token_type"];
expires_in = $local:Parts["expires_in"];
scope = $local:Parts["scope"]
})
}
function Submit-RstsPrimaryCredential
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Appliance,
[Parameter(Mandatory=$true,Position=1)]
[string]$PrimaryProviderId,
[Parameter(Mandatory=$true,Position=2)]
[string]$Username,
[Parameter(Mandatory=$true,Position=3)]
[securestring]$Password,
[Parameter(Mandatory=$true,Position=4)]
[object]$CsrfToken
)
if (-not $PSBoundParameters.ContainsKey("ErrorAction")) { $ErrorActionPreference = "Stop" }
if (-not $PSBoundParameters.ContainsKey("Verbose")) { $VerbosePreference = $PSCmdlet.GetVariableValue("VerbosePreference") }
$local:PasswordPlainText = [System.Net.NetworkCredential]::new("", $Password).Password
$local:Response = (Invoke-RestMethod -Method POST "https://$Appliance/RSTS/UserLogin/LoginController?response_type=token&redirect_uri=urn%3aInstalledApplication&loginRequestStep=3" `
-WebSession $HttpSession -Headers @{ "Accept" = "application/json"; "Content-type" = "application/x-www-form-urlencoded" } -Body @{
directoryComboBox = "$PrimaryProviderId";
usernameTextbox = "$Username";
passwordTextbox = "$($local:PasswordPlainText)";
csrfTokenTextbox = "$CsrfToken"
})
$local:stsIdentity0 = ((($HttpSession).Cookies).GetCookies("https://$Appliance/RSTS") | Where-Object { $_.Name -eq "stsIdentity0" })[0]
if (-not $local:stsIdentity0)
{
throw "Unable to find primary identity cookie"
}
if ($local:Response.SecondaryProviderID)
{
$local:Response = (Submit-RstsMultiFactorCredential $Appliance $PrimaryProviderId $Username $Password $CsrfToken)
$local:Response
}
else
{
Write-Verbose "No 2FA configured for $Username"
if (-not $local:Response.access_token)
{
throw "No access token found in RSTS response"
}
$local:Response.access_token
}
}
function Get-RstsCsrfTokenAndSession
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Appliance
)
if (-not $PSBoundParameters.ContainsKey("ErrorAction")) { $ErrorActionPreference = "Stop" }
if (-not $PSBoundParameters.ContainsKey("Verbose")) { $VerbosePreference = $PSCmdlet.GetVariableValue("VerbosePreference") }
$local:Response = (Invoke-RestMethod -Method POST "https://$Appliance/RSTS/UserLogin/LoginController?response_type=token&redirect_uri=urn%3aInstalledApplication&loginRequestStep=1" `
-SessionVariable LocalHttpSession -Headers @{ "Accept" = "application/json"; "Content-type" = "application/x-www-form-urlencoded" } -Body @{})
$local:CsrfToken = ((($LocalHttpSession).Cookies).GetCookies("https://$Appliance/RSTS") | Where-Object { $_.Name -eq "CsrfToken" })[0]
Add-Type -AssemblyName System.Web
$local:CsrfToken = ([System.Web.HttpUtility]::UrlDecode($local:CsrfToken.Value))
if ($local:CsrfToken -ne $local:Response.AntiCsrfToken)
{
throw "Anti-CSRF token in response does not match CSRF in cookie"
}
Set-Variable -Name HttpSession -Scope Script -Value $LocalHttpSession
$local:CsrfToken
}
function Get-RstsTokenWith2fa
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Appliance,
[Parameter(Mandatory=$true,Position=1)]
[string]$PrimaryProviderId,
[Parameter(Mandatory=$true,Position=2)]
[string]$Username,
[Parameter(Mandatory=$true,Position=3)]
[SecureString]$Password
)
if (-not $PSBoundParameters.ContainsKey("ErrorAction")) { $ErrorActionPreference = "Stop" }
if (-not $PSBoundParameters.ContainsKey("Verbose")) { $VerbosePreference = $PSCmdlet.GetVariableValue("VerbosePreference") }
try
{
New-Variable -Name "HttpSession" -Scope Script -Value $null -Force
$local:CsrfToken = (Get-RstsCsrfTokenAndSession $Appliance)
$local:RstsResponse = (Submit-RstsPrimaryCredential $Appliance $PrimaryProviderId $Username $Password $local:CsrfToken)
$local:RstsResponse
}
finally
{
Clear-Variable -Name HttpSession
}
}
function New-SafeguardUrl
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Appliance,
[Parameter(Mandatory=$true,Position=1)]
[string]$Service,
[Parameter(Mandatory=$true,Position=2)]
[int]$Version,
[Parameter(Mandatory=$true,Position=3)]
[string]$RelativeUrl,
[Parameter(Mandatory=$false)]
[object]$Parameters
)
if (-not $PSBoundParameters.ContainsKey("ErrorAction")) { $ErrorActionPreference = "Stop" }
if (-not $PSBoundParameters.ContainsKey("Verbose")) { $VerbosePreference = $PSCmdlet.GetVariableValue("VerbosePreference") }
$local:Url = "https://$Appliance/service/$($Service.ToLower())/v$Version/$RelativeUrl"
if ($Parameters -and $Parameters.Length -gt 0)
{
$local:Url += "?"
$Parameters.Keys | ForEach-Object {
$local:Url += ($_ + "=" + [uri]::EscapeDataString($Parameters.Item($_)) + "&")
}
$local:Url = $local:Url -replace ".$"
}
$local:Url
}
function Wait-LongRunningTask
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=0)]
[object]$Response,
[Parameter(Mandatory=$true,Position=1)]
[object]$Headers,
[Parameter(Mandatory=$true,Position=2)]
[int]$Timeout
)
if (-not $PSBoundParameters.ContainsKey("ErrorAction")) { $ErrorActionPreference = "Stop" }
if (-not $PSBoundParameters.ContainsKey("Verbose")) { $VerbosePreference = $PSCmdlet.GetVariableValue("VerbosePreference") }
if (-not $Response.Headers.Location)
{
throw "Trying to track long running task, but response did not include a Location header"
}
$local:StartTime = (Get-Date)
$local:TaskResult = $null
$local:TaskToPoll = $($Response.Headers.Location)
do {
$local:TaskResponse = (Invoke-RestMethod -Method GET -Headers $Headers -Uri $local:TaskToPoll)
Write-Verbose $local:TaskResponse
Write-Verbose $local:TaskResponse.RequestStatus
if (-not $local:TaskResponse.RequestStatus)
{
throw "Trying to track long running task, but Location URL did not return a long running task"
}
$local:TaskStatus = $local:TaskResponse.RequestStatus
if ($local:TaskStatus.PercentComplete -eq 100)
{
Write-Progress -Activity "Waiting for long-running task" -Status "Step: $($local:TaskStatus.Message)" -PercentComplete $local:TaskStatus.PercentComplete
$local:TaskResult = $local:TaskStatus.Message + "`n " + ($local:TaskResponse.Log | ForEach-Object { "{0,-26} {1,-12} {2}`n" -f $_.Timestamp,$_.Status,$_.Message })
}
else
{
$local:Percent = 0
if ($local:TaskStatus.PercentComplete)
{
$local:Percent = $local:TaskStatus.PercentComplete
}
Write-Progress -Activity "Waiting for long-running task" -Status "Step: $($local:TaskStatus.Message)" -PercentComplete $local:Percent
if ((((Get-Date) - $local:StartTime).TotalSeconds) -gt $Timeout)
{
throw "Timed out waiting for long-running task, timeout was $Timeout seconds"
}
}
Start-Sleep 1
} until ($local:TaskResult)
if ($local:TaskStatus.State -ieq "Failure")
{
Import-Module -Name "$PSScriptRoot\sg-utilities.psm1" -Scope Local
throw (New-LongRunningTaskException $local:TaskResult $local:TaskResponse)
}
$local:TaskResult
}
function Invoke-WithoutBody
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Appliance,
[Parameter(Mandatory=$true,Position=1)]
[string]$Service,
[Parameter(Mandatory=$true,Position=2)]
[string]$Method,
[Parameter(Mandatory=$true,Position=3)]
[int]$Version,
[Parameter(Mandatory=$true,Position=4)]
[string]$RelativeUrl,
[Parameter(Mandatory=$true,Position=5)]
[object]$Headers,
[Parameter(Mandatory=$false)]
[object]$Parameters,
[Parameter(Mandatory=$false)]
[string]$InFile,
[Parameter(Mandatory=$false)]
[string]$OutFile,
[Parameter(Mandatory=$false)]
[switch]$LongRunningTask,
[Parameter(Mandatory=$false)]
[int]$Timeout
)
if (-not $PSBoundParameters.ContainsKey("ErrorAction")) { $ErrorActionPreference = "Stop" }
if (-not $PSBoundParameters.ContainsKey("Verbose")) { $VerbosePreference = $PSCmdlet.GetVariableValue("VerbosePreference") }
$local:Url = (New-SafeguardUrl $Appliance $Service $Version $RelativeUrl -Parameters $Parameters)
Write-Verbose "Url=$($local:Url)"
Write-Verbose "Parameters=$(ConvertTo-Json -InputObject $Parameters)"
$arguments = @{
Method = $Method;
Headers = $Headers;
Uri = $local:Url;
TimeoutSec = $Timeout
}
if ($InFile)
{
Write-Verbose "InFile=$InFile"
$arguments = $arguments + @{ InFile = $InFile }
}
if ($OutFile)
{
Write-Verbose "OutFile=$OutFile"
$arguments = $arguments + @{ OutFile = $OutFile }
}
if ($LongRunningTask)
{
$local:Response = (Invoke-WebRequest @arguments)
Wait-LongRunningTask $local:Response $Headers $Timeout
}
else
{
Invoke-RestMethod @arguments
}
}
function Invoke-WithBody
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Appliance,
[Parameter(Mandatory=$true,Position=1)]
[string]$Service,
[Parameter(Mandatory=$true,Position=2)]
[string]$Method,
[Parameter(Mandatory=$true,Position=3)]
[int]$Version,
[Parameter(Mandatory=$true,Position=4)]
[string]$RelativeUrl,
[Parameter(Mandatory=$true,Position=5)]
[object]$Headers,
[Parameter(Mandatory=$false)]
[object]$Body,
[Parameter(Mandatory=$false)]
[object]$JsonBody,
[Parameter(Mandatory=$false)]
[object]$Parameters,
[Parameter(Mandatory=$false)]
[string]$OutFile,
[Parameter(Mandatory=$false)]
[switch]$LongRunningTask,
[Parameter(Mandatory=$false)]
[int]$Timeout
)
if (-not $PSBoundParameters.ContainsKey("ErrorAction")) { $ErrorActionPreference = "Stop" }
if (-not $PSBoundParameters.ContainsKey("Verbose")) { $VerbosePreference = $PSCmdlet.GetVariableValue("VerbosePreference") }
$local:BodyInternal = $JsonBody
if ($Body)
{
$local:BodyInternal = (ConvertTo-Json -Depth 100 -InputObject $Body)
}
$local:Url = (New-SafeguardUrl $Appliance $Service $Version $RelativeUrl -Parameters $Parameters)
Write-Verbose "Url=$($local:Url)"
Write-Verbose "Parameters=$(ConvertTo-Json -InputObject $Parameters)"
Write-Verbose "---Request Body---"
Write-Verbose "$($local:BodyInternal)"
$arguments = @{
Method = $Method;
Headers = $Headers;
Uri = $local:Url;
Body = ([System.Text.Encoding]::UTF8.GetBytes($local:BodyInternal));
TimeoutSec = $Timeout
}
if ($OutFile)
{
Write-Verbose "OutFile=$OutFile"
$arguments = $arguments + @{ OutFile = $OutFile }
}
if ($LongRunningTask)
{
$local:Response = (Invoke-WebRequest @arguments)
Wait-LongRunningTask $local:Response $Headers $Timeout
}
else
{
Invoke-RestMethod @arguments
}
}
function Invoke-Internal
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Appliance,
[Parameter(Mandatory=$true,Position=1)]
[string]$Service,
[Parameter(Mandatory=$true,Position=2)]
[string]$Method,
[Parameter(Mandatory=$true,Position=3)]
[int]$Version,
[Parameter(Mandatory=$true,Position=4)]
[string]$RelativeUrl,
[Parameter(Mandatory=$true,Position=5)]
[object]$Headers,
[Parameter(Mandatory=$false)]
[object]$Body,
[Parameter(Mandatory=$false)]
[object]$JsonBody,
[Parameter(Mandatory=$false)]
[object]$Parameters,
[Parameter(Mandatory=$false)]
[string]$InFile,
[Parameter(Mandatory=$false)]
[string]$OutFile,
[Parameter(Mandatory=$false)]
[switch]$LongRunningTask,
[Parameter(Mandatory=$false)]
[int]$Timeout
)
if (-not $PSBoundParameters.ContainsKey("ErrorAction")) { $ErrorActionPreference = "Stop" }
if (-not $PSBoundParameters.ContainsKey("Verbose")) { $VerbosePreference = $PSCmdlet.GetVariableValue("VerbosePreference") }
try
{
switch ($Method.ToLower())
{
{$_ -in "get","delete"} {
Invoke-WithoutBody $Appliance $Service $Method $Version $RelativeUrl $Headers `
-Parameters $Parameters -InFile $InFile -OutFile $OutFile -LongRunningTask:$LongRunningTask -Timeout $Timeout
break
}
{$_ -in "put","post"} {
if ($InFile)
{
Invoke-WithoutBody $Appliance $Service $Method $Version $RelativeUrl $Headers `
-Parameters $Parameters -InFile $InFile -OutFile $OutFile -LongRunningTask:$LongRunningTask -Timeout $Timeout
}
else
{
Invoke-WithBody $Appliance $Service $Method $Version $RelativeUrl $Headers `
-Body $Body -JsonBody $JsonBody `
-Parameters $Parameters -OutFile $OutFile -LongRunningTask:$LongRunningTask -Timeout $Timeout
}
break
}
}
}
catch
{
Import-Module -Name "$PSScriptRoot\sg-utilities.psm1" -Scope Local
Out-SafeguardExceptionIfPossible $_
}
}
<#
.SYNOPSIS
Log into a Safeguard appliance in this Powershell session for the purposes
of using the Web API.
.DESCRIPTION
This utility can help you securely obtain an access token from a Safeguard
appliance and save it as a global variable. Optionally, the token can be
returned to standard out and not saved in the session.
The password may be passed in as a SecureString or a Powershell
credential can be used for both username and password. By default, this
script will securely prompt for the password. Client certificate
authentication is also supported.
First this script retrieves an access token from the embedded redistributable
secure token service. Then, it exchanges this token for a Safeguard user token.
You must use the -Browser parameter for 2FA login support.
.PARAMETER Appliance
IP address or hostname of a Safeguard appliance.
.PARAMETER Insecure
Ignore verification of Safeguard appliance SSL certificate--will be ignored for entire session.
.PARAMETER IdentityProvider
Identity provider to use for RSTS authentication (e.g. local, certificate, ad<int>-<domain>)
.PARAMETER Credential
Powershell credential to be used for username and password.
.PARAMETER Username
The username to authenticate as when not using Powershell credential.
.PARAMETER Password
SecureString containing the password.
.PARAMETER CertificateFile
Path to a PFX (PKCS12) file containing the client certificate to use to connect to the RSTS.
.PARAMETER Thumbprint
Client certificate thumbprint to use to authenticate the connection to the RSTS.
.PARAMETER Version
Version of the Web API you are using (default: 4).
.PARAMETER Gui (Deprecated)
Use -Browser instead.
.PARAMETER Browser
Launch redistributable STS login window in a native system browser. Supports 2FA.
If neither the -Gui nor -Browser switches are specified, then the OAuth2 Resource Owner Password Credential grant type
will be used to programmatically submit the provided credentials. Ensure that Safeguard has been configured to allow
this grant type by checking the Safeguard Access settings in Appliance Management.
.PARAMETER TwoFactor
Attempt to authenticate using multiple factors via the command line. Supports Starling 2FA.
.PARAMETER NoSessionVariable
If this switch is sent the access token will be returned and a login session context variable will not be created.
.PARAMETER NoWindowTitle
If this switch is sent safeguard-ps won't try to set the window title, which can cause failures when the PowerShell
runtime doesn't allow user interaction; for example, when running safeguard-ps from C#.
.INPUTS
None.
.OUTPUTS
None (with LoginSession variable filled out) or AccessToken for calling Web API.
.EXAMPLE
Connect-Safeguard 10.5.32.54 local -Credential (Get-Credential)
Login Successful.
.EXAMPLE
Connect-Safeguard 10.5.32.54 -Browser
[Opens browser window for normal Safeguard login experience, including 2FA]
.EXAMPLE
Connect-Safeguard 10.5.32.54 -Username admin -Insecure
(certificate, local)
IdentityProvider: local
Password: ********
Login Successful.
.EXAMPLE
Connect-Safeguard 10.5.32.162 -Thumbprint "AB40BF0AD5647C9A8E0431DA5F473F44910D8975"
Login Successful.
.EXAMPLE
Connect-Safeguard 10.5.32.162 ad18-green.vas
Username: petrsnd
Password: **********
Login Successful.
.EXAMPLE
Connect-Safeguard 10.5.32.162 local Admin Admin123 -NoSessionVariable
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1Ni...
#>
function Connect-Safeguard
{
[CmdletBinding(DefaultParameterSetName="Username")]
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Appliance,
[Parameter(Mandatory=$false)]
[switch]$Insecure = $false,
[Parameter(Mandatory=$false,Position=1)]
[string]$IdentityProvider,
[Parameter(ParameterSetName="PSCredential",Position=2)]
[PSCredential]$Credential,
[Parameter(ParameterSetName="Username",Mandatory=$false,Position=2)]
[string]$Username,
[Parameter(ParameterSetName="Username",Position=3)]
[SecureString]$Password,
[Parameter(ParameterSetName="Certificate",Mandatory=$false)]
[string]$CertificateFile,
[Parameter(ParameterSetName="Certificate",Mandatory=$false)]
[string]$Thumbprint,
[Parameter(ParameterSetName="Gui",Mandatory=$false)]
[switch]$Gui,
[Parameter(ParameterSetName="Browser",Mandatory=$false)]
[switch]$Browser,
[Parameter(ParameterSetName="Username",Mandatory=$false)]
[switch]$TwoFactor,
[Parameter(Mandatory=$false)]
[int]$Version = 4,
[Parameter(Mandatory=$false)]
[switch]$NoSessionVariable = $false,
[Parameter(Mandatory=$false)]
[switch]$NoWindowTitle = $false
)
if (-not $PSBoundParameters.ContainsKey("ErrorAction")) { $ErrorActionPreference = "Stop" }
if (-not $PSBoundParameters.ContainsKey("Verbose")) { $VerbosePreference = $PSCmdlet.GetVariableValue("VerbosePreference") }
try
{
Edit-SslVersionSupport
if ($Insecure)
{
Disable-SslVerification
if ($global:PSDefaultParameterValues) { $PSDefaultParameterValues = $global:PSDefaultParameterValues.Clone() }
}
if ($Browser -Or $Gui)
{
$local:RstsResponse = (Get-RstsTokenFromBrowser $Appliance $Username)
}
else
{
Write-Verbose "Getting configured identity providers from CORE service (using GET)..."
try
{
$local:ConfiguredProvidersRaw = (Invoke-RestMethod -Method GET -Uri "https://$Appliance/service/core/v$Version/AuthenticationProviders" `
-Headers @{ "Accept" = "application/json" } `
-ErrorAction SilentlyContinue)
}
catch [Net.WebException]
{
Write-Verbose "Initial attempt returned WebException: $($_.Exception.Status)"
if ($_.Exception.Status -eq "ConnectFailure")
{
throw "Unable to connect to $Appliance, bad appliance network address?"
}
}
catch
{
Write-Verbose "Initial attempt threw unknown exception"
}
# Built-in providers
$local:ConfiguredProviders = ,(New-Object -TypeName PSObject -Property @{
RstsProviderId = "certificate";
Name = "certificate"
}),(New-Object -TypeName PSObject -Property @{
RstsProviderId = "local";
Name = "Local"
})
$local:ConfiguredProvidersRaw | Sort-Object Name | ForEach-Object {
# Trim out local so we can control order
if ($_.RstsProviderId -ine "local")
{
$local:ConfiguredProviders += (New-Object -TypeName PSObject -Property @{
RstsProviderId = $_.RstsProviderId;
Name = $_.Name
})
}
}
$local:IdentityProviders = ($local:ConfiguredProviders | ForEach-Object {
if ($_.RstsProviderId -ieq "certificate" -or $_.RstsProviderId -ieq "local")
{
"$($_.RstsProviderId)"
}
else
{
"$($_.RstsProviderId) [$($_.Name)]"
}
})
if (-not $IdentityProvider)
{
Write-Verbose "Identity provider not passed in"
if ($Thumbprint -or $CertificateFile)