PS.MTA-STS.psm1

function Resolve-PSMTASTSDnsName {
    <#
        .SYNOPSIS
        Resolve-PSMTASTSDnsName resolves DNS name using specified DNS server.
 
        .DESCRIPTION
        Resolve-PSMTASTSDnsName resolves DNS name using specified DNS server.
         
        .PARAMETER Name
        Name of the DNS record to resolve.
 
        .PARAMETER Type
        Type of the DNS record to resolve.
 
        .PARAMETER Server
        DNS server to use for resolving the DNS record.
 
        .EXAMPLE
        Resolve-PSMTASTSDnsName -Name "example.com" -Type "TXT" -Server "8.8.8.8"
 
        Resolves the TXT record for example.com using the DNS server "8.8.8.8". The return value is the TXT record for example.com.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]
        $Name,

        [Parameter(Mandatory = $true)]
        [string]
        $Type,

        [Parameter(Mandatory = $true)]
        [String]
        $Server
    )

    Write-Verbose "...checking $Type record for $Name using DNS server $Server"
    try {
        Resolve-DnsName -Name $Name -Type $Type -Server $Server -QuickTimeout -ErrorAction Stop
    }
    catch {
        if($_.Exception.Message -like "*DNS name does not exist*") {
            Write-Verbose "DNS record not found. Continuing..."
        }
        elseif($_.Exception.Message -like "*timeout period expired*") {
            throw "ERROR: Timeout period expired. Please check the DNS server and try again. Are you able to resolve the DNS record using the defined DNS server?"
        }
        else {
            throw $_
        }
    }
}

function Add-PSMTASTSCustomDomain {
    <#
        .SYNOPSIS
        Add-PSMTASTSCustomDomain adds custom domains to MTA-STS Function App.
 
        .DESCRIPTION
        Add-PSMTASTSCustomDomain adds custom domains to MTA-STS Function App. It also creates new certificate for each domain and adds binding to Function App.
 
        .PARAMETER CsvPath
        Provide path to csv file with accepted domains. Csv file should have one column with header "DomainName" and list of domains in each row.
 
        .PARAMETER DomainName
        Provide list of domains.
 
        .PARAMETER ResourceGroupName
        Provide name of Resource Group where Function App is located.
 
        .PARAMETER FunctionAppName
        Provide name of Function App.
 
        .PARAMETER DoNotAddManagedCertificate
        Switch to not add managed certificate to Function App. This is useful, if you want to use your own certificate.
 
        .PARAMETER CsvEncoding
        Provide encoding of csv file. Default is "UTF8".
 
        .PARAMETER CsvDelimiter
        Provide delimiter of csv file. Default is ";".
 
        .PARAMETER DnsServer
        Provide a String containing the IP address of the DNS server, which should be used to query the MX record. Default is 8.8.8.8 (Google DNS).
 
        .PARAMETER WhatIf
        Switch to run the command in a WhatIf mode.
 
        .PARAMETER Confirm
        Switch to run the command in a Confirm mode.
 
        .EXAMPLE
        Add-PSMTASTSCustomDomain -CsvPath "C:\temp\accepted-domains.csv" -ResourceGroupName "MTA-STS" -FunctionAppName "MTA-STS-FunctionApp"
 
        Reads list of accepted domains from "C:\temp\accepted-domains.csv" and adds them to Function App "MTA-STS-FunctionApp" in Resource Group "MTA-STS". It also creates new certificate for each domain and adds binding to Function App.
 
        .EXAMPLE
        Add-PSMTASTSCustomDomain -DomainName "contoso.com", "fabrikam.com" -ResourceGroupName "MTA-STS" -FunctionAppName "MTA-STS-FunctionApp"
 
        Adds domains "contoso.com" and "fabrikam.com" to Function App "MTA-STS-FunctionApp" in Resource Group "MTA-STS". It also creates new certificate for each domain and adds binding to Function App.
 
        .LINK
        https://github.com/jklotzsche-msft/PS.MTA-STS
    #>

    [CmdletBinding(SupportsShouldProcess = $true, DefaultParameterSetName = "Csv")]
    param (
        [Parameter(Mandatory = $true, ParameterSetName = "Csv")]
        [string]
        $CsvPath,

        [Parameter(Mandatory = $true, ParameterSetName = "Manual")]
        [string[]]
        $DomainName,

        [Parameter(Mandatory = $true)]
        [string]
        $ResourceGroupName,

        [Parameter(Mandatory = $true)]
        [string]
        $FunctionAppName,

        [switch]
        $DoNotAddManagedCertificate,

        [Parameter(ParameterSetName = "Csv")]
        [string]
        $CsvEncoding = "UTF8",

        [Parameter(ParameterSetName = "Csv")]
        [string]
        $CsvDelimiter = ";",

        [String]
        $DnsServer = "8.8.8.8"
    )
    
    begin {
        # Check, if we are connected to Azure
        if ($null -eq (Get-AzContext)) {
            Write-Warning "Connecting to Azure service"
            $null = Connect-AzAccount -ErrorAction Stop
        }

        # Import csv file with accepted domains
        if ($CsvPath) {
            Write-Verbose "Importing csv file from $CsvPath"
            $domainList = Import-Csv -Path $CsvPath -Encoding $CsvEncoding -Delimiter $CsvDelimiter -ErrorAction Stop | Select-Object -ExpandProperty DomainName
        }

        # Import domains from input parameter
        if ($DomainName) {
            Write-Verbose "Creating array of domains from input parameter"
            $domainList = @()
            foreach ($domain in $DomainName) { $domainList += $domain }
        }

        # Check, if domains have correct format
        foreach ($domain in $domainList) {
            if ($domain -notmatch "^[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$") {
                Write-Error -Message "Domain $domain has incorrect format. Please provide domain in format 'contoso.com'."
                return
            }
        }
    }

    process {
        # Preset ErrorActionPreference to Stop
        $ErrorActionPreference = "Stop"

        # Trap errors
        trap {
            Write-Error $_
            return
        }

        #Check FunctionApp
        Write-Verbose "Get Azure Function App $FunctionAppName in Resource Group $ResourceGroupName"
        $FunctionAppResult = Get-AzFunctionApp -ResourceGroupName $ResourceGroupName -Name $FunctionAppName -WarningAction SilentlyContinue
        if ($null -eq $FunctionAppResult) {
            #Function App not found
            throw "FunctionApp $FunctionAppName not found"
        }

        #Get CustomDomain Names
        Write-Verbose "Get CustomDomainNames from Azure Function App $FunctionAppName"
        $customDomainNames = Get-PSMTASTSCustomDomain -ResourceGroupName $ResourceGroupName -FunctionAppName $FunctionAppName -ErrorAction Stop

        # Prepare new domains
        $newCustomDomainsToAdd = @()
        foreach ($domain in $domainList) {
            Write-Verbose "Working on Domain: $Domain"

            #Check if mta-sts.domain.tld CNAME $FunctionAppName.azurewebsites.net exists
            $mtaStsDomain = "mta-sts." + $domain
            $mtaStsCName = Resolve-PSMTASTSDnsName -Name $mtaStsDomain -Server $DnsServer -Type CNAME -ErrorAction Stop | Where-Object { $_.NameHost -like "*.azurewebsites.net" } | Select-Object -ExpandProperty NameHost

            # Check, if CNAME record exists
            if ($Null -eq $mtaStsCName -or $mtaStsCName -ne "$FunctionAppName.azurewebsites.net") {
                Write-Warning "CNAME record not found for $mtaStsDomain with value $FunctionAppName.azurewebsites.net. Found value: $mtaStsCName - Please create/update it and try again with this domain. Continuing with next domain."
                continue
            }
            
            # Add domain to list, if it is not already added
            if ($mtaStsDomain -notin $customDomainNames.CustomDomains) {
                $newCustomDomainsToAdd += $mtaStsDomain
            }
        }

        # Check, if there are new domains to add
        if ($newCustomDomainsToAdd.count -eq 0) {
            Write-Warning "No new domains to add to Function App $FunctionAppName. Stopping here."
            return
        }

        # Add new domains to Function App
        $customDomainsToSet = @()
        $customDomainsToSet += $customDomainNames.DefaultDomain # Add default domain
        $customDomainsToSet += $newCustomDomainsToAdd # Add new custom domains
        if($null -ne $customDomainNames.CustomDomains) {
            $customDomainsToSet += $customDomainNames.CustomDomains # Add existing custom domains, if any exist
        }
        Write-Verbose "Setting $($customDomainsToSet.count) domains for Function App $FunctionAppName : $($customDomainsToSet -join ", ")"
        $setAzWebApp = @{
            ResourceGroupName = $ResourceGroupName
            Name              = $FunctionAppName
            HostNames         = $customDomainsToSet
            ErrorAction       = "Stop"
            WarningAction     = "Stop"
        }
        if ($PSCmdlet.ShouldProcess("Function App $FunctionAppName", "Add custom domains")) {
            $null = Set-AzWebApp @setAzWebApp
        }

        # Stop here, if we should not add managed certificate
        if ($DoNotAddManagedCertificate) {
            Write-Verbose "Managed certificate will not be added to Function App $FunctionAppName."
            return
        }

        # Add managed certificate to Function App
        Write-Verbose "Add Managed Certificate to Function App"
        foreach ($newCustomDomainToAdd in $newCustomDomainsToAdd) {
            Write-Verbose "Adding certificate for $newCustomDomainToAdd"
            $newAzWebAppCertificate = @{
                ResourceGroupName = $ResourceGroupName
                WebAppName        = $FunctionAppName
                Name              = "mtasts-cert-$($newCustomDomainToAdd.replace(".", "-"))"
                HostName          = $newCustomDomainToAdd
                AddBinding        = $true
                SslState          = "SniEnabled"
            }
            if ($PSCmdlet.ShouldProcess("Function App $FunctionAppName", "Add certificate for $newCustomDomainToAdd")) {
                $null = New-AzWebAppCertificate @newAzWebAppCertificate
            }
        }
    }
}

