Debian Codegraph @

ansible_collections/community/windows/plugins/module_utils/_Tls.psm1

raw
1 # Copyright: (c) 2025, Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 # This module_util is for internal use only. It is not intended to be used by
5 # collections outside of community.windows.
6
7 using namespace System.Net
8 using namespace System.Reflection
9
10 function Enable-TlsProtocol {
11 <#
12 .SYNOPSIS
13 Gets .NET to use the system configured TLS protocols for outbound connections.
14
15 .DESCRIPTION
16 This function ensures that the .NET runtime is configured to use the system
17 configured TLS protocols for outbound connections. This is particularly
18 important for PowerShell hosts running on older versions of .NET Framework
19 where only TLS 1.0 is used.
20
21 This also handles running in a PSRemoting WSMan host where the default is
22 hardcoded to use 1.0, 1.1, and 1.2 only even if 1.3 is available.
23
24 .NOTES
25 https://github.com/ansible-collections/ansible.windows/pull/573#issuecomment-1865477707
26 #>
27 [CmdletBinding()]
28 param ()
29
30 $currentProtocol = [ServicePointManager]::SecurityProtocol
31 if ([SecurityProtocolType].GetMember("Tls13")) {
32 # If the Tls13 member is present we are on .NET Framework 4.8+ so using
33 # the SystemDefault setting will use the OS policies. If it's not set
34 # to SystemDefault already we are running in a PSRemoting WSMan host
35 # and need some reflection to reconfigure the policies to get it to use
36 # the OS policies.
37
38 if ($currentProtocol -ne 'SystemDefault') {
39 # https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls#switchsystemnetdontenablesystemdefaulttlsversions
40 $disableSystemTlsField = [ServicePointManager].GetField(
41 's_disableSystemDefaultTlsVersions',
42 [BindingFlags]'NonPublic, Static')
43 if ($disableSystemTlsField -and $disableSystemTlsField.GetValue($null)) {
44 $disableSystemTlsField.SetValue($null, $false)
45 }
46
47 [ServicePointManager]::SecurityProtocol = [SecurityProtocolType]::SystemDefault
48 }
49 }
50 else {
51 # We are on .NET 4.7 or older, as TLS 1.2 is the max version we can
52 # use here regardless of the OS, manually enable the protocols known to
53 # the runtime.
54 if ([SecurityProtocolType].GetMember("Tls11")) {
55 $currentProtocol = $currentProtocol -bor [SecurityProtocolType]::Tls11
56 }
57 if ([SecurityProtocolType].GetMember("Tls12")) {
58 $currentProtocol = $currentProtocol -bor [SecurityProtocolType]::Tls12
59 }
60 [ServicePointManager]::SecurityProtocol = $currentProtocol
61 }
62
63 }
64
65 Export-ModuleMember -Function Enable-TlsProtocol