Debian Codegraph @

src/spnego/tls.py

raw
1 # Copyright: (c) 2021, Jordan Borean (@jborean93) <[email protected]>
2 # MIT License (see LICENSE or https://opensource.org/licenses/MIT)
3
4 import dataclasses
5 import datetime
6 import platform
7 import ssl
8 import typing
9
10 from cryptography import x509
11 from cryptography.hazmat.backends import default_backend
12 from cryptography.hazmat.primitives import hashes, serialization
13 from cryptography.hazmat.primitives.asymmetric import rsa
14
15
16 @dataclasses.dataclass
17 class CredSSPTLSContext:
18 """A TLS context generated for CredSSP.
19
20 This is the SSLContext object used by both an initiator and acceptor of
21 CredSSP authentication. It allows the caller to finely control the SSL/TLS
22 options used during the CredSSP authentication phase, e.g. selecting
23 min/max protocol versions, specific cipher suites, etc.
24
25 The public_key attribute is used for acceptor CredSSP contexts as the
26 DER encoded public key loaded in the SSLContext. Here is an example of
27 generating and loading a X509 certificate for an acceptor context:
28
29 ctx = spnego.tls.default_tls_context()
30 cert_pem, key_Pem, pub_key = spnego.tls.generate_tls_certificate()
31
32 # Cannot use tempfile.NamedTemporaryFile due to sharing violations on
33 # Windows. Use a tempdir as a workaround.
34 temp_dir = tempfile.mkdtemp()
35 try:
36 cert_path = os.path.join(tmpe_dir, 'ca.pem')
37 with open(cert_path, mode'wb') as fd:
38 fd.write(cert_pem)
39 fd.write(key_pem)
40
41 ctx.context.load_cert_chain(cert_path)
42 ctx.public_key = pub_key
43
44 finally:
45 shutil.rmtree(temp_dir)
46
47 This context is then passed in through the `credssp_tls_context` kwarg of
48 :meth:`spnego.client` or :meth:`spnego.server`.
49
50 Attributes:
51 context (ssl.SSLContext): The TLS context generated for CredSSP.
52 public_key (Optional[bytes]): When generating the TLS context for an
53 acceptor this is the public key bytes for the generated cert in the
54 TLS context.
55 """
56
57 context: ssl.SSLContext
58 public_key: typing.Optional[bytes] = None
59
60
61 def default_tls_context(
62 usage: str = "initiate",
63 ) -> CredSSPTLSContext:
64 """CredSSP TLSContext with sane defaults.
65
66 Creates the TLS context used to generate the SSL object for CredSSP
67 authentication. By default the TLS context will set the minimum protocol to
68 TLSv1.2. Certificate verification is also disabled for both the initiator
69 and acceptor as per the `MS-CSSP Events and Sequencing Rules`_ in step 1.
70 This can be used as a base context where the caller applies further changes
71 based on their requirements such as cert validation and so forth.
72
73 This context is then passed in through the `credssp_tls_context` kwarg of
74 :meth:`spnego.client` or :meth:`spnego.server`.
75
76 Args:
77 usage: Either `initiate` for a client context or `accept` for a server context.
78
79 Returns:
80 TLSContext: The TLS context that can be used with CredSSP auth.
81
82 .. _MS-CSSP Events and Sequencing Rules:
83 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cssp/385a7489-d46b-464c-b224-f7340e308a5c
84 """
85 if usage == "initiate":
86 # TLS_CLIENT enables CA/CN checking but CredSSP does not use this by default in the docs. The caller can
87 # re-enable this if needed.
88 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
89 ctx.check_hostname = False
90 ctx.verify_mode = ssl.CERT_NONE
91 else:
92 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
93
94 # Required to interop with SChannel which does not support compression, TLS padding, and empty fragments
95 # SSL_OP_NO_COMPRESSION | SSL_OP_TLS_BLOCK_PADDING_BUG | SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
96 ctx.options |= ssl.OP_NO_COMPRESSION | 0x00000200 | 0x00000800
97
98 # The minimum_version field requires OpenSSL 1.1.0g or newer, fallback to the deprecated method of setting the
99 # OP_NO_* options.
100 # FUTURE: Remove once Python 3.10 is minimum which requires 1.1.1 or newer
101 tls_version = getattr(ssl, "TLSVersion", None)
102 if hasattr(ctx, "minimum_version") and tls_version:
103 setattr(ctx, "minimum_version", tls_version.TLSv1_2)
104
105 else:
106 ctx.options |= (
107 ssl.Options.OP_NO_SSLv2 | ssl.Options.OP_NO_SSLv3 | ssl.Options.OP_NO_TLSv1 | ssl.Options.OP_NO_TLSv1_1
108 )
109
110 return CredSSPTLSContext(context=ctx)
111
112
113 def generate_tls_certificate() -> typing.Tuple[bytes, bytes, bytes]:
114 """Generates X509 cert and key for CredSSP acceptor.
115
116 Generates a TLS X509 certificate and key that can be used by a CredSSP
117 acceptor for authentication. This certificate is modelled after the one
118 that the WSMan CredSSP service uses on Windows.
119
120 Returns:
121 Tuple[bytes, bytes, bytes]: The X509 PEM encoded certificate,
122 PEM encoded key, and DER encoded public key.
123 """
124 key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())
125
126 # socket.getfqdn() can block for a few seconds if DNS is not set up properly.
127 name = x509.Name([x509.NameAttribute(x509.NameOID.COMMON_NAME, "CREDSSP-%s" % platform.node())])
128
129 now = datetime.datetime.utcnow()
130 cert = (
131 x509.CertificateBuilder()
132 .subject_name(name)
133 .issuer_name(name)
134 .public_key(key.public_key())
135 .serial_number(x509.random_serial_number())
136 .not_valid_before(now)
137 .not_valid_after(now + datetime.timedelta(days=365))
138 .sign(key, hashes.SHA256(), default_backend())
139 )
140 cert_pem = cert.public_bytes(encoding=serialization.Encoding.PEM)
141 key_pem = key.private_bytes(
142 encoding=serialization.Encoding.PEM,
143 format=serialization.PrivateFormat.TraditionalOpenSSL,
144 encryption_algorithm=serialization.NoEncryption(),
145 )
146 public_key = cert.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.PKCS1)
147
148 return cert_pem, key_pem, public_key
149
150
151 def get_certificate_public_key(
152 data: bytes,
153 ) -> bytes:
154 """Public key bytes of an X.509 Certificate.
155
156 Gets the public key bytes used by CredSSP of the provided X.509
157 certificate. Use this for the `public_key` attribute of
158 class:`CredSSPTLSContext` for an acceptor context when providing your own
159 certificate.
160
161 Args:
162 data: The DER encoded bytes of the X.509 certificate.
163
164 Returns:
165 bytes: The public key bytes of the certificate.
166 """
167 cert = x509.load_der_x509_certificate(data, default_backend())
168 public_key = cert.public_key()
169
170 return public_key.public_bytes(serialization.Encoding.DER, serialization.PublicFormat.PKCS1)