function Export-PSMTASTSDomainsFromExo {
    <#
        .SYNOPSIS
        Export-PSMTASTSDomainsFromExo
 
        .DESCRIPTION
        This script exports all domains from Exchange Online and checks, if the MX record points to Exchange Online. The result is exported to a .csv file.
 
        .PARAMETER DisplayResult
        Provide a Boolean value, if the result should be displayed in the console. Default is $true.
 
        .PARAMETER CsvPath
        Provide a String containing the path to the .csv file, where the result should be exported to.
 
        .PARAMETER DomainName
        Provide a PSCustomObject containing the result of Get-AcceptedDomain. If not provided, the script will run Get-AcceptedDomain itself.
 
        .PARAMETER DnsServer
        Provide a String containing the IP address of the DNS server, which should be used to query the MX record. Default is 8.8.8.8 (Google DNS).
 
        .PARAMETER ExoHost
        Provide a String containing the host name of the MX record, which should be used to check, if the MX record points to Exchange Online. Default is *.mail.protection.outlook.com.
 
        .PARAMETER CsvEncoding
        Provide encoding of csv file. Default is "UTF8".
 
        .PARAMETER CsvDelimiter
        Provide delimiter of csv file. Default is ";".
 
        .PARAMETER DnsServer
        Provide a String containing the IP address of the DNS server, which should be used to query the MX record. Default is 8.8.8.8 (Google DNS).
 
        .EXAMPLE
        Export-PSMTASTSDomainsFromExo -CsvPath "C:\Temp\ExoDomains.csv"
 
        Gets accepted domains from Exchange Online and checks, if the MX record points to Exchange Online. The result is exported to "C:\Temp\ExoDomains.csv".
 
        .EXAMPLE
        Get-AcceptedDomain -ResultSize 10 | Export-PSMTASTSDomainsFromExo -CsvPath "C:\Temp\ExoDomains.csv"
 
        Gets 10 accepted domains from Exchange Online and checks, if the MX record points to Exchange Online. The result is exported to "C:\Temp\ExoDomains.csv".
        If you want to filter the accepted domains first, you can do so and pipe it to the Export-PSMTASTSDomainsFromExo function.
 
        .EXAMPLE
        "contoso.com","fabrikam.com" | Export-PSMTASTSDomainsFromExo -CsvPath "C:\Temp\ExoDomains.csv"
 
        Checks if the MX record points to Exchange Online for the domains "contoso.com" and "fabrikam.com". The result is exported to "C:\Temp\ExoDomains.csv".
 
        .LINK
        https://github.com/jklotzsche-msft/PS.MTA-STS
    #>

    [CmdletBinding()]
    param(
        [string]
        $CsvPath = (Join-Path -Path $env:TEMP -ChildPath "$(Get-Date -Format yyyyMMddhhmmss)_mta-sts-export.csv"),

        [Parameter(ValueFromPipeline = $true)]
        [PSObject[]]
        $DomainName,

        [Bool]
        $DisplayResult = $true,

        [String]
        $DnsServer = "8.8.8.8",

        [string]
        $CsvEncoding = "UTF8",

        [string]
        $CsvDelimiter = ";",

        [Parameter(DontShow = $true)]
        [String]
        $ExoHost = "*.mail.protection.outlook.com"
    )
    
    begin {
        # Prepare result array
        $result = @()
    }
    
    process {
        # Preset ErrorActionPreference to Stop
        $ErrorActionPreference = "Stop"

        # Trap errors
        trap {
            Write-Error $_
            return
        }
        
        # Connect to Exchange Online, if not already connected
        $exchangeConnection = Get-ConnectionInformation -ErrorAction SilentlyContinue | Sort-Object -Property TokenExpiryTimeUTC -Descending | Select-Object -First 1 -ExpandProperty State
        if (($exchangeConnection -ne "Connected") -and ($null -eq $DomainName)) {
            Write-Warning "Connecting to Exchange Online"
            $null = Connect-ExchangeOnline -ShowBanner:$false
        }

        # Get either full list of accepted domains or the provided list of accepted domains
        if($null -eq $DomainName) {
            Write-Verbose "Getting all domains from Exchange Online and checking MX-Record. Please wait..."
            $acceptedDomains = Get-AcceptedDomain -ResultSize unlimited -ErrorAction Stop
        }
        else {
            Write-Verbose "Checking MX-Record for provided domains. Please wait..."
            $acceptedDomains = $DomainName | Get-AcceptedDomain -ErrorAction Stop
        }
        $acceptedDomains = $acceptedDomains | Sort-Object -Property Name

        $counter = 1
        foreach ($acceptedDomain in $acceptedDomains) {
            Write-Verbose "Checking $counter / $($acceptedDomains.count) - $($acceptedDomain.DomainName)"
            # Prepare result object
            $resultObject = [PSCustomObject]@{
                Name                  = $acceptedDomain.Name        # Name of the domain
                DomainName            = $acceptedDomain.DomainName  # Domain name
                MX_Record_Pointing_To = ""                          # MX Record pointing to Exchange Online or other host(s) found? (Yes/No)
                MTA_STS_TXTRecord     = ""                          # MTA-STS TXT Record
                MTA_STS_Policy        = ""                          # MTA-STS Policy, if available
                MTA_STS_CanBeUsed     = ""                          # Can MTA-STS be used? (Yes/No)
                TLSRPT                = ""                          # TLSRPT Record, if available
            }

            # Checking MTA-STS TXT Record
            # Example: _mta-sts.example.com. IN TXT "v=STSv1; id=20160831085700Z"
            $mtaStsDNSHost = "_mta-sts." + $acceptedDomain.DomainName
            $mtaStsTXTRecord = Resolve-PSMTASTSDnsName -Name $mtaStsDNSHost -Type TXT -Server $DnsServer -ErrorAction Stop | Where-Object {$_.Strings -match "v=STSv1"}

            if ($null -ne $mtaStsTXTRecord) {
                $resultObject.MTA_STS_TXTRecord = $mtaStsTXTRecord.strings -join " | " # Strings are joined, because multiple strings can be returned
            }

            # Checking MTA-STS Policy
            <# Example:
                version: STSv1
                mode: enforce
                mx: *.mail.protection.outlook.com
                max_age: 604800
            #>

            $mtaStsUri = "https://mta-sts.{0}/.well-known/mta-sts.txt" -f $acceptedDomain.DomainName
            Write-Verbose "...checking MTA-STS Policy file at $mtaStsUri"
            try {
                # Try to get the MTA-STS Policy file
                $mtaStsPolicyResponse = Invoke-WebRequest -URI $mtaStsUri -TimeoutSec 20 -ErrorAction SilentlyContinue
                $resultObject.MTA_STS_Policy = ($mtaStsPolicyResponse.Content).Trim() #.Replace("`r`n","")
            }
            catch {
                # If the MTA-STS Policy file is not available or other issues occur, the result will be set to "ERROR: $($_.Exception.InnerException.Message)"
                $resultObject.MTA_STS_Policy = "ERROR: $($_.Exception.InnerException.Message)"
            }

            # Checking TLSRPT Record
            # Example: _smtp._tls.example.com. IN TXT "v=TLSRPTv1;rua=mailto:reports@example.com"
            $tlsRptDNSHost = "_smtp._tls." + $acceptedDomain.DomainName
            $tlsRptRecord = Resolve-PSMTASTSDnsName -Name $tlsRptDNSHost -Type TXT -Server $DnsServer -ErrorAction Stop | Where-Object {$_.Strings -like "v=TLSRPTv1*"}

            if ($null -ne $tlsRptRecord) {
                $resultObject.TLSRPT = $tlsRptRecord.Strings[0]
            }

            # Checking MX Record
            # Example: example.com. IN MX 0 example-com.mail.protection.outlook.com.
            $mxRecord = Resolve-PSMTASTSDnsName -Name $acceptedDomain.DomainName -Type MX -Server $DnsServer -ErrorAction Stop

            $resultObject.MTA_STS_CanBeUsed = "No" # Default value
            # Check if the domain is an onmicrosoft.com domain
            if ($acceptedDomain.DomainName -like "*.onmicrosoft.com") {
                $resultObject.MX_Record_Pointing_To = "WARNING: You cannot configure MTA-STS for an onmicrosoft.com domain."
            }
            # Check if the MX record points to Exchange Online
            elseif (($mxRecord.NameExchange.count -eq 1) -and ($mxRecord.NameExchange -like $ExoHost)) {
                $resultObject.MX_Record_Pointing_To = $mxRecord.NameExchange
                # Check if MTA-STS can be used (TXT record and Policy file are configured)
                if (("" -eq $resultObject.MTA_STS_TXTRecord) -and ("" -eq $resultObject.MTA_STS_Policy)) {
                    $resultObject.MTA_STS_CanBeUsed = "Yes"
                }
                elseif (("" -ne $resultObject.MTA_STS_TXTRecord) -and ($resultObject.MTA_STS_Policy -like "ERROR: *" -or "" -eq $resultObject.MTA_STS_Policy)) {
                    $resultObject.MTA_STS_CanBeUsed = "WARNING: MTA-STS TXT record is configured, but MTA-STS Policy file is not available."
                }
                elseif (("" -eq $resultObject.MTA_STS_TXTRecord) -and ("" -ne $resultObject.MTA_STS_Policy)) {
                    $resultObject.MTA_STS_CanBeUsed = "INFORMATION: MTA-STS TXT record is not configured, but MTA-STS Policy file is configured."
                }
                else {
                    $resultObject.MTA_STS_CanBeUsed = "COMPLETED: MTA-STS TXT record and MTA-STS Policy file are configured. Please double-check the content of the MTA-STS Policy file."
                }
            }
            # Check if the MX record points to another host than Exchange Online or if multiple MX records were found
            elseif (($mxRecord.NameExchange.count -gt 1) -or ($mxRecord.NameExchange -notlike $ExoHost)) {
                $resultObject.MX_Record_Pointing_To = "WARNING: MX Record does not point to Exchange Online (only). The following host(s) was/were found: $($mxRecord.NameExchange -join ", ")"
            }
            # Assume, that no MX record was found
            else {
                $resultObject.MX_Record_Pointing_To = "ERROR: No MX record found. Please assure, that the MX record for $($acceptedDomain.DomainName) points to Exchange Online."
            }
        
            # Add the result to the result array
            Write-Verbose "...adding result to result array."
            $result += $resultObject

            # Increase the counter for verbose output
            $counter++
        }
    }
    
    end {
        # Output the result in a new PowerShell window
        $domainsToExport = $result
        if($DisplayResult) {
            Write-Warning "Please select/highlight the domains you want to configure MTA-STS for in the new PowerShell window and click OK. You can select multiple entries by holding the CTRL key OR by selecting your first entry, then holding the SHIFT key and selecting your last entry."
            $domainsToExport = $result | Sort-Object -Property MTA_STS_CanBeUsed, Name | Out-GridView -Title "Please select the domains you want to configure MTA-STS for and click OK." -PassThru
        }

        # Check if the user selected any domains
        if ($null -eq $domainsToExport) {
            Write-Verbose "No domains selected. Exiting."
            return
        }

        # Export the result to a .csv file
        Write-Warning "Exporting $($domainsToExport.count) domain(s) to $CsvPath"
        $domainsToExport | Export-Csv -Path $CsvPath -Delimiter $CsvDelimiter -Encoding $CsvEncoding -NoTypeInformation -Force
    }
}

