Add-ADFS_RelyingPartyTrust.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
#Requires -RunAsAdministrator
#Requires -Version 5.0

<#
     .SYNOPSIS
        Create ADFS Relying Party Trust configuration .
    .DESCRIPTION
        Create ADFS Relying Party Trust configuration samples.
 
        Dependencies:
        None.
 
    .NOTES
        Version: 2.0.0.5
        Author: SecureMfa.com
        Creation Date: 15/02/2021
        Purpose/Change: Release
   
    .EXAMPLE
        Add-ADFS_RelyingPartyTrust -RP_WEBSITE_URL 'https://ardswebl01.adatum.labnet/RDWeb/Pages/Default.aspx' -SampleRP RDWeb
 
        This command will create ADFS RelyingPartyTrust configuration for Microsoft RD Web Servers deployment with SSO configuration.
    
#>


Function Add-ADFS_RelyingPartyTrust {
Param
(  
    [Parameter(Mandatory=$false)][string]$RP_WEBSITE_URL = "https://ardswebl01.adatum.labnet/RDWeb/Pages/Default.aspx",
    [Parameter(Mandatory=$false)][string]$RP_Name,
    [Parameter(Mandatory=$false)][ValidateSet('RDWeb','SpringSample','None')][string]$SampleRP='RDWeb',
    [Parameter(Mandatory=$false)][Switch]$Force    
)
    
    #Variables
    if($SampleRP -eq 'RDWeb') {$RP_Name = "SecureMFA_RDWeb"}
    elseif($SampleRP -eq 'SpringSample') {$RP_Name = "SecureMFA_SpringSample"}
    else {if($RP_Name){$RP_Name = "SecureMFA_" + $RP_Name} else {$RP_Name = "SecureMFA_RDWeb"};}
    
    $ADFS_ISSUER = (Get-ADFSEndpoint  | where{$_.Protocol -eq "SAML 2.0/WS-Federation"}).FullUrl.OriginalString
    $ADFS_Identifier = (Get-AdfsProperties).Identifier.AbsoluteUri
    $ADFS_FederationMetadata = (Get-ADFSEndpoint  | where{$_.Protocol -eq "Federation Metadata"}).FullUrl.OriginalString
    $ADFS_TokenSigning_Thumbprint = (Get-AdfsCertificate -CertificateType Token-Signing).Thumbprint
       
    if (!$Force) {
    $message  = "Do you want to overwrite existing ADFS RelyingPartyTrust " + $RP_Name + " ?";            
    $question = 'Please confirm?'
    $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
    $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes'))
    $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))
    
    if(Get-AdfsRelyingPartyTrust -Name $RP_Name) {
        $decision_Validation = $Host.UI.PromptForChoice($message, $question, $choices, 0)
        if ($decision_Validation -eq 1 ) {Write-Host "ADFS RelyingPartyTrust configuration has been cancelled, exiting!" -ForegroundColor Yellow ; break} else {Remove-AdfsRelyingPartyTrust -TargetName $RP_Name}
        }
    }
    else {if(Get-AdfsRelyingPartyTrust -Name $RP_Name) {Remove-AdfsRelyingPartyTrust -TargetName $RP_Name}}
            
    try
    {
        $Error.Clear()
        #Validate if Identifier is not dublicated
        if(Get-ADFSRelyingPartyTrust -Identifier $RP_WEBSITE_URL) {throw "RelyingPartyTrust Identifier exist: $RP_WEBSITE_URL . Please fix the duplicate Identifier issue for RP: " + (Get-ADFSRelyingPartyTrust -Identifier $RP_WEBSITE_URL).Name  + " and try again. " ; break}
                                   
        #Start RP creation
        
#-------
#Default authorization rules
$IssuanceAuthorizationRules=@'
@RuleTemplate = "AllowAllAuthzRule"
 => issue(Type = "http://schemas.microsoft.com/authorization/claims/permit",
Value = "true");
'@


#Stores Issuance Transformation Rules
$IssuanceTransformRules=@'
 @RuleTemplate = "LdapClaims"
 @RuleName = "Active Directory"
c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"]
 => issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"), query = ";userPrincipalName;{0}", param = c.Value);
'@

#-------
                
        if($SampleRP -eq 'RDWeb') {        
        
        #Validate if RDWeb Identifier is not dublicated
        if(Get-ADFSRelyingPartyTrust -Identifier "urn:microsoft:rdweb") {throw "RelyingPartyTrust Identifier exist: 'urn:microsoft:rdweb' . Please fix the duplicate Identifier issue for RP: " + (Get-ADFSRelyingPartyTrust -Identifier "urn:microsoft:rdweb").Name  + " and try again. " ; break}
                
        #Creates Relying Party Trust
        Add-ADFSRelyingPartyTrust -Name $RP_Name `
                          -Enabled $true `
                          -Notes "This is a trust for $RP_WEBSITE_URL" `
                          -WSFedEndpoint $RP_WEBSITE_URL `
                          -Identifier $RP_WEBSITE_URL,"urn:microsoft:rdweb" `
                          -IssuanceTransformRules $IssuanceTransformRules `
                          -IssuanceAuthorizationRules $IssuanceAuthorizationRules        
        }
        elseif($SampleRP -eq 'SpringSample') {
        
        #Validate if SpringSample Identifier is not dublicated
        if(Get-ADFSRelyingPartyTrust -Identifier "com:securemfa:domain:springsample:test:sp") {throw "RelyingPartyTrust Identifier exist: 'com:securemfa:domain:springsample:test:sp' . Please fix the duplicate Identifier issue for RP: " + (Get-ADFSRelyingPartyTrust -Identifier "com:securemfa:domain:springsample:test:sp").Name  + " and try again. " ; break}
        
        $ClaimSet1 = New-ADFSClaimRuleSet -ClaimRule '@RuleTemplate = "LdapClaims" @RuleName = "Email" c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"] => issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"), query = ";mail,displayName;{0}", param = c.Value);'
        $ClaimSet2 = New-ADFSClaimRuleSet -ClaimRule '@RuleName = "Transform Email to NameID" c:[Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"] => issue(Type = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", Issuer = c.Issuer, OriginalIssuer = c.OriginalIssuer, Value = c.Value, ValueType = c.ValueType, Properties["http://schemas.xmlsoap.org/ws/2005/05/identity/claimproperties/format"] = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", Properties["http://schemas.xmlsoap.org/ws/2005/05/identity/claimproperties/spnamequalifier"] = "springsample-saml");'
        $ClaimRulesAll = New-AdfsClaimRuleSet -ClaimRule  ($ClaimSet1.ClaimRules + $ClaimSet2.ClaimRules)

        #SAMLAssertionConsumer
        $samlEndpoint1 = New-ADFSSamlEndpoint -Protocol 'SAMLAssertionConsumer' -Uri $RP_WEBSITE_URL -Binding 'POST' -IsDefault $true -Index 0
        #SAMLLogout
        $xRP_WEBSITE_URL = $RP_WEBSITE_URL;
        if ($xRP_WEBSITE_URL -notmatch '/$') {$xRP_WEBSITE_URL += '/'}
        $SAMLLogoutURL = $xRP_WEBSITE_URL + "saml/sp/logout"
        $samlEndpoint2 = New-ADFSSamlEndpoint -Protocol 'SAMLLogout' -Uri $SAMLLogoutURL -Binding 'POST'
                
        #Creates Relying Party Trust
        Add-ADFSRelyingPartyTrust -Name $RP_Name `
                          -Enabled $true `
                          -Notes "This is a trust for $RP_WEBSITE_URL" `
                          -SamlEndpoint @($samlEndpoint1,$samlEndpoint2) `
                          -Identifier "com:securemfa:domain:springsample:test:sp" `
                          -IssuanceTransformRules $IssuanceTransformRules `
                          -IssuanceAuthorizationRules $IssuanceAuthorizationRules  
        
        #Apply Claim rules
        Set-AdfsRelyingPartyTrust -TargetName $RP_Name -IssuanceTransformRules $ClaimRulesAll.ClaimRulesString      
        }
        else 
        {        
        Add-ADFSRelyingPartyTrust -Name $RP_Name `
                          -Enabled $true `
                          -Notes "This is a trust for $RP_WEBSITE_URL" `
                          -WSFedEndpoint $RP_WEBSITE_URL `
                          -Identifier $RP_WEBSITE_URL `
                          -IssuanceTransformRules $IssuanceTransformRules `
                          -IssuanceAuthorizationRules $IssuanceAuthorizationRules
        }

        Set-AdfsRelyingPartyTrust -TargetName $RP_Name -AccessControlPolicyName "Permit everyone and require MFA"

        # Complete
        write-host "ADFS RelyingPartyTrust $RP_Name has been configured for: $RP_WEBSITE_URL" -ForegroundColor Green
        write-host "ADFS Issuer: $ADFS_ISSUER" -ForegroundColor Cyan
        write-host "ADFS Identifier: $ADFS_Identifier" -ForegroundColor Cyan
        write-host "ADFS Federation Metadata Endpoint: $ADFS_FederationMetadata" -ForegroundColor Cyan        
        write-host "ADFS TokenSigning Thumbprint: $ADFS_TokenSigning_Thumbprint" -ForegroundColor Cyan
        
    }
    catch
    {
        Write-Host "$($MyInvocation.InvocationName): $_" -ForegroundColor red
    }    


}