TlsConfig.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\TlsConfig.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName TlsConfig.Import.DoDotSource -Fallback $false
if ($TlsConfig_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName TlsConfig.Import.IndividualFiles -Fallback $false
if ($TlsConfig_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'TlsConfig' -Language 'en-US'

function ConvertFrom-RawTlsData {
    <#
    .SYNOPSIS
        Converts raw tls information objects into structured, processed data.
     
    .DESCRIPTION
        Converts raw tls information objects into structured, processed data.
     
    .PARAMETER InputObject
        The TLS configuration object returned from the remote hosts.
     
    .EXAMPLE
        PS C:\> $data | ConvertFrom-RawTlsData
 
        Converts raw tls information objects into structured, processed data.
    #>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        $InputObject
    )

    process {
        foreach ($object in $InputObject) {
            $object.PSObject.TypeNames.Insert(0, 'TLS.Configuration')

            Add-Member -InputObject $object -MemberType ScriptProperty -Name SecureOnly -Value {
                $default = $false

                # Shouldn't disable good stuff
                if ($this.StrongCrypto_35 -eq "Disabled") { return $default }
                if ($this.StrongCrypto_45 -eq "Disabled") { return $default }
                if ($this.StrongCrypto_x86_35 -eq "Disabled") { return $default }
                if ($this.StrongCrypto_x86_45 -eq "Disabled") { return $default }
                if ($this.TLS1_2Client -eq "Disabled") { return $default }
                if ($this.TLS1_2Server -eq "Disabled") { return $default }

                # Insecure Protocols / Ciphers are bad
                if ($this.DES_56_56 -eq "Enabled") { return $default }
                if ($this.RC2_128_128 -eq "Enabled") { return $default }
                if ($this.RC2_40_128 -eq "Enabled") { return $default }
                if ($this.RC2_56_128 -eq "Enabled") { return $default }
                if ($this.RC4_128_128 -eq "Enabled") { return $default }
                if ($this.RC4_40_128 -eq "Enabled") { return $default }
                if ($this.RC4_56_128 -eq "Enabled") { return $default }
                if ($this.RC4_64_128 -eq "Enabled") { return $default }
                if ($this.SSL2Client -eq "Enabled") { return $default }
                if ($this.SSL2Server -eq "Enabled") { return $default }
                if ($this.SSL3Client -eq "Enabled") { return $default }
                if ($this.SSL3Server -eq "Enabled") { return $default }
                if ($this.TLS1_0Client -eq "Enabled") { return $default }
                if ($this.TLS1_0Server -eq "Enabled") { return $default }
                if ($this.TLS1_1Client -eq "Enabled") { return $default }
                if ($this.TLS1_1Server -eq "Enabled") { return $default }

                $true
            }

            Add-Member -InputObject $object -MemberType ScriptProperty -Name SecureEnabled -Value {
                # Shouldn't disable good stuff
                if ($this.StrongCrypto_35 -eq "Disabled") { return $false }
                if ($this.StrongCrypto_45 -eq "Disabled") { return $false }
                if ($this.StrongCrypto_x86_35 -eq "Disabled") { return $false }
                if ($this.StrongCrypto_x86_45 -eq "Disabled") { return $false }
                if ($this.TLS1_2Client -eq "Disabled") { return $false }
                if ($this.TLS1_2Server -eq "Disabled") { return $false }

                $true
            }

            Add-Member -InputObject $object -MemberType ScriptProperty -Name InsecureEnabled -Value {
                $default = $true
                
                # Insecure Protocols / Ciphers are bad
                if ($this.DES_56_56 -eq "Enabled") { return $default }
                if ($this.RC2_128_128 -eq "Enabled") { return $default }
                if ($this.RC2_40_128 -eq "Enabled") { return $default }
                if ($this.RC2_56_128 -eq "Enabled") { return $default }
                if ($this.RC4_128_128 -eq "Enabled") { return $default }
                if ($this.RC4_40_128 -eq "Enabled") { return $default }
                if ($this.RC4_56_128 -eq "Enabled") { return $default }
                if ($this.RC4_64_128 -eq "Enabled") { return $default }
                if ($this.SSL2Client -eq "Enabled") { return $default }
                if ($this.SSL2Server -eq "Enabled") { return $default }
                if ($this.SSL3Client -eq "Enabled") { return $default }
                if ($this.SSL3Server -eq "Enabled") { return $default }
                if ($this.TLS1_0Client -eq "Enabled") { return $default }
                if ($this.TLS1_0Server -eq "Enabled") { return $default }
                if ($this.TLS1_1Client -eq "Enabled") { return $default }
                if ($this.TLS1_1Server -eq "Enabled") { return $default }

                $false
            }

            $object
        }
    }
}

function Get-TlsConfiguration {
    <#
    .SYNOPSIS
        Read the actually deployed TLS configuration from the registry of the target host.
     
    .DESCRIPTION
        Read the actually deployed TLS configuration from the registry of the target host.
        Specifically returns information on:
        - Strong Crypto enabled in .NET
        - TLS 1.0/1.1/1.2 Enabled registry keys
        - SSL 2.0/3.0 Enabled registry keys
        - RC2/RC4/DES Cypher Suites
     
    .PARAMETER ComputerName
        The computers to scan
     
    .EXAMPLE
        PS C:\> Get-TlsConfiguration
 
        Read the actually deployed TLS configuration from the registry of the local computer.
 
    .EXAMPLE
        PS C:\> Get-TlsConfiguration -ComputerName (Get-ADComputer -Filter *)
 
        Read the actually deployed TLS configuration for every single computer in the current domain.
    #>

    [CmdletBinding()]
    Param (
        [Parameter(ValueFromPipeline = $true)]
        [PSFComputer[]]
        $ComputerName = $env:COMPUTERNAME
    )
    
    begin {
        #region Gather Code
        $gatherCode = {
            $registryLocations = @(
                @{ Name = 'SSL2Client'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client' }
                @{ Name = 'SSL2Server'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' }
                @{ Name = 'SSL3Client'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client' }
                @{ Name = 'SSL3Server'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' }
                @{ Name = 'TLS1_0Client'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client' }
                @{ Name = 'TLS1_0Server'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server' }
                @{ Name = 'TLS1_1Client'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' }
                @{ Name = 'TLS1_1Server'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' }
                @{ Name = 'TLS1_2Client'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' }
                @{ Name = 'TLS1_2Server'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' }
                @{ Name = 'RC2_40_128'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC2 40$([char]0x2215)128" }
                @{ Name = 'RC2_56_128'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC2 56$([char]0x2215)128" }
                @{ Name = 'RC2_128_128'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC2 128$([char]0x2215)128" }
                @{ Name = 'RC4_40_128'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC4 40$([char]0x2215)128" }
                @{ Name = 'RC4_56_128'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC4 56$([char]0x2215)128" }
                @{ Name = 'RC4_64_128'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC4 64$([char]0x2215)128" }
                @{ Name = 'RC4_128_128'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC4 128$([char]0x2215)128" }
                @{ Name = 'DES_56_56'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\DES 56$([char]0x2215)56" }
                @{ Name = 'StrongCrypto_35'; Property = 'SchUseStrongCrypto'; Key = 'HKLM:\SOFTWARE\Microsoft\.NETFramework\v2.0.50727'; NullIsDisabled = $true }
                @{ Name = 'StrongCrypto_45'; Property = 'SchUseStrongCrypto'; Key = 'HKLM:\SOFTWARE\Microsoft\.NETFramework\v4.0.30319'; NullIsDisabled = $true }
                @{ Name = 'StrongCrypto_x86_35'; Property = 'SchUseStrongCrypto'; Key = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v2.0.50727'; NullIsDisabled = $true }
                @{ Name = 'StrongCrypto_x86_45'; Property = 'SchUseStrongCrypto'; Key = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319'; NullIsDisabled = $true }
            )
            $enabledHash = @{
                $false = 'Disabled'
                $true = 'Enabled'
                0 = 'Disabled'
                1 = 'Enabled'
            }
            $results = @{
                ComputerName = $env:COMPUTERNAME
            }
            foreach ($location in $registryLocations) {
                if (-not (Test-Path -Path $location.Key)) {
                    $results[$location.Name] = $enabledHash[(-not $location.NullIsDisabled)]
                    continue
                }
                $properties = Get-ItemProperty -Path $location.Key
                if ($properties.PSObject.Properties.Name -notcontains $location.Property) {
                    $results[$location.Name] = $enabledHash[(-not $location.NullIsDisabled)]
                    continue
                }
                $results[$location.Name] = $enabledHash[$properties.$($location.Property)]
            }
            [PSCustomObject]$results
        }
        #endregion Gather Code
    }
    process {
        Invoke-PSFCommand -ComputerName $ComputerName -ScriptBlock $gatherCode | ConvertFrom-RawTlsData
    }
}


function Get-TlsProcessConfiguration {
    <#
    .SYNOPSIS
        Get the current processes' network security settings.
     
    .DESCRIPTION
        Get the current processes' network security settings.
     
    .EXAMPLE
        PS C:\> Get-TlsProcessConfiguration
 
        Get the current processes' network security settings.
    #>

    [CmdletBinding()]
    param ( )

    process {
        $spm = [System.Net.ServicePointManager]
        [PSCustomObject]@{
            CheckCertificateRevocationList      = $spm::CheckCertificateRevocationList
            DefaultConnectionLimit              = $spm::DefaultConnectionLimit
            DefaultNonPersistentConnectionLimit = $spm::DefaultNonPersistentConnectionLimit
            DefaultPersistentConnectionLimit    = $spm::DefaultPersistentConnectionLimit
            DnsRefreshTimeout                   = $spm::DnsRefreshTimeout
            EnableDnsRoundRobin                 = $spm::EnableDnsRoundRobin
            EncryptionPolicy                    = $spm::EncryptionPolicy
            Expect100Continue                   = $spm::Expect100Continue
            MaxServicePointIdleTime             = $spm::MaxServicePointIdleTime
            MaxServicePoints                    = $spm::MaxServicePoints
            ReusePort                           = $spm::ReusePort
            SecurityProtocol                    = $spm::SecurityProtocol
            ServerCertificateValidationCallback = $spm::ServerCertificateValidationCallback
            UseNagleAlgorithm                   = $spm::UseNagleAlgorithm
        }
    }
}

function Set-TlsConfiguration {
    <#
    .SYNOPSIS
        Change the allowed ssl/tls protocols and cipher suites.
     
    .DESCRIPTION
        Change the allowed ssl/tls protocols and cipher suites.
        Note: Most changes require a restart of the target computer.
         
    .PARAMETER ComputerName
        The computer to process.
        Defaults to localhost.
     
    .PARAMETER Enable
        Which protocol/cipher suite to enable.
     
    .PARAMETER Disable
        Which protocol/cipher suite to disable.
     
    .PARAMETER EnableSecure
        Enable all protocols considered secure.
        - Configures .NET to use strong cryptography by default.
        - Enables TLS1.2
     
    .PARAMETER DisableSecure
        Disable all protocols considered secure.
        - Configures .NET to NOT use strong cryptography by default.
        - Disables TLS1.2
        Why the heck would you do this?!
     
    .PARAMETER EnableInsecure
        Enable all protocols and cipher suites considered insecure.
        - Enables SSL2.0 & 3.0
        - Enables TLS1.0 & 1.1
        - Enables RC2 / RC4 / DES
        Only use this if you need to temporarily roll back after all.
     
    .PARAMETER DisableInsecure
        Disable all protocols and cipher suites considered insecure.
        - Disables SSL2.0 & 3.0
        - Disables TLS1.0 & 1.1
        - Disables RC2 / RC4 / DES
        Yehaw!
     
    .EXAMPLE
        PS C:\> Set-TlsConfiguration -EnableSecure -DisableInsecure
 
        Secures the allowed network protocols on the local computer.
 
    .EXAMPLE
        PS C:\> Set-TlsConfiguration -EnableSecure -DisableInsecure -ComputerName (Get-ADComputer -Filter *)
 
        Secures all computers in the entire active directory domain.
    #>

    [CmdletBinding()]
    Param (
        [Parameter(ValueFromPipeline = $true)]
        [PSFComputer[]]
        $ComputerName = $env:COMPUTERNAME,

        [ValidateSet('TLS1_2Client', 'TLS1_2Server', 'StrongCrypto_35', 'StrongCrypto_45', 'StrongCrypto_x86_35', 'StrongCrypto_x86_45', 'DES_56_56', 'RC2_128_128', 'RC2_40_128', 'RC2_56_128', 'RC4_128_128', 'RC4_40_128', 'RC4_56_128', 'RC4_64_128', 'SSL3Client', 'SSL3Server', 'TLS1_0Client', 'TLS1_0Server', 'TLS1_1Client', 'TLS1_1Server', 'SSL2Client', 'SSL2Server')]
        [string[]]
        $Enable,

        [ValidateSet('TLS1_2Client', 'TLS1_2Server', 'StrongCrypto_35', 'StrongCrypto_45', 'StrongCrypto_x86_35', 'StrongCrypto_x86_45', 'DES_56_56', 'RC2_128_128', 'RC2_40_128', 'RC2_56_128', 'RC4_128_128', 'RC4_40_128', 'RC4_56_128', 'RC4_64_128', 'SSL3Client', 'SSL3Server', 'TLS1_0Client', 'TLS1_0Server', 'TLS1_1Client', 'TLS1_1Server', 'SSL2Client', 'SSL2Server')]
        [string[]]
        $Disable,

        [switch]
        $EnableSecure,

        [switch]
        $DisableSecure,

        [switch]
        $EnableInsecure,

        [switch]
        $DisableInsecure
    )
    
    begin {
        #region Remote Scriptblock
        $setCode = {
            param (
                $Parameters
            )

            #region Locations
            $registryLocations = @(
                @{ Name = 'SSL2Client'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client' }
                @{ Name = 'SSL2Server'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server' }
                @{ Name = 'SSL3Client'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client' }
                @{ Name = 'SSL3Server'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server' }
                @{ Name = 'TLS1_0Client'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client' }
                @{ Name = 'TLS1_0Server'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server' }
                @{ Name = 'TLS1_1Client'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client' }
                @{ Name = 'TLS1_1Server'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server' }
                @{ Name = 'TLS1_2Client'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' }
                @{ Name = 'TLS1_2Server'; Property = 'Enabled'; Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' }
                @{ Name = 'RC2_40_128'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC2 40$([char]0x2215)128" }
                @{ Name = 'RC2_56_128'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC2 56$([char]0x2215)128" }
                @{ Name = 'RC2_128_128'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC2 128$([char]0x2215)128" }
                @{ Name = 'RC4_40_128'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC4 40$([char]0x2215)128" }
                @{ Name = 'RC4_56_128'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC4 56$([char]0x2215)128" }
                @{ Name = 'RC4_64_128'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC4 64$([char]0x2215)128" }
                @{ Name = 'RC4_128_128'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC4 128$([char]0x2215)128" }
                @{ Name = 'DES_56_56'; Property = 'Enabled'; Key = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\DES 56$([char]0x2215)56" }
                @{ Name = 'StrongCrypto_35'; Property = 'SchUseStrongCrypto'; Key = 'HKLM:\SOFTWARE\Microsoft\.NETFramework\v2.0.50727'; NullIsDisabled = $true }
                @{ Name = 'StrongCrypto_45'; Property = 'SchUseStrongCrypto'; Key = 'HKLM:\SOFTWARE\Microsoft\.NETFramework\v4.0.30319'; NullIsDisabled = $true }
                @{ Name = 'StrongCrypto_x86_35'; Property = 'SchUseStrongCrypto'; Key = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v2.0.50727'; NullIsDisabled = $true }
                @{ Name = 'StrongCrypto_x86_45'; Property = 'SchUseStrongCrypto'; Key = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319'; NullIsDisabled = $true }
            )
            #endregion Locations

            #region Enable Protocols
            $toEnable = @()
            foreach ($protocol in $Parameters.Enable) {
                $toEnable += $protocol
            }
            if ($Parameters.EnableSecure) {
                $toEnable += $Parameters.SecureOptions
            }
            if ($Parameters.EnableInsecure) {
                $toEnable += $Parameters.InsecureOptions
            }

            foreach ($protocol in $toEnable) {
                $location = $registryLocations | Where-Object { $_.Name -eq $protocol }

                if (-not (Test-Path -Path $location.Key)) {
                    $null = New-Item -Path $location.Key -Force
                }

                Set-ItemProperty -Path $location.Key -Name $location.Property -Value 1
            }
            #endregion Enable Protocols

            #region Disable Protocols
            $toDisable = @()
            foreach ($protocol in $Parameters.Disable) {
                $toDisable += $protocol
            }
            if ($Parameters.DisableSecure) {
                $toDisable += $Parameters.SecureOptions
            }
            if ($Parameters.DisableInsecure) {
                $toDisable += $Parameters.InsecureOptions
            }

            foreach ($protocol in $toDisable) {
                $location = $registryLocations | Where-Object { $_.Name -eq $protocol }

                if (-not (Test-Path -Path $location.Key)) {
                    $null = New-Item -Path $location.Key -Force
                }

                Set-ItemProperty -Path $location.Key -Name $location.Property -Value 0
            }
            #endregion Disable Protocols
        }
        #region Remote Scriptblock
        
        $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Enable, Disable, EnableSecure, DisableSecure, EnableInsecure, DisableInsecure
        $parameters += @{
            SecureOptions   = 'TLS1_2Client', 'TLS1_2Server', 'StrongCrypto_35', 'StrongCrypto_45', 'StrongCrypto_x86_35', 'StrongCrypto_x86_45'
            InsecureOptions = 'DES_56_56', 'RC2_128_128', 'RC2_40_128', 'RC2_56_128', 'RC4_128_128', 'RC4_40_128', 'RC4_56_128', 'RC4_64_128', 'SSL3Client', 'SSL3Server', 'TLS1_0Client', 'TLS1_0Server', 'TLS1_1Client', 'TLS1_1Server', 'SSL2Client', 'SSL2Server'
        }
    }
    process {
        Invoke-PSFCommand -ComputerName $ComputerName -ScriptBlock $setCode -ArgumentList $parameters
    }
}


function Set-TlsProcessConfiguration {
    <#
    .SYNOPSIS
        Configure local process network tls settings.
     
    .DESCRIPTION
        Configure local process network tls settings.
        This specifically allows you to define allowed TLS protocols, override certificate validation, port reuse and all the other myriad of settings supported by .NET.
     
    .PARAMETER CheckCertificateRevocationList
        Sets a Boolean value that indicates whether the certificate is checked against the certificate authority revocation list.
 
    .PARAMETER DefaultConnectionLimit
        Sets the maximum number of concurrent connections allowed by a ServicePoint object.
 
    .PARAMETER DnsRefreshTimeout
        Sets a value that indicates how long a Domain Name Service (DNS) resolution is considered valid.
 
    .PARAMETER EnableDnsRoundRobin
        Sets a value that indicates whether a Domain Name Service (DNS) resolution rotates among the applicable Internet Protocol (IP) addresses.
 
    .PARAMETER Expect100Continue
        Sets a Boolean value that determines whether 100-Continue behavior is used.
 
    .PARAMETER MaxServicePointIdleTime
        Sets the maximum idle time of a ServicePoint object.
 
    .PARAMETER MaxServicePoints
        Sets the maximum number of ServicePoint objects to maintain at any time.
 
    .PARAMETER ReusePort
        Setting this property value to true causes all outbound TCP connections from HttpWebRequest to use the native socket option SO_REUSE_UNICASTPORT on the socket. This causes the underlying outgoing ports to be shared. This is useful for scenarios where a large number of outgoing connections are made in a short time, and the app risks running out of ports.
 
    .PARAMETER AddSecurityProtocol
        Adds a security protocol used by the ServicePoint objects managed by the ServicePointManager object.
 
    .PARAMETER RemoveSecurityProtocol
        Removes a security protocol used by the ServicePoint objects managed by the ServicePointManager object.
 
    .PARAMETER ServerCertificateValidationCallback
        Set the validation logic used to validate certificates in https connections.
        Set it to { $true } to disable validation.
 
    .PARAMETER UseNagleAlgorithm
        Determines whether the Nagle algorithm is used by the service points managed by this ServicePointManager object.
 
    .EXAMPLE
        PS C:\> Set-TlsProcessConfiguration -AddSecurityProtocol Tls12
 
        Addes TLS1.2 to the list of protocols used.
    #>

    [CmdletBinding()]
    param (
        [System.Boolean]
        $CheckCertificateRevocationList,

        [System.Int32]
        $DefaultConnectionLimit,

        [System.Int32]
        $DnsRefreshTimeout,

        [System.Boolean]
        $EnableDnsRoundRobin,

        [System.Boolean]
        $Expect100Continue,

        [System.Int32]
        $MaxServicePointIdleTime,

        [System.Int32]
        $MaxServicePoints,

        [System.Boolean]
        $ReusePort,

        [System.Net.SecurityProtocolType]
        $AddSecurityProtocol,

        [System.Net.SecurityProtocolType]
        $RemoveSecurityProtocol,

        [scriptblock]
        $ServerCertificateValidationCallback,

        [System.Boolean]
        $UseNagleAlgorithm
    )

    begin {
        $commonParam = 'Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable','Confirm','WhatIf'
    }
    process {
        foreach ($parameter in $PSBoundParameters.GetEnumerator()) {
            if ($parameter.Key -in $commonParam) { continue }
            switch ($parameter.Key) {
                'AddSecurityProtocol' { [System.Net.ServicePointManager]::SecurityProtocol += $parameter.Value }
                'RemoveSecurityProtocol' { [System.Net.ServicePointManager]::SecurityProtocol -= $parameter.Value }
                default { [System.Net.ServicePointManager]::$($parameter.Key) = $parameter.Value }
            }
        }
    }
}

function Test-TlsProtocol {
    <#
        .SYNOPSIS
            A quick helper function to test supported TLS protocols
         
        .DESCRIPTION
            A quick helper function to test supported TLS protocols
         
        .PARAMETER ComputerName
            The hosts to check.
         
        .PARAMETER Port
            The Port to test against.
            Defaults to 443
         
        .EXAMPLE
            PS C:\> Test-TlsProtocol -ComputerName 'contoso.com'
         
            Tests contoso.com's supported TLS protocols (at least as far as the service listening on Port 443 is concerned).
    #>

        [CmdletBinding()]
        param (
            [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
            [ValidateNotNullOrEmpty()]
            [string[]]
            $ComputerName,
            
            [UInt16]
            $Port = 443
        )
        begin {
            $tlsProtocols = [enum]::GetNames([System.Security.Authentication.SslProtocols]) | Where-Object { $_ -ne 'None' }
            $certificateCallback = [System.Net.Security.RemoteCertificateValidationCallback]{ $true }
        }
        process {
            :main foreach ($computer in $ComputerName) {
                $results = @{
                    Host          = $computer
                    Port          = $Port
                    KeyExhange    = $null
                    HashAlgorithm = $null
                    Error          = @{ }
                }
                
                foreach ($tlsProtocol in $tlsProtocols) {
                    $tcpClient = [Net.Sockets.TcpClient]::new()
                    try { $tcpClient.Connect($computer, $Port) }
                    catch {
                        $tcpClient.Dispose()
                        Write-PSFMessage -Level Error -String 'Test-TlsProtocol.Tcp.Failed' -StringValues $computer, $port, $_.Exception.GetBaseException().Message -ErrorRecord $_ -OverrideExceptionMessage -EnableException $true
                        if ($_.Exception.InnerException.SocketErrorCode -eq 'HostNotFound') { continue main }
                        continue
                    }
                    
                    $sslStream = [Net.Security.SslStream]::new(
                        $tcpClient.GetStream(),
                        $true,
                        $certificateCallback
                    )
                    
                    try {
                        $sslStream.AuthenticateAsClient($results.Host, $null, $tlsProtocol, $false)
                        $results.KeyExhange = $sslStream.KeyExchangeAlgorithm
                        $results.HashAlgorithm = $sslStream.HashAlgorithm
                        $results.$tlsProtocol = $true
                    }
                    catch {
                        $results.$tlsProtocol = $false
                        $results.Error.$tlsProtocol = $_
                    }
                    finally {
                        $tcpClient.Dispose()
                        $sslStream.Dispose()
                    }
                }
                
                [pscustomobject]$results
            }
        }
    }

<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'TlsConfig' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'TlsConfig' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'TlsConfig' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

Set-PSFConfig -Module TlsConfig -Name 'Disable.Auto1_2' -Value $false -Initialize -Validation bool -Description 'Whether the module should stop adding 1.2 to the list of supported protocols on import. Only applied at import time, so set/persist the setting for it to stick.'

<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'TlsConfig.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppScriptblock -Name "TlsConfig.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name TlsConfig.alcohol
#>


if (-not (Get-PSFConfigValue -FullName 'TlsConfig.Disable.Auto1_2')) {
    Set-TlsProcessConfiguration -AddSecurityProtocol TLS12
}

New-PSFLicense -Product 'TlsConfig' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2021-04-29") -Text @"
Copyright (c) 2021 Friedrich Weinmann
 
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.
"@

#endregion Load compiled code