function Get-PSMTASTSCustomDomain {
    <#
        .SYNOPSIS
        Get-PSMTASTSCustomDomain gets custom domains of MTA-STS Function App.
 
        .DESCRIPTION
        Get-PSMTASTSCustomDomain gets custom domains of MTA-STS Function App.
 
        .PARAMETER ResourceGroupName
        Provide name of Resource Group where Function App is located.
 
        .PARAMETER FunctionAppName
        Provide name of Function App.
 
        .EXAMPLE
        Get-PSMTASTSCustomDomain -ResourceGroupName "MTA-STS" -FunctionAppName "MTA-STS-FunctionApp"
 
        Gets list of custom domains of Function App "MTA-STS-FunctionApp" in Resource Group "MTA-STS".
 
        .EXAMPLE
        [PSCustomObject]@{
            ResourceGroupName = "rg-MTASTS001"
            FunctionAppName = "func-MTASTS-Enforce"
        },
        [PSCustomObject]@{
            ResourceGroupName = "rg-MTASTS002"
            FunctionAppName = "func-MTASTS-Testing"
        } | Get-PSMTASTSCustomDomain
 
        Gets list of custom domains of Function App "func-MTASTS-Enforce" in Resource Group "rg-MTASTS001" and Function App "func-MTASTS-Testing" in Resource Group "rg-MTASTS002".
        The result will be a list of custom domains, default domain and SSLStates of both Function Apps.
 
        .LINK
        https://github.com/jklotzsche-msft/PS.MTA-STS
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [String]
        $ResourceGroupName,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [String]
        $FunctionAppName
    )
    
    begin {
        # Check if PowerShell is connected to Azure
        if ( -not (Get-AzContext)) {
            Write-Warning "Connecting to Azure service..."
            $null = Connect-AzAccount -ErrorAction Stop
        }
    }
    
    process {
        Write-Verbose "Getting domains of Function App $FunctionAppName..."
        Get-AzWebApp -ResourceGroupName $ResourceGroupName -Name $FunctionAppName -ErrorAction Stop | Select-Object -Property @{
            Name = "CustomDomains"
            Expression = {
                if ($null -ne $_.HostNames) {
                    $_.HostNames | Where-Object { $_ -notlike "*.azurewebsites.net" }
                }
            }
        },
        @{
            Name = "DefaultDomain"
            Expression = {
                if ($null -ne $_.DefaultHostName) {
                    $_.DefaultHostName
                }
            }
        },
        @{
            Name = "SSLState"
            Expression = {
                if ($null -ne $_.HostNameSslStates) {
                    $_.HostNameSslStates | Select-Object -Property Name,SslState,Thumbprint | Sort-Object -Property Name
                }
            }
        }
    }
}

