Get-SAMLMetadata.ps1

<#
.SYNOPSIS
    This script returns some of the metadata information provided by a remote identity provider.
 
.DESCRIPTION
    This script returns some of the metadata information provided by a remote identity provider.
 
.PARAMETER ADFSHostname
    ADFS server hostname, this DNS name is used to connect to well known federation metadata URL
    https://$ADFSHostname/FederationMetadata/2007-06/FederationMetadata.xml
 
    Default value: None
    Mandatory: Either this value or MetadataURL must be specified
 
.PARAMETER MetadataURL
    URL where metadata is stored. If this URL is set, ADFSHostname paramater is ignored.
 
    Default value: None
    Mandatory: Either this value or ADFSHostname must be specified
 
.PARAMETER Output
    Specfies which part of metadata to return.
        "WS-Fed-WebSSO-Config" data includes:
            ADFS/STS Identifier aka /adfs/services/trust
            WS Federation ADFS/STS URL aka /adfs/ls
            Service display name
            Signing Certificates
 
 
        "SAML2-WebSSO-Config" data includes:
            ADFS/STS Identifier aka /adfs/services/trust
            SingleLogoutServices
               Binding / URL of Single Logout Endpoints
            SingleSignOnServices
                Binding / URL of SSO Endpoints
            Signing Certificates
 
        "XML-File":
            Saves metadata to XML file named METADATA_$Hostname_yyyy-MM-dd.xml
 
            Default value: WS-Fed-WebSSO-Config
            Mandatory: No
 
.NOTES
    Author : Martin Rublik (martin.rublik@bspc.sk)
    Created : 2018-07-10
    Version : 1.2
 
 
    Changelog:
    V 1.0 (2016-03-23) - intial version
    V 1.1 (2017-09-19) - added verbos information and encryption certificates
    V 1.2 (2018-07-10) - added insecure option, output to file
 
    License:
    The MIT License (MIT)
 
    Copyright (c) 2016 Martin Rublik
 
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
 
    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.
 
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
 
 
.EXAMPLE
            .\GetSAMLMetadata.ps1 -ADFSHostname adfs.example.com
 
            Return WS Federation related data from adfs.example.com
 
.EXAMPLE
            $certs = .\GetSAMLMetadata.ps1 -ADFSHostname adfs.example.com | Select-Object -ExpandProperty SigningCertificates
 
            Return signing certificates for adfs.example.com with WS-Federation support. These certificates can be used in configuration scripts.
 
.EXAMPLE
            $certs = .\GetSAMLMetadata.ps1 -ADFSHostname adfs.example.com -Out SAML2-WebSSO-Config | Select-Object -ExpandProperty SigningCertificates
 
            Return signing certificates for adfs.example.com with WS-Federation support. These certificates can be used in configuration scripts.
 
.EXAMPLE
            .\GetSAMLMetadata.ps1 -ADFSHostname adfs.example.com -Out SAML2-WebSSO-Config | Select-Object -ExpandProperty SigningCertificates | foreach { Set-Content -Encoding Byte -Path "SIGN-$($_.Thumbprint).crt" $_.RawData }
 
            Save token signing certificates to filesystem.
 
 
#>