function New-PSMTASTSFunctionAppDeployment {
    <#
    .SYNOPSIS
        Creates an Azure Function App with the needed PowerShell code to publish MTA-STS policies.
 
    .DESCRIPTION
        Creates an Azure Function App with the needed PowerShell code to publish MTA-STS policies.
        The Azure Function App will be created in the specified resource group and location.
        If the resource group doesn't exist, it will be created.
        If the Azure Function App doesn't exist, it will be created.
        If the Azure Function App exists, it will be updated with the latest PowerShell code. This will overwrite any changes you made to the Azure Function App!
 
    .PARAMETER Location
        Provide the Azure location, where the Azure Function App should be created.
        You can get a list of all available locations by running 'Get-AzLocation | Select-Object -ExpandProperty location | Sort-Object'
     
    .PARAMETER ResourceGroupName
        Provide the name of the Azure resource group, where the Azure Function App should be created.
        If the resource group doesn't exist, it will be created.
        If the resource group exists already, it will be used.
     
    .PARAMETER FunctionAppName
        Provide the name of the Azure Function App, which should be created.
        If the Azure Function App doesn't exist, the Azure Storace Account and Azure Function App will be created.
        If the Azure Function App exists, it will be updated with the latest PowerShell code. This will overwrite any changes you made to the Azure Function App!
         
    .PARAMETER StorageAccountName
        Provide the name of the Azure Storage Account, which should be created.
        If the Azure Function App doesn't exist, the Azure Storace Account and Azure Function App will be created.
 
    .PARAMETER PolicyMode
        Specifies if the policy is in "Enforce" mode or "Testing" mode
 
    .PARAMETER DnsServer
        Provide a String containing the IP address of the DNS server, which should be used to query the MX record. Default is 8.8.8.8 (Google DNS).
 
    .PARAMETER WhatIf
        If this switch is provided, no changes will be made. Only a summary of the changes will be shown.
 
    .PARAMETER Confirm
        If this switch is provided, you will be asked for confirmation before any changes are made.
 
    .EXAMPLE
        New-PSMTASTSFunctionAppDeployment -Location 'West Europe' -ResourceGroupName 'rg-PSMTASTS' -FunctionAppName 'func-PSMTASTS' -StorageAccountName 'stpsmtasts'
         
        Creates an Azure Function App with the name 'PSMTASTS' in the resource group 'PSMTASTS' in the location 'West Europe' with policy mode 'Enforce'.
        If the resource group doesn't exist, it will be created.
        If the Azure Function App doesn't exist, it will be created and app files published.
 
    .LINK
        https://github.com/jklotzsche-msft/PS.MTA-STS
    #>


    #region Parameter
    [CmdletBinding(SupportsShouldProcess = $true)]
    Param (
        [Parameter(Mandatory = $true)]
        [String]
        $Location,

        [Parameter(Mandatory = $true)]
        [ValidateScript({
                if ($_.length -lt 1 -or $_.length -gt 90 -or $_ -notmatch "^[a-zA-Z0-9\.-]*$") {
                    throw "ResourceGroup name '$_' is not valid. The name must be between 1 and 90 characters long and can contain only letters, numbers, hyphens and periods."
                }
                else {
                    $true
                }
            })]
        [String]
        $ResourceGroupName,

        [Parameter(Mandatory = $true)]
        [ValidateScript({
                if ($_.length -lt 2 -or $_.length -gt 60 -or $_ -notmatch "^[a-z0-9-]*$") {
                    throw "Function App name '$_' is not valid. The name must be between 2 and 60 characters long and can contain only lowercase letters, numbers and hyphens."
                }
                else {
                    $true
                }
            })]
        [String]
        $FunctionAppName,

        [Parameter(Mandatory = $true)]
        [ValidateScript({
                if ($_.length -lt 3 -or $_.length -gt 24 -or $_ -notmatch "^[a-z0-9]*$") {
                    throw "Storage Account name '$_' is not valid. The name must be between 3 and 24 characters long and can contain only lowercase letters and numbers."
                }
                else {
                    $true
                }
            })]
        [String]
        $StorageAccountName,

        [ValidateSet("Enforce", "Testing", "None")] # ValidateSet is used to limit the possible values
        [String]
        $PolicyMode = "Enforce",

        [String]
        $DnsServer = "8.8.8.8"
    )
    #endregion Parameter

    begin {
        # Check if PowerShell is connected to Azure
        if ( -not (Get-AzContext)) {
            Write-Warning "Connecting to Azure service..."
            $null = Connect-AzAccount -ErrorAction Stop
        }
    }
    
    process {
        # Preset ErrorActionPreference to Stop
        $ErrorActionPreference = "Stop"

        # Trap errors
        trap {
            Write-Error $_
            return
        }
        
        # Check, if Location is valid
        Write-Verbose "Checking if location '$($Location)' is valid."
        $validLocations = Get-AzLocation | Select-Object -ExpandProperty location
        if (-not ($Location -in $validLocations)) {
            throw "Location '$($Location)' is not valid. Please provide one of the following values: $($validLocations -join ', ')"
        }

        # Create, if resource group doesn't exist already. If it doesn't exist, create it.
        Write-Verbose "Checking if ResourceGroup '$ResourceGroupName' already exists"
        if ($null -eq (Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction SilentlyContinue)) {
            Write-Verbose "Creating Azure Resource Group '$ResourceGroupName'..."
            if ($PSCmdlet.ShouldProcess("Resource Group $ResourceGroupName", "Create")) {
                $null = New-AzResourceGroup -Name $ResourceGroupName -Location $Location
            }
        }

        # Set default resource group for future cmdlets in this powershell session
        $null = Set-AzDefault -ResourceGroupName $ResourceGroupName

        # Check if Storage StorageAccountName already exists
        $storageAccountDnsResult = Resolve-PSMTASTSDnsName -Name "$StorageAccountName.blob.core.windows.net" -Type A -Server $DnsServer -ErrorAction Stop
        if ($null -ne $storageAccountDnsResult) {
            throw "Storage Account already exists. Please provide a different name for the Storage Account."
        }

        # Check, if FunctionApp exists already
        $functionAppDnsResult = Resolve-PSMTASTSDnsName -Name "$FunctionAppName.azurewebsites.net" -Type A -Server $DnsServer -ErrorAction Stop
        if ($null -ne $functionAppDnsResult) {
            throw "Function App already exists. Please provide a different name for the Function Account."
        }

        # Create Storage Account
        Write-Verbose "Creating Azure Storage Account $StorageAccountName..."
        $newAzStorageAccountProps = @{
            ResourceGroupName     = $ResourceGroupName
            Name                  = $StorageAccountName
            Location              = $Location
            SkuName               = 'Standard_LRS'
            AllowBlobPublicAccess = $false
            ErrorAction           = 'Stop'
        }
        if ($PSCmdlet.ShouldProcess("Storage Account $StorageAccountName", "Create")) {
            $null = New-AzStorageAccount @newAzStorageAccountProps
        }

        # Create Function App
        Write-Verbose "Creating Azure Function App $FunctionAppName..."
        $newAzFunctionAppProps = @{
            ResourceGroupName  = $ResourceGroupName
            Name               = $FunctionAppName
            Location           = $Location
            Runtime            = 'PowerShell'
            StorageAccountName = $StorageAccountName
            FunctionsVersion   = '4'
            OSType             = 'Windows'
            RuntimeVersion     = '7.2'
            ErrorAction        = 'Stop'
        }
        if ($PSCmdlet.ShouldProcess("Function App $FunctionAppName", "Create")) {
            $null = New-AzFunctionApp @newAzFunctionAppProps
        }

        # Wait for Function App to be ready
        Write-Verbose "Waiting for Azure Function App $FunctionAppName to be ready..."
        $null = Start-Sleep -Seconds 60

        # Update the Azure Function App files with the latest PowerShell code
        $updateFunctionAppProps = @{
            ResourceGroupName = $ResourceGroupName
            FunctionAppName   = $FunctionAppName
            PolicyMode        = $PolicyMode
        }
        if ($PSCmdlet.ShouldProcess("Function App $FunctionAppName", "Update")) {
            $null = Update-PSMTASTSFunctionAppFile @updateFunctionAppProps
        }
    }
}

function Remove-PSMTASTSCustomDomain {
    <#
        .SYNOPSIS
        Remove-PSMTASTSCustomDomain removes custom domains from MTA-STS Function App.
 
        .DESCRIPTION
        Remove-PSMTASTSCustomDomain removes custom domains from MTA-STS Function App. It does not remove AzWebAppCertificates, as they could be used elsewhere.
 
        .PARAMETER CsvPath
        Provide path to csv file with accepted domains. Csv file should have one column with header "DomainName" and list of domains in each row.
 
        .PARAMETER DomainName
        Provide list of domains.
 
        .PARAMETER ResourceGroupName
        Provide name of Resource Group where Function App is located.
 
        .PARAMETER FunctionAppName
        Provide name of Function App.
 
        .PARAMETER CsvEncoding
        Provide encoding of csv file. Default is "UTF8".
 
        .PARAMETER CsvDelimiter
        Provide delimiter of csv file. Default is ";".
 
        .PARAMETER WhatIf
        Switch to run the command in a WhatIf mode.
 
        .PARAMETER Confirm
        Switch to run the command in a Confirm mode.
 
        .EXAMPLE
        Remove-PSMTASTSCustomDomain -CsvPath "C:\temp\accepted-domains.csv" -ResourceGroupName "MTA-STS" -FunctionAppName "MTA-STS-FunctionApp"
 
        Reads list of accepted domains from "C:\temp\accepted-domains.csv" and removes them from Function App "MTA-STS-FunctionApp" in Resource Group "MTA-STS".
 
        .EXAMPLE
        Remove-PSMTASTSCustomDomain -DomainName "contoso.com", "fabrikam.com" -ResourceGroupName "MTA-STS" -FunctionAppName "MTA-STS-FunctionApp"
 
        Removes domains "contoso.com" and "fabrikam.com" from Function App "MTA-STS-FunctionApp" in Resource Group "MTA-STS".
 
        .LINK
        https://github.com/jklotzsche-msft/PS.MTA-STS
    #>

    [CmdletBinding(SupportsShouldProcess = $true, DefaultParameterSetName = "Csv")]
    param (
        [Parameter(Mandatory = $true, ParameterSetName = "Csv")]
        [string]
        $CsvPath,

        [Parameter(Mandatory = $true, ParameterSetName = "Manual")]
        [string[]]
        $DomainName,

        [Parameter(Mandatory = $true)]
        [string]
        $ResourceGroupName,

        [Parameter(Mandatory = $true)]
        [string]
        $FunctionAppName,

        [Parameter(ParameterSetName = "Csv")]
        [string]
        $CsvEncoding = "UTF8",

        [Parameter(ParameterSetName = "Csv")]
        [string]
        $CsvDelimiter = ";"
    )
    
    begin {
        # Check, if we are connected to Azure
        if ($null -eq (Get-AzContext)) {
            Write-Warning "Connecting to Azure service"
            $null = Connect-AzAccount -ErrorAction Stop
        }

        # Import csv file with accepted domains
        if ($CsvPath) {
            Write-Verbose "Importing csv file from $CsvPath"
            $domainList = Import-Csv -Path $CsvPath -Encoding $CsvEncoding -Delimiter $CsvDelimiter -ErrorAction Stop | Select-Object -ExpandProperty DomainName
        }

        # Import domains from input parameter
        if ($DomainName) {
            Write-Verbose "Creating array of domains from input parameter"
            $domainList = @()
            foreach ($domain in $DomainName) { $domainList += $domain }
        }

        # Check, if domains have correct format
        foreach ($domain in $domainList) {
            if ($domain -notmatch "^[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$") {
                Write-Error -Message "Domain $domain has incorrect format. Please provide domain in format 'contoso.com'."
                return
            }
        }
    }

    process {
        # Preset ErrorActionPreference to Stop
        $ErrorActionPreference = "Stop"

        # Trap errors
        trap {
            Write-Error $_
            return
        }

        #Check FunctionApp
        Write-Verbose "Get Azure Function App $FunctionAppName in Resource Group $ResourceGroupName"
        $FunctionAppResult = Get-AzFunctionApp -ResourceGroupName $ResourceGroupName -Name $FunctionAppName -WarningAction SilentlyContinue
        if ($null -eq $FunctionAppResult) {
            #Function App not found
            throw "FunctionApp $FunctionAppName not found"
        }

        #Get CustomDomain Names
        Write-Verbose "Get CustomDomainNames from Azure Function App $FunctionAppName"
        $customDomainNames = Get-PSMTASTSCustomDomain -ResourceGroupName $ResourceGroupName -FunctionAppName $FunctionAppName -ErrorAction Stop

        # Prepare new domains
        $removeCustomDomains = @()
        foreach ($domain in $domainList) {
            #Check if CustomDomain is added as Custom Domain
            $mtaStsDomain = "mta-sts." + $domain
            if ($mtaStsDomain -in $CustomDomainNames.CustomDomains) {
                #Custom Domain is present
                Write-Verbose "Adding Domain to Array of Domains to remove: $mtaStsDomain"
                $removeCustomDomains += $mtaStsDomain
            }
        }

        # Check, if there are new domains to remove
        if ($removeCustomDomains.count -eq 0) {
            Write-Warning "No domains to remove from Function App $FunctionAppName. Stopping here."
            return
        }

        # Add the current domains to the list of domains to remove
        $newCustomDomains = Compare-Object -ReferenceObject $CustomDomainNames.CustomDomains -DifferenceObject $removeCustomDomains | Where-Object -FilterScript {$_.SideIndicator -eq "<="} | Select-Object -ExpandProperty InputObject
        $customDomainsToSet = @()
        $customDomainsToSet += $customDomainNames.DefaultDomain # Add default domain
        $customDomainsToSet += $newCustomDomains # Add custom domains to keep

        # Remove domains from Function App
        Write-Verbose "Removing $($removeCustomDomains.count) domains from Function App $FunctionAppName : $($removeCustomDomains -join ", ")..."
        $setAzWebApp = @{
            ResourceGroupName = $ResourceGroupName
            Name              = $FunctionAppName
            HostNames         = $customDomainsToSet
            ErrorAction       = "Stop"
            WarningAction     = "Stop"
        }
        if ($PSCmdlet.ShouldProcess("Function App $FunctionAppName", "Remove custom domains")) {
            $null = Set-AzWebApp @setAzWebApp
        }

        #Remove Managed Certificate if needed
        Write-Verbose "Remove Certificates"
        [Array]$webAppCertificates = Get-AzWebAppCertificate -ResourceGroupName $ResourceGroupName
        foreach ($certificate in $webAppCertificates) {
            $subjectName = $certificate.SubjectName
            if ($subjectName -in $removeCustomDomains) {
                #Get Thumbprint of Certificate
                $thumbprint = $certificate.Thumbprint
                
                #Remove Managed Certificate
                Write-Verbose "Remove Managed Certificate: $subjectName Thumbprint: $thumbprint"
                if ($PSCmdlet.ShouldProcess("Subject: $subjectName, Thumbprint: $thumbprint", "Remove managed certificate")) {
                    # If an error occurs during certificate removal, continue with the next certificate removal as the certificate might be used elsewhere
                    # If we do not continue anyways, users would have to remove the certificate manually for next domains
                    $null = Remove-AzWebAppCertificate -ResourceGroupName $ResourceGroupName -Thumbprint $thumbprint -Confirm:$false -ErrorAction Continue
                }
            }
        }
    }
}