function Get-SAMLMetadata
{
    [cmdletbinding(ConfirmImpact = 'Low')]
    param(
                [string] $ADFSHostname,
                [string] $MetadataURL,
                [ValidateSet("WS-Fed-WebSSO-Config","SAML2-WebSSO-Config","XML-File",IgnoreCase = $true)]
                [string] $Output="WS-Fed-WebSSO-Config",
                [switch] $Insecure
    )


    try
    {
        #Add-Type -AssemblyName "System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

        if (-not $MetadataURL)
        {
            $MetadataURL="https://$ADFSHostname/FederationMetadata/2007-06/FederationMetadata.xml"
        }
        if ($Insecure)
        {
            if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
            {
                $certCallback=@"
                using System;
                using System.Net;
                using System.Net.Security;
                using System.Security.Cryptography.X509Certificates;
                public class ServerCertificateValidationCallback
                {
                    public static void Ignore()
                    {
                        if(ServicePointManager.ServerCertificateValidationCallback ==null)
                        {
                            ServicePointManager.ServerCertificateValidationCallback +=
                                delegate
                                (
                                    Object obj,
                                    X509Certificate certificate,
                                    X509Chain chain,
                                    SslPolicyErrors errors
                                )
                                {
                                    return true;
                                };
                        }
                    }
                }
"@

                Add-Type $certCallback
            }
            [ServerCertificateValidationCallback]::Ignore();
            Write-Error "Switching to insecure channel, metadata is not verified at all"
            Write-Warning "Downloading from:`n $MetadataURL"
        }else
        {
            Write-Warning "Caution, the metadata is verified strictly on SSL/TLS transport level, XML digital signature is not checked. `nDownloading from:`n $MetadataURL"
        }

        if ( $Output.ToLower().Equals("xml-file") )
        {
            $Uri = New-Object System.Uri($MetadataURL)
            $FileName = "METADATA_$($Uri.Host)_$((get-date).ToString("yyyy-MM-dd")).xml"

            Invoke-WebRequest -Uri $MetadataURL -OutFile $FileName
            Write-Output "Data written to $(Get-Location)\$FileName"
            return
        }

        $metadataResponse = Invoke-WebRequest -Uri $MetadataURL

        $metadataSerializer = New-Object System.IdentityModel.Metadata.MetadataSerializer
        $metadataSerializer.CertificateValidationMode = [System.ServiceModel.Security.X509CertificateValidationMode]::None

        $metadataResponse.RawContentStream.Position=0
        $entityDescriptor = $metadataSerializer.ReadMetadata($metadataResponse.RawContentStream);

        $STSDesc = $entityDescriptor.RoleDescriptors | Where-Object {$_.gettype().Name -eq "SecurityTokenServiceDescriptor"}
        $IDPSSODesc = $entityDescriptor.RoleDescriptors | Where-Object {$_.gettype().Name -eq "IdentityProviderSingleSignOnDescriptor"}

        $result=New-Object PSObject
        $result | Add-Member -MemberType NoteProperty Id -Value $entityDescriptor.EntityId.Id -Force
        $result | Add-Member -MemberType NoteProperty Organization -Value $entityDescriptor.Organization -Force

        if ( $Output.ToLower().Equals("ws-fed-websso-config") )
        {


            $result | Add-Member -MemberType NoteProperty ServiceDisplayName -Value $STSDesc.ServiceDisplayName -Force

            $passiveURLs=@();
            if ($STSDesc.PassiveRequestorEndpoints.Count -gt 0)
            {
                foreach($reference in $STSDesc.PassiveRequestorEndpoints) {$passiveURLs+=$reference.Uri}
            }
            $result | Add-Member -MemberType NoteProperty PassiveRequestorEndpoints -Value $passiveURLs -Force

            $singingCerts=@();
            if ($STSDesc.Keys.Count -gt 0)
            {
                foreach($key in $STSDesc.Keys)
                {
                    try
                    {
                        if ($key.Use -eq "Signing")
                        {
                            # http://www.leeholmes.com/blog/2007/06/19/invoking-generic-methods-on-non-generic-classes-in-powershell/
                            $genericFindRawCertMethod = [System.IdentityModel.Tokens.SecurityKeyIdentifier].GetMethod("Find");
                            $closedFindRawCertMethod = $genericFindRawCertMethod.MakeGenericMethod([System.IdentityModel.Tokens.X509RawDataKeyIdentifierClause]);
                            $keyInfo = $closedFindRawCertMethod.Invoke($key.KeyInfo,$null);

                            $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(,$keyInfo.GetX509RawData())
                            $singingCerts+=$cert
                        }
                    }catch
                    {
                        # TODO err handling
                        Write-Warning $_.Exception.Message
                    }
                }
            }
            $result | Add-Member -MemberType NoteProperty SigningCertificates -Value $singingCerts -Force

        }

        if ( $Output.ToLower().Equals("saml2-websso-config"))
        {

            $result | Add-Member -MemberType NoteProperty SingleLogoutServices -Value $IDPSSODesc.SingleLogoutServices -Force
            $result | Add-Member -MemberType NoteProperty SingleSignOnServices -Value $IDPSSODesc.SingleSignOnServices -Force

            $singingCerts=@();
            $encryptionCerts=@();
            if ($IDPSSODesc.Keys.Count -gt 0)
            {
                foreach($key in $IDPSSODesc.Keys)
                {
                    try
                    {
                        if ($key.Use -eq "Signing")
                        {
                            # http://www.leeholmes.com/blog/2007/06/19/invoking-generic-methods-on-non-generic-classes-in-powershell/
                            $genericFindRawCertMethod = [System.IdentityModel.Tokens.SecurityKeyIdentifier].GetMethod("Find");
                            $closedFindRawCertMethod = $genericFindRawCertMethod.MakeGenericMethod([System.IdentityModel.Tokens.X509RawDataKeyIdentifierClause]);
                            $keyInfo = $closedFindRawCertMethod.Invoke($key.KeyInfo,$null);

                            $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(,$keyInfo.GetX509RawData())
                            $singingCerts+=$cert
                        }
                        if ($key.Use -eq "Encryption")
                        {
                            # http://www.leeholmes.com/blog/2007/06/19/invoking-generic-methods-on-non-generic-classes-in-powershell/
                            $genericFindRawCertMethod = [System.IdentityModel.Tokens.SecurityKeyIdentifier].GetMethod("Find");
                            $closedFindRawCertMethod = $genericFindRawCertMethod.MakeGenericMethod([System.IdentityModel.Tokens.X509RawDataKeyIdentifierClause]);
                            $keyInfo = $closedFindRawCertMethod.Invoke($key.KeyInfo,$null);

                            $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(,$keyInfo.GetX509RawData())
                            $encryptionCerts+=$cert
                        }

                    }catch
                    {
                        Write-Warning $_.Exception.Message
                    }
                }
            }
            $result | Add-Member -MemberType NoteProperty SigningCertificates -Value $singingCerts -Force
            $result | Add-Member -MemberType NoteProperty EncryptionCertificates -Value $encryptionCerts -Force
        }

        $result

    }catch
    {
                throw $_.Exception
    }
}