function Test-PSMTASTSConfiguration {
    <#
        .SYNOPSIS
        Test-PSMTASTSConfiguration checks if MTA-STS is configured correctly for all domains in a CSV file.
 
        .DESCRIPTION
        Test-PSMTASTSConfiguration checks if MTA-STS is configured correctly for all domains in a CSV file.
        It checks if the...
        - ...TXT record is configured correctly,
        - ...CNAME record is configured correctly,
        - ...policy file is available and
        - ...MX record is configured correctly.
 
        .PARAMETER CsvPath
        Provide path to csv file with accepted domains.
        Csv file should have one column with header "DomainName" and list of domains in each row.
 
        .PARAMETER DomainName
        Provide list of domains.
 
        .PARAMETER DnsServer
        Provide IP address of DNS server to use for DNS queries. Default is 8.8.8.8 (Google DNS).
 
        .PARAMETER DisplayResult
        Provide a Boolean value, if the result should be displayed in the console. Default is $true.
 
        .PARAMETER FunctionAppName
        Provide name of Function App.
 
        .PARAMETER ExportResult
        Switch Parameter. Export result to CSV file.
         
        .PARAMETER ResultPath
        Provide path to CSV file where result should be exported. Default is "C:\temp\mta-sts-result.csv".
 
        .PARAMETER CsvEncoding
        Provide encoding of csv file. Default is "UTF8".
 
        .PARAMETER CsvDelimiter
        Provide delimiter of csv file. Default is ";".
 
        .PARAMETER ExoHost
        Provide a String containing the host name of the MX record, which should be used to check, if the MX record points to Exchange Online. Default is *.mail.protection.outlook.com.
 
        .EXAMPLE
        Test-PSMTASTSConfiguration -CsvPath "C:\temp\accepted-domains.csv" -FunctionAppName "MTA-STS-FunctionApp"
 
        Reads list of accepted domains from "C:\temp\accepted-domains.csv" and checks if MTA-STS is configured correctly for each domain in Function App "MTA-STS-FunctionApp".
 
        .EXAMPLE
        Test-PSMTASTSConfiguration -CsvPath "C:\temp\accepted-domains.csv" -FunctionAppName "MTA-STS-FunctionApp" -ExportResult -ResultPath "C:\temp\mta-sts-result.csv"
 
        Reads list of accepted domains from "C:\temp\accepted-domains.csv" and checks if MTA-STS is configured correctly for each domain in Function App "MTA-STS-FunctionApp". It also exports result to "C:\temp\mta-sts-result.csv".
    #>

    [CmdletBinding(DefaultParameterSetName = "CsvWithExport")]
    param(
        [Parameter(Mandatory = $true, ParameterSetName = "CsvWithExport")]
        [Parameter(Mandatory = $true, ParameterSetName = "CsvWithoutExport")]
        [string]
        $CsvPath,

        [Parameter(Mandatory = $true, ParameterSetName = "ManualWithExport")]
        [Parameter(Mandatory = $true, ParameterSetName = "ManualWithoutExport")]
        [string[]]
        $DomainName,

        [Parameter(Mandatory = $true, ParameterSetName = "CsvWithExport")]
        [Parameter(Mandatory = $true, ParameterSetName = "CsvWithoutExport")]
        [Parameter(Mandatory = $true, ParameterSetName = "ManualWithExport")]
        [Parameter(Mandatory = $true, ParameterSetName = "ManualWithoutExport")]
        [string]
        $FunctionAppName,

        [String]
        $DnsServer = "8.8.8.8",

        [Bool]
        $DisplayResult = $true,

        [Parameter(ParameterSetName = "CsvWithExport")]
        [Parameter(ParameterSetName = "ManualWithExport")]
        [Switch]
        $ExportResult,
    
        [Parameter(ParameterSetName = "CsvWithExport")]
        [Parameter(ParameterSetName = "ManualWithExport")]
        [String]
        $ResultPath = (Join-Path -Path $env:TEMP -ChildPath "$(Get-Date -Format yyyyMMddhhmmss)_mta-sts-test-result.csv"),

        [string]
        $CsvEncoding = "UTF8",

        [string]
        $CsvDelimiter = ";",

        [Parameter(DontShow = $true)]
        [String]
        $ExoHost = "*.mail.protection.outlook.com"
    )

    begin {
        # Prepare result array
        $result = @()

        # Import csv file with accepted domains
        if ($CsvPath) {
            Write-Verbose "Importing csv file from $CsvPath"
            $domainList = Import-Csv -Path $CsvPath -Encoding $CsvEncoding -Delimiter $CsvDelimiter -ErrorAction Stop | Select-Object -ExpandProperty DomainName
        }
    }

    process {
        # Preset ErrorActionPreference to Stop
        $ErrorActionPreference = "Stop"

        # Trap errors
        trap {
            Write-Error $_
            return
        }

        # Import domains from input parameter
        if ($DomainName) {
            Write-Verbose "Creating array of domains from input parameter"
            $domainList = @()
            foreach ($domain in $DomainName) { $domainList += $domain }
        }

        # Check, if domains have correct format
        foreach ($domain in $domainList) {
            if ($domain -notmatch "^[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$") {
                Write-Error -Message "Domain $domain has incorrect format. Please provide domain in format 'contoso.com'."
                return
            }
        }

        # Prepare variables
        $txtRecordContent = "v=STSv1; id=*Z;"
        $mtaStsPolicyFileContent = @"
version: STSv1
mode: *
mx: $ExoHost
max_age: 604800
"@

        $counter = 1

        # Loop through all domains
        foreach ($domain in $domainList) {
            Write-Verbose "Checking $counter / $($domainList.count) - $($domain)"
            # Prepare result object
            $resultObject = [PSCustomObject]@{
                DomainName            = $domain
                Host                  = "$FunctionAppName.azurewebsites.net"
                MX_Record_Pointing_To = ""
                MX_Record_Result      = ""
                MTA_STS_CNAME         = ""
                MTA_STS_Policy        = ""
                MTA_STS_PolicyContent = ""
                MTA_STS_TXTRecord     = ""
                MTA_STS_OVERALL       = "OK"
                TLSRPT                = ""
            }

            # Checking MTA-STS TXT Record
            # Example: _mta-sts.example.com. IN TXT "v=STSv1; id=20160831085700Z"
            $mtaStsDNSHost = "_mta-sts." + $domain
            $mtaStsTXTRecord = Resolve-PSMTASTSDnsName -Name $mtaStsDNSHost -Type TXT -Server $DnsServer -ErrorAction Stop | Where-Object { $_.Strings -match "v=STSv1" }

            if ($mtaStsTXTRecord -and ($mtaStsTXTRecord.strings -like $txtRecordContent)) {
                $resultObject.MTA_STS_TXTRecord = "OK"
            }
            elseif ($mtaStsTXTRecord -and ($mtaStsTXTRecord.strings -notlike $txtRecordContent)) {
                $resultObject.MTA_STS_TXTRecord = "TXT record does not contain the expected content. The following content was found: $($txtRecord.strings -join ", ")"
                $resultObject.MTA_STS_OVERALL = "ISSUE_FOUND"
            }
            else {
                $resultObject.MTA_STS_TXTRecord = "TXT record was not found."
                $resultObject.MTA_STS_OVERALL = "ISSUE_FOUND"
            }

            # Check MTA-STS CNAME record
            $mtaStsName = "mta-sts." + $domain
            $cnameRecord = Resolve-PSMTASTSDnsName -Name $mtaStsName -Type CNAME -Server $DnsServer -ErrorAction Stop

            if ($cnameRecord -and ($resultObject.Host -eq $cnameRecord.NameHost)) {
                $resultObject.MTA_STS_CNAME = "OK"
            }
            elseif ($cnameRecord -and ($resultObject.Host -ne $cnameRecord.NameHost)) {
                $resultObject.MTA_STS_CNAME = "CNAME record does not contain the expected content. The following content was found: $($cnameRecord.NameHost -join ", ")"
                $resultObject.MTA_STS_OVERALL = "ISSUE_FOUND"
            }
            else {
                $resultObject.MTA_STS_CNAME = "CNAME record was not found. Please check if the CNAME record for $mtaStsName points to the Function App $($resultObject.Host)."
                $resultObject.MTA_STS_OVERALL = "ISSUE_FOUND"
            }
    
            # Checking MTA-STS Policy
            <# Example:
                version: STSv1
                mode: enforce
                mx: *.mail.protection.outlook.com
                max_age: 604800
            #>

            $mtaStsUri = "https://mta-sts.{0}/.well-known/mta-sts.txt" -f $domain
            Write-Verbose "...checking MTA-STS Policy file at $mtaStsUri"
            
            try {
                $mtaStsPolicyResponse = Invoke-WebRequest -Uri $mtaStsUri -TimeoutSec 20 -ErrorAction SilentlyContinue
                $resultObject.MTA_STS_PolicyContent = ($mtaStsPolicyResponse.Content).Trim()
            }
            catch {
                $resultObject.MTA_STS_Policy = "ERROR"
                $resultObject.MTA_STS_PolicyContent = $_.Exception.Message
                $resultObject.MTA_STS_OVERALL = "ISSUE_FOUND"
            }

            if (($resultObject.MTA_STS_PolicyContent -like $mtaStsPolicyFileContent) -and (($resultObject.MTA_STS_PolicyContent -like "*mode: enforce*") -or ($resultObject.MTA_STS_PolicyContent -like "*mode: testing*") -or ($resultObject.MTA_STS_PolicyContent -like "*mode: none*"))) {
                $resultObject.MTA_STS_Policy = "OK"
            }
            else {
                $resultObject.MTA_STS_Policy = "Policy file does not contain the expected content."
                $resultObject.MTA_STS_OVERALL = "ISSUE_FOUND"
            }

            # Checking TLSRPT Record
            # Example: _smtp._tls.example.com. IN TXT "v=TLSRPTv1;rua=mailto:reports@example.com"
            $tlsRptDNSHost = "_smtp._tls." + $domain
            $tlsRptRecord = Resolve-PSMTASTSDnsName -Name $tlsRptDNSHost -Type TXT -Server $DnsServer -ErrorAction Stop | Where-Object -FilterScript {$_.Strings -like "v=TLSRPTv1*"}

            if ($null -ne $tlsRptRecord) {
                $resultObject.TLSRPT = $tlsRptRecord.Strings[0]
            }

            # Checking MX Record
            # Example: example.com. IN MX 0 example-com.mail.protection.outlook.com.
            $mxRecord = Resolve-PSMTASTSDnsName -Name $domain -Type MX -Server $DnsServer -ErrorAction Stop

            $resultObject.MX_Record_Pointing_To = $mxRecord.NameExchange -join ", "

            # Check if the domain is an onmicrosoft.com domain
            if ($domain -like "*.onmicrosoft.com") {
                $resultObject.MX_Record_Result = "WARNING: You cannot configure MTA-STS for an onmicrosoft.com domain."
                $resultObject.MTA_STS_OVERALL = "ISSUE_FOUND"
            }
            # Check if the MX record points to Exchange Online
            elseif (($mxRecord.NameExchange.count -eq 1) -and ($mxRecord.NameExchange -like $ExoHost)) {
                # MX record points to Exchange Online (only)
                $resultObject.MX_Record_Result = "OK"
            }
            # Check if the MX record points to another host than Exchange Online or if multiple MX records were found
            elseif (($mxRecord.NameExchange.count -gt 1) -or ($mxRecord.NameExchange -notlike $ExoHost)) {
                $resultObject.MX_Record_Result = "WARNING: MX Record does not point to Exchange Online (only). The following host(s) was/were found: $($mxRecord.NameExchange -join ", ")"
            }
            # Assume, that no MX record was found
            else {
                $resultObject.MX_Record_Result = "ERROR: No MX record found. Please assure, that the MX record for $domain points to Exchange Online."
            }

            # Add the result to the result array
            Write-Verbose "...adding result to result array."
            $result += $resultObject

            # Increase the counter for verbose output
            $counter++
        }

        # Output the result in a new PowerShell window
        if ($DisplayResult) {
            Write-Warning "Please check the results in the new PowerShell window."
            $result | Out-GridView -Title "Test MTA-STS Configuration"
        }

        # Export result to CSV
        if ($ExportResult) {
            Write-Warning "Exporting result to $ResultPath"
            $result | Export-Csv -Path $ResultPath -Encoding UTF8 -Delimiter ";" -NoTypeInformation
        }
    }
}

function Update-PSMTASTSFunctionAppFile {
    <#
    .SYNOPSIS
        Publishes Azure Function App files and functions to Azure Function App.
 
    .DESCRIPTION
        Publishes Azure Function App files and functions to Azure Function App.
        The Azure Function App will be updated with the latest PowerShell code.
        This will overwrite any changes you may have made to the Azure Function App!
         
    .PARAMETER ResourceGroupName
        Provide the name of the Azure resource group, where the Azure Function App should be updated.
     
    .PARAMETER FunctionAppName
        Provide the name of the Azure Function App, which should be updated.
 
    .PARAMETER PolicyMode
        Specifies if the policy is in "Enforce" mode or "Testing" mode
 
    .PARAMETER WhatIf
        If this switch is provided, no changes will be made. Only a summary of the changes will be shown.
 
    .PARAMETER Confirm
        If this switch is provided, you will be asked for confirmation before any changes are made.
         
    .EXAMPLE
        Update-PSMTASTSFunctionAppFile -ResourceGroupName 'rg-PSMTASTS' -FunctionAppName 'func-PSMTASTS' -PolicyMode 'Testing'
         
        Updates the Azure Function App with the name 'PSMTASTS' in the resource group 'PSMTASTS' with policy mode 'Testing'.
        This will overwrite any changes you made to the Azure Function App!
 
    .LINK
        https://github.com/jklotzsche-msft/PS.MTA-STS
    #>


    #region Parameter
    [CmdletBinding(SupportsShouldProcess = $true)]
    Param (
        [Parameter(Mandatory = $true)]
        [String]
        $ResourceGroupName,

        [Parameter(Mandatory = $true)]
        [String]
        $FunctionAppName,

        [ValidateSet("Enforce", "Testing", "None")] # ValidateSet is used to limit the possible values
        [String]
        $PolicyMode = "Enforce"
    )
    #endregion Parameter

    begin {
        # Check if PowerShell is connected to Azure
        if ( -not (Get-AzContext)) {
            Write-Warning "Connecting to Azure service..."
            $null = Connect-AzAccount -ErrorAction Stop
        }
    }
    
    process {
        # Preset ErrorActionPreference to Stop
        $ErrorActionPreference = "Stop"

        # Trap errors
        trap {
            Write-Error $_

            # Clean up, if needed
            if (Test-Path -Path $workingDirectory) {
                $null = Remove-Item -Path $workingDirectory -Recurse -Force
            }

            return
        }

        # Set working directory for temporary files
        $workingDirectory = Join-Path -Path $env:TEMP -ChildPath "PS.MTA-STS_deployment"

        # Create, if resource group doesn't exist already. If it doesn't exist, create it.
        Write-Verbose "Checking if ResourceGroup '$ResourceGroupName' already exists"
        if ($null -eq (Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction SilentlyContinue)) {
            throw "ResourceGroup '$ResourceGroupName' does not exist. Please create it first."
        }

        # Set default resource group for future cmdlets in this powershell session
        $null = Set-AzDefault -ResourceGroupName $ResourceGroupName

        # Check, if FunctionApp exists already
        Write-Verbose "Checking if Function Account exists in DNS"
        $functionApp = Get-AzFunctionApp -ResourceGroupName $ResourceGroupName -Name $FunctionAppName -WarningAction SilentlyContinue
        if ($null -eq $functionApp) {
            throw "Function App '$FunctionAppName' does not exist. Please create it first using 'New-PSMTASTSFunctionAppDeployment'."
        }

        # Create Function App contents in temporary folder and zip it
        Write-Verbose "Creating Function App content in temp folder..."
        if (Test-Path -Path $workingDirectory) {
            $null = Get-ChildItem -Path $workingDirectory -Recurse | Remove-Item -Recurse -Force -Confirm:$false
        }

        # Create Function App contents
        ## App files
        $null = New-Item -Path $workingDirectory -ItemType Directory -ErrorAction SilentlyContinue
        $null = New-Item -Path "$workingDirectory/function" -ItemType Directory
        $null = $script:PSMTASTS_hostJson | Set-Content -Path "$workingDirectory/function/host.json" -Force
        $null = $script:PSMTASTS_profilePs1 | Set-Content -Path "$workingDirectory/function/profile.ps1" -Force
        $null = $script:PSMTASTS_requirementsPsd1 | Set-Content -Path "$workingDirectory/function/requirements.psd1" -Force
        ## Root Website function
        $null = New-Item -Path "$workingDirectory/function/WebsiteRoot" -ItemType Directory
        $null = $script:Root_functionJson | Set-Content -Path "$workingDirectory/function/WebsiteRoot/function.json" -Force
        $null = $script:Root_runPs1 | Set-Content -Path "$workingDirectory/function/WebsiteRoot/run.ps1" -Force
        ## MTA-STS Policy function
        $null = New-Item -Path "$workingDirectory/function/MTASTS" -ItemType Directory
        $null = $script:PSMTASTS_functionJson | Set-Content -Path "$workingDirectory/function/MTASTS/function.json" -Force
        if ($PolicyMode -ne "enforce"){
            $PSMTASTS_runPs1 = $script:PSMTASTS_runPs1.replace("mode: enforce", "mode: $($PolicyMode.ToLower())")
        }
        $null = $PSMTASTS_runPs1 | Set-Content -Path "$workingDirectory/function/MTASTS/run.ps1" -Force
        ## Create Zip
        if ($PSCmdlet.ShouldProcess("Zip Function App", "Create")) {
            $null = Compress-Archive -Path "$workingDirectory/function/*" -DestinationPath "$workingDirectory/Function.zip" -Force
        }

        # Upload PowerShell code to Azure Function App
        Write-Verbose "Uploading PowerShell code to Azure Function App $($FunctionAppName)..."
        if ($PSCmdlet.ShouldProcess("Function App $FunctionAppName", "Update")) {
            $null = Publish-AzWebApp -ResourceGroupName $ResourceGroupName -Name $FunctionAppName -ArchivePath "$workingDirectory/Function.zip" -Confirm:$false -Force
        }
        
        # Clean up
        Write-Verbose "Cleanup Temp Folder"
        if (Test-Path -Path $workingDirectory) {
            $null = Get-ChildItem -Path $workingDirectory -Recurse | Remove-Item -Recurse -Force -Confirm:$false
        }
    }
}

$script:PSMTASTS_hostJson = @'
{
    "version": "2.0",
    "extensions": {
        "http": {
        "routePrefix": "",
            "customHeaders": {
                "Permissions-Policy": "geolocation=()",
                "X-Frame-Options": "SAMEORIGIN",
                "Content-Security-Policy": "default-src 'self'",
                "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
                "X-Content-Type-Options": "nosniff",
                "Referrer-Policy": "no-referrer"
            }
        }
    },
    "managedDependency": {
        "Enabled": false
    },
    "extensionBundle": {
        "id": "Microsoft.Azure.Functions.ExtensionBundle",
        "version": "[3.*, 4.0.0)"
    }
}
'@


$script:PSMTASTS_profilePs1 = @'
# Azure Functions profile.ps1
#
# This profile.ps1 will get executed every "cold start" of your Function App.
# "cold start" occurs when:
#
# * A Function App starts up for the very first time
# * A Function App starts up after being de-allocated due to inactivity
#
# You can define helper functions, run commands, or specify environment variables
# NOTE: any variables defined that are not environment variables will get reset after the first execution
# Authenticate with Azure PowerShell using MSI.
# Remove this if you are not planning on using MSI or Azure PowerShell.
 
#if ($env:MSI_SECRET -and (Get-Module -ListAvailable Az.Accounts)) {
# Write-Host "Connecting to Azure"
# Connect-AzAccount -Identity
#}
 
# Uncomment the next line to enable legacy AzureRm alias in Azure PowerShell.
# Enable-AzureRmAlias
# You can also define functions or aliases that can be referenced in any of your PowerShell functions.
'@


$script:PSMTASTS_requirementsPsd1 = @'
# This file enables modules to be automatically managed by the Functions service.
# See https://aka.ms/functionsmanageddependency for additional information.
#
@{
 
}
'@


#Root Function Json
$script:Root_functionJson = @'
{
    "bindings": [
        {
            "route": "/",
            "authLevel": "ANONYMOUS",
            "methods": [
                "get"
            ],
            "type": "httpTrigger",
            "direction": "in",
            "name": "Request"
        },
        {
            "type": "http",
            "direction": "out",
            "name": "Response"
        }
    ]
}
'@


#Root Script
$script:Root_runPs1 = @'
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
 
# Write to the Azure Functions log stream.
Write-Host "Trigger: Static website index has been requested."
 
# Create HTML
$staticWebsiteIndex = @"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>MTA-STS</title>
</head>
<body>
    <hl>MTA-STS Static Website Index</hl>
    <p>Looking for the <a href="./.well-known/mta-sts.txt">mta-sts.txt</a>?</p>
</body>
</html>
"@
 
# Return the response
try {
    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
        StatusCode = [System.Net.HttpStatusCode]::OK
        Headers = @{
            "content-type" = "text/html"
        }
        Body = $staticWebsiteIndex
    })
}
catch {
 # Return error, if something went wrong
 Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
        StatusCode = [System.Net.HttpStatusCode]::InternalServerError
        Headers = @{
            "Content-type" = "text/plain"
        }
        Body = $_.Exception.Message
    })
}
'@


#MTA-STS Poliy Function JSON
$script:PSMTASTS_functionJson = @'
{
    "bindings": [
        {
            "route": ".well-known/mta-sts.txt",
            "authLevel": "anonymous",
            "methods": [
                "get"
            ],
            "type": "httpTrigger",
            "direction": "in",
            "name": "Request"
        },
        {
            "type": "http",
            "direction": "out",
            "name": "Response"
        }
    ]
}
'@


#MTA-STS Poliy Script
$script:PSMTASTS_runPs1 = @'
param ($Request, $TriggerMetadata)
 
# Write to the Azure Functions log stream.
Write-Host "Trigger: MTA-STS policy has been requested."
 
# Prepare the response body
## Replace 'enforce' with 'testing' to test the policy without enforcing it
## Or use the "Update-PSMTASTSFunctionAppDeployment" function to update the policy and other function app files to the current version
$mtaStsPolicy = @"
version: STSv1
mode: enforce
mx: *.mail.protection.outlook.com
max_age: 604800
"@
 
# Return the response
try {
    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
        StatusCode = [System.Net.HttpStatusCode]::OK
        Headers = @{
            "Content-type" = "text/plain"
        }
        Body = $mtaStsPolicy
    })
}
catch {
 # Return error, if something went wrong
 Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
        StatusCode = [System.Net.HttpStatusCode]::InternalServerError
        Headers = @{
            "Content-type" = "text/plain"
        }
        Body = $_.Exception.Message
    })
}
'@