| 1 |
# Copyright: (c) 2020, Jordan Borean (@jborean93) <[email protected]> |
| 2 |
# MIT License (see LICENSE or https://opensource.org/licenses/MIT) |
| 3 |
|
| 4 |
import base64 |
| 5 |
import hashlib |
| 6 |
import logging |
| 7 |
import os |
| 8 |
import re |
| 9 |
import shutil |
| 10 |
import ssl |
| 11 |
import struct |
| 12 |
import tempfile |
| 13 |
import typing |
| 14 |
|
| 15 |
import spnego |
| 16 |
from spnego._context import ( |
| 17 |
IOV, |
| 18 |
ContextProxy, |
| 19 |
ContextReq, |
| 20 |
IOVUnwrapResult, |
| 21 |
IOVWrapResult, |
| 22 |
SecPkgContextSizes, |
| 23 |
UnwrapResult, |
| 24 |
WinRMWrapResult, |
| 25 |
WrapResult, |
| 26 |
split_username, |
| 27 |
) |
| 28 |
from spnego._credential import Credential, Password, unify_credentials |
| 29 |
from spnego._credssp_structures import ( |
| 30 |
NegoData, |
| 31 |
TSCredentials, |
| 32 |
TSPasswordCreds, |
| 33 |
TSRequest, |
| 34 |
) |
| 35 |
from spnego._text import to_text |
| 36 |
from spnego.channel_bindings import GssChannelBindings |
| 37 |
from spnego.exceptions import ( |
| 38 |
BadBindingsError, |
| 39 |
ErrorCode, |
| 40 |
FeatureMissingError, |
| 41 |
InvalidTokenError, |
| 42 |
NativeError, |
| 43 |
NegotiateOptions, |
| 44 |
NoContextError, |
| 45 |
OperationNotAvailableError, |
| 46 |
SpnegoError, |
| 47 |
) |
| 48 |
from spnego.tls import ( |
| 49 |
CredSSPTLSContext, |
| 50 |
default_tls_context, |
| 51 |
generate_tls_certificate, |
| 52 |
get_certificate_public_key, |
| 53 |
) |
| 54 |
|
| 55 |
log = logging.getLogger(__name__) |
| 56 |
|
| 57 |
# The protocol version understood by the client and server. |
| 58 |
_CREDSSP_VERSION = 6 |
| 59 |
_X509_CERTIFICATE: typing.Optional[typing.Tuple[bytes, bytes, bytes]] = None |
| 60 |
|
| 61 |
F = typing.TypeVar("F", bound=typing.Callable[..., typing.Any]) |
| 62 |
|
| 63 |
|
| 64 |
def _create_tls_context( |
| 65 |
usage: str, |
| 66 |
) -> CredSSPTLSContext: |
| 67 |
log.debug("Creating TLS context") |
| 68 |
ctx = default_tls_context(usage=usage) |
| 69 |
|
| 70 |
if usage == "accept": |
| 71 |
# Cache the result for future operations |
| 72 |
global _X509_CERTIFICATE |
| 73 |
if not _X509_CERTIFICATE: |
| 74 |
_X509_CERTIFICATE = generate_tls_certificate() |
| 75 |
|
| 76 |
cert_pem, key_pem, public_key = _X509_CERTIFICATE |
| 77 |
|
| 78 |
# Can't use tempfile.NamedTemporaryFile() as load_cert_chain() opens the file on another handle which fails |
| 79 |
# on Windows as the tempfile requires DELETE share access for that to work. |
| 80 |
temp_dir = tempfile.mkdtemp() |
| 81 |
try: |
| 82 |
cert_path = os.path.join(temp_dir, "ca.pem") |
| 83 |
with open(cert_path, mode="wb") as fd: |
| 84 |
fd.write(cert_pem) |
| 85 |
fd.write(key_pem) |
| 86 |
|
| 87 |
ctx.context.load_cert_chain(cert_path) |
| 88 |
ctx.public_key = public_key |
| 89 |
|
| 90 |
finally: |
| 91 |
shutil.rmtree(temp_dir) |
| 92 |
|
| 93 |
return ctx |
| 94 |
|
| 95 |
|
| 96 |
def _get_pub_key_auth( |
| 97 |
pub_key: bytes, |
| 98 |
usage: str, |
| 99 |
nonce: typing.Optional[bytes] = None, |
| 100 |
) -> bytes: |
| 101 |
"""Computes the public key authentication value. |
| 102 |
|
| 103 |
Params: |
| 104 |
pub_key: The public key to transform. |
| 105 |
usage: Either `initiate` or `accept` to denote if the key is for the |
| 106 |
client to server or vice versa. |
| 107 |
nonce: A 32 byte nonce used for CredSSP version 5 or newer. |
| 108 |
|
| 109 |
Returns: |
| 110 |
bytes: The public key authentication value. |
| 111 |
""" |
| 112 |
if nonce: |
| 113 |
direction = b"Client-To-Server" if usage == "initiate" else b"Server-To-Client" |
| 114 |
hash_input = (b"CredSSP %s Binding Hash\x00" % direction) + nonce + pub_key |
| 115 |
key_auth = hashlib.sha256(hash_input).digest() |
| 116 |
|
| 117 |
elif usage == "accept": |
| 118 |
first_byte = struct.unpack("B", pub_key[0:1])[0] |
| 119 |
key_auth = struct.pack("B", first_byte + 1) + pub_key[1:] |
| 120 |
|
| 121 |
else: |
| 122 |
key_auth = pub_key |
| 123 |
|
| 124 |
return key_auth |
| 125 |
|
| 126 |
|
| 127 |
def _tls_trailer_length( |
| 128 |
data_length: int, |
| 129 |
protocol: str, |
| 130 |
cipher_suite: str, |
| 131 |
) -> int: |
| 132 |
"""Gets the length of the TLS trailer. |
| 133 |
|
| 134 |
WinRM wrapping needs to split the trailer/header with the data but the |
| 135 |
length of the trailer is dependent on the cipher suite that was negotiated. |
| 136 |
On Windows you can get this length by calling `QueryContextAttributes`_ |
| 137 |
with the `SecPkgContext_StreamSizes`_ structure. Unfortunately we need to |
| 138 |
work on other platforms so we calculate it manually. |
| 139 |
|
| 140 |
Params: |
| 141 |
data_length: The length of the TLS data used to calculate the padding |
| 142 |
size. |
| 143 |
protocol: The TLS protocol negotiated between the client and server. |
| 144 |
cipher_suite: The TLS cipher suite negotiated between the client and |
| 145 |
server. |
| 146 |
|
| 147 |
Returns: |
| 148 |
int: The length of the trailer. |
| 149 |
|
| 150 |
.. _QueryContextAttributes: |
| 151 |
https://docs.microsoft.com/en-us/windows/win32/api/sspi/nf-sspi-querycontextattributesw |
| 152 |
|
| 153 |
.. _SecPkgContext_StreamSizes: |
| 154 |
https://docs.microsoft.com/en-us/windows/win32/api/sspi/ns-sspi-secpkgcontext_streamsizes |
| 155 |
""" |
| 156 |
if protocol == "TLSv1.3": |
| 157 |
# The 2 cipher suites that MS supports for TLS 1.3 (TLS_AES_*_GCM_SHA*) have a fixed length of 17. This may |
| 158 |
# change in the future but it works for now. |
| 159 |
trailer_length = 17 |
| 160 |
|
| 161 |
elif re.match(r"^.*[-_]GCM[-_][\w\d]*$", cipher_suite): |
| 162 |
# GCM has a fixed length of 16 bytes |
| 163 |
trailer_length = 16 |
| 164 |
|
| 165 |
else: |
| 166 |
# For other cipher suites, trailer size == len(hmac) + len(padding) the padding is the length required by the |
| 167 |
# chosen block cipher. |
| 168 |
hash_algorithm = cipher_suite.split("-")[-1] |
| 169 |
|
| 170 |
# While there are other algorithms, SChannel doesn't support them as of yet so we just keep to this list. |
| 171 |
hash_length = {"MD5": 16, "SHA": 20, "SHA256": 32, "SHA384": 48}.get(hash_algorithm, 0) |
| 172 |
|
| 173 |
pre_pad_length = data_length + hash_length |
| 174 |
if "RC4" in cipher_suite: |
| 175 |
# RC4 is a stream cipher so no padding would be added. |
| 176 |
padding_length = 0 |
| 177 |
|
| 178 |
elif "DES" in cipher_suite or "3DES" in cipher_suite: |
| 179 |
# 3DES is a 64 bit block cipher. |
| 180 |
padding_length = 8 - (pre_pad_length % 8) |
| 181 |
|
| 182 |
else: |
| 183 |
# AES is a 128 bit block cipher. |
| 184 |
padding_length = 16 - (pre_pad_length % 16) |
| 185 |
|
| 186 |
trailer_length = (pre_pad_length + padding_length) - data_length |
| 187 |
|
| 188 |
return trailer_length |
| 189 |
|
| 190 |
|
| 191 |
def _wrap_ssl_error(context: str) -> typing.Callable[[F], F]: |
| 192 |
def decorator(func: F) -> F: |
| 193 |
def wrapped(*args: typing.Any, **kwargs: typing.Any) -> F: |
| 194 |
try: |
| 195 |
return func(*args, **kwargs) |
| 196 |
|
| 197 |
except ssl.SSLError as e: |
| 198 |
raise SpnegoError(error_code=ErrorCode.failure, context_msg="%s: %s" % (context, e)) from e |
| 199 |
|
| 200 |
return typing.cast(F, wrapped) |
| 201 |
|
| 202 |
return decorator |
| 203 |
|
| 204 |
|
| 205 |
class CredSSPProxy(ContextProxy): |
| 206 |
"""CredSSP proxy class CredSSP authentication. |
| 207 |
|
| 208 |
This proxy class for CredSSP can be used to exchange CredSSP tokens. |
| 209 |
It uses the NegotiateProxy provider for the underlying authentication but |
| 210 |
exchanges the tokens in the exchange required by CredSSP. The main |
| 211 |
advantage of CredSSP is that it allows you to delegate the user's |
| 212 |
credentials to the server. |
| 213 |
|
| 214 |
The acceptor logic is mostly done as a proof of concept and for use with |
| 215 |
testing. Use at your own risk. |
| 216 |
|
| 217 |
Currently this context proxy supports the following CredSSP protocols: |
| 218 |
|
| 219 |
2: |
| 220 |
Earliest protocol that ships with Windows XP, Vista, 7, 8, Server |
| 221 |
2008, 2008 R2, and 2012. This version is susceptible to |
| 222 |
CVE-2018-0886 |
| 223 |
3: |
| 224 |
Introduced with Windows 8.1 and Server 2012 R2. Adds the errorCode |
| 225 |
field for better error details on a failure. This version is |
| 226 |
susceptible to CVE-2018-0886. |
| 227 |
4: |
| 228 |
Largely the same as 3, introduced in an older Win 10 build. |
| 229 |
5: |
| 230 |
Same as version 2 but with the mitigations for CVE-2018-0886 |
| 231 |
applied. |
| 232 |
6: |
| 233 |
Same as version 3 and 4 but with the mitigations for CVE-2018-0886 |
| 234 |
applied. |
| 235 |
|
| 236 |
If the context proxy is talking to a peer with a higher protocol number it |
| 237 |
is treated the same as what the client supports. |
| 238 |
|
| 239 |
Optional kwargs supports by CredSSPProxy: |
| 240 |
|
| 241 |
credssp_negotiate_context: Use this contest for the underlying |
| 242 |
authentication negotiation. This allows the caller to restrict the |
| 243 |
auth to Kerberos or set any other setting specific to their |
| 244 |
environment: |
| 245 |
|
| 246 |
credssp_tls_context: Custom :class:`CredSSPTLSContext` to use for the |
| 247 |
CredSSP exchange. See `spnego.tls` for helper methods to generate |
| 248 |
a custom TLS context. |
| 249 |
|
| 250 |
credssp_min_protocol: The minimum CredSSP authentication protocol the |
| 251 |
context will allow. This can control whether the server rejects |
| 252 |
peers running on a lower protocol version than what is set to |
| 253 |
enforce a better security baseline. The default is 2 which works |
| 254 |
against all CredSSP peers. To ensure the mitigations for |
| 255 |
CVE-2018-0886 is in place set this value to 5 or higher. |
| 256 |
""" |
| 257 |
|
| 258 |
def __init__( |
| 259 |
self, |
| 260 |
username: typing.Optional[typing.Union[str, Credential, typing.List[Credential]]] = None, |
| 261 |
password: typing.Optional[str] = None, |
| 262 |
hostname: typing.Optional[str] = None, |
| 263 |
service: typing.Optional[str] = None, |
| 264 |
channel_bindings: typing.Optional[GssChannelBindings] = None, |
| 265 |
context_req: ContextReq = ContextReq.default, |
| 266 |
usage: str = "initiate", |
| 267 |
protocol: str = "credssp", |
| 268 |
options: NegotiateOptions = NegotiateOptions.none, |
| 269 |
**kwargs: typing.Any, |
| 270 |
) -> None: |
| 271 |
credentials = unify_credentials( |
| 272 |
username, password, required_protocol="credssp" if usage == "initiate" else None |
| 273 |
) |
| 274 |
super(CredSSPProxy, self).__init__( |
| 275 |
credentials, hostname, service, channel_bindings, context_req, usage, protocol, options |
| 276 |
) |
| 277 |
|
| 278 |
if options & NegotiateOptions.session_key: |
| 279 |
raise FeatureMissingError(NegotiateOptions.session_key) |
| 280 |
|
| 281 |
self._credentials = credentials |
| 282 |
self._options = options & ~NegotiateOptions.wrapping_winrm # WinRM wrapping won't apply for auth context. |
| 283 |
|
| 284 |
self._auth_context: typing.Optional[ContextProxy] = kwargs.get("credssp_negotiate_context", None) |
| 285 |
self._ts_credential: typing.Optional[TSCredentials] = None |
| 286 |
self._complete = False |
| 287 |
self._step_gen: typing.Optional[typing.Generator[bytes, typing.Optional[bytes], None]] = None |
| 288 |
self._auth_stage = "TLS Handshake" |
| 289 |
self._min_version: int = kwargs.get("credssp_min_protocol", 2) |
| 290 |
self._selected_version: typing.Optional[int] = None |
| 291 |
|
| 292 |
self._tls_context: CredSSPTLSContext |
| 293 |
if "credssp_tls_context" in kwargs: |
| 294 |
self._tls_context = kwargs["credssp_tls_context"] |
| 295 |
|
| 296 |
if usage == "accept" and not self._tls_context.public_key: |
| 297 |
raise OperationNotAvailableError(context_msg="Provided tls context does not have a public key set") |
| 298 |
else: |
| 299 |
self._tls_context = _create_tls_context(usage) |
| 300 |
|
| 301 |
self._in_buff = ssl.MemoryBIO() |
| 302 |
self._out_buff = ssl.MemoryBIO() |
| 303 |
self._tls_object = self._tls_context.context.wrap_bio( |
| 304 |
self._in_buff, self._out_buff, server_side=(usage == "accept") |
| 305 |
) |
| 306 |
|
| 307 |
if usage == "initiate": |
| 308 |
for cred in credentials: |
| 309 |
# There will always be a Password cred as per the check in unify_credentials |
| 310 |
if isinstance(cred, Password): |
| 311 |
domain, username = split_username(cred.username) |
| 312 |
password_cred = TSPasswordCreds(domain or "", username or "", cred.password) |
| 313 |
self._ts_credential = TSCredentials(credentials=password_cred) |
| 314 |
break |
| 315 |
|
| 316 |
@classmethod |
| 317 |
def available_protocols(cls, options: typing.Optional[NegotiateOptions] = None) -> typing.List[str]: |
| 318 |
return ["credssp"] |
| 319 |
|
| 320 |
@classmethod |
| 321 |
def iov_available(cls) -> bool: |
| 322 |
return False |
| 323 |
|
| 324 |
@property |
| 325 |
def client_principal(self) -> typing.Optional[str]: |
| 326 |
return self._auth_context.client_principal if self._auth_context else None |
| 327 |
|
| 328 |
@property |
| 329 |
def complete(self) -> bool: |
| 330 |
return self._complete |
| 331 |
|
| 332 |
@property |
| 333 |
def negotiated_protocol(self) -> typing.Optional[str]: |
| 334 |
return self._auth_context.negotiated_protocol if self._auth_context else None |
| 335 |
|
| 336 |
@property |
| 337 |
def session_key(self) -> bytes: |
| 338 |
raise OperationNotAvailableError(context_msg="CredSSP does not have a session key to share") |
| 339 |
|
| 340 |
def new_context(self) -> "CredSSPProxy": |
| 341 |
return CredSSPProxy( |
| 342 |
username=self._credentials, |
| 343 |
hostname=self._hostname, |
| 344 |
service=self._service, |
| 345 |
channel_bindings=self.channel_bindings, |
| 346 |
context_req=self.context_req, |
| 347 |
usage=self.usage, |
| 348 |
protocol=self.protocol, |
| 349 |
options=self.options, |
| 350 |
credssp_negotiate_context=self._auth_context.new_context() if self._auth_context else None, |
| 351 |
) |
| 352 |
|
| 353 |
def step( |
| 354 |
self, |
| 355 |
in_token: typing.Optional[bytes] = None, |
| 356 |
*, |
| 357 |
channel_bindings: typing.Optional[GssChannelBindings] = None, |
| 358 |
) -> typing.Optional[bytes]: |
| 359 |
log.debug("CredSSP step input: %s", to_text(base64.b64encode(in_token or b""))) |
| 360 |
|
| 361 |
if self._step_gen is None: |
| 362 |
self._step_gen = getattr(self, "_step_%s" % self.usage)(in_token) |
| 363 |
in_token = None |
| 364 |
|
| 365 |
out_token = None |
| 366 |
try: |
| 367 |
out_token = self._step_gen.send(in_token) |
| 368 |
except StopIteration: |
| 369 |
pass |
| 370 |
|
| 371 |
log.debug("CredSSP step output: %s", to_text(base64.b64encode(out_token or b""))) |
| 372 |
return out_token |
| 373 |
|
| 374 |
def _step_initiate( |
| 375 |
self, |
| 376 |
in_token: typing.Optional[bytes], |
| 377 |
) -> typing.Generator[bytes, bytes, None]: |
| 378 |
"""The initiator authentication steps of CredSSP.""" |
| 379 |
yield from self._step_tls(in_token) |
| 380 |
|
| 381 |
server_certificate = typing.cast(bytes, self._tls_object.getpeercert(True)) |
| 382 |
public_key = get_certificate_public_key(server_certificate) |
| 383 |
|
| 384 |
log.debug("Starting CredSSP authentication phase") |
| 385 |
if not self._auth_context: |
| 386 |
auth_kwargs: typing.Dict[str, typing.Any] = {} |
| 387 |
if self._hostname: |
| 388 |
auth_kwargs["hostname"] = self._hostname |
| 389 |
if self._service: |
| 390 |
auth_kwargs["service"] = self._service |
| 391 |
self._auth_context = spnego.client( |
| 392 |
self._credentials, protocol="negotiate", options=self._options, **auth_kwargs |
| 393 |
) |
| 394 |
|
| 395 |
round = 0 |
| 396 |
out_token = self._auth_context.step() |
| 397 |
while True: |
| 398 |
round += 1 |
| 399 |
auth_request = TSRequest(_CREDSSP_VERSION, nego_tokens=NegoData(out_token or b"")) |
| 400 |
|
| 401 |
auth_response = yield from self._yield_ts_request(auth_request, "Authentication %d" % round) |
| 402 |
out_token = self._auth_context.step(auth_response.nego_tokens[0].nego_token) # type: ignore[index] |
| 403 |
|
| 404 |
# Special edge case, we need to include the final NTLM token in the pubKeyAuth step but the context won't |
| 405 |
# be seen as complete when it's wrapped in SPNEGO. We just check if the known header signature is present. |
| 406 |
if self._auth_context.complete or (out_token and b"NTLMSSP\x00\x03\x00\x00\x00" in out_token): |
| 407 |
break |
| 408 |
|
| 409 |
self._selected_version = min(auth_response.version, _CREDSSP_VERSION) |
| 410 |
log.debug("Negotiated CredSSP version: %d" % self._selected_version) |
| 411 |
if self._selected_version < self._min_version: |
| 412 |
msg = ( |
| 413 |
f"The peer protocol version was {auth_response.version} and did not meet the minimum " |
| 414 |
f"requirements of {self._min_version}" |
| 415 |
) |
| 416 |
raise InvalidTokenError(context_msg=msg) |
| 417 |
|
| 418 |
pub_key_nego_token = NegoData(out_token) if out_token else None |
| 419 |
nonce = os.urandom(32) if self._selected_version > 4 else None |
| 420 |
pub_value = _get_pub_key_auth(public_key, "initiate", nonce=nonce) |
| 421 |
pub_key_request = TSRequest( |
| 422 |
version=_CREDSSP_VERSION, |
| 423 |
nego_tokens=pub_key_nego_token, |
| 424 |
client_nonce=nonce, |
| 425 |
pub_key_auth=self._auth_context.wrap(pub_value).data, |
| 426 |
) |
| 427 |
|
| 428 |
pub_key_response = yield from self._yield_ts_request(pub_key_request, "Public key exchange") |
| 429 |
if not pub_key_response.pub_key_auth: |
| 430 |
raise InvalidTokenError(context_msg="Acceptor did not response with pubKeyAuth info.") |
| 431 |
|
| 432 |
if pub_key_response.nego_tokens: |
| 433 |
# NTLM over SPNEGO auth returned the mechListMIC for us to verify. |
| 434 |
self._auth_context.step(pub_key_response.nego_tokens[0].nego_token) |
| 435 |
|
| 436 |
response_key = self._auth_context.unwrap(pub_key_response.pub_key_auth).data |
| 437 |
expected_key = _get_pub_key_auth(public_key, "accept", nonce=nonce) |
| 438 |
if expected_key != response_key: |
| 439 |
raise BadBindingsError(context_msg="Public key verification failed, potential man in the middle attack") |
| 440 |
|
| 441 |
enc_credentials = self._auth_context.wrap( |
| 442 |
self._ts_credential.pack() # type: ignore[union-attr] # initiate always has one |
| 443 |
).data |
| 444 |
credential_request = TSRequest(_CREDSSP_VERSION, auth_info=enc_credentials) |
| 445 |
self._complete = True |
| 446 |
|
| 447 |
yield from self._yield_ts_request(credential_request, "Credential exchange") |
| 448 |
|
| 449 |
def _step_accept( |
| 450 |
self, |
| 451 |
in_token: typing.Optional[bytes], |
| 452 |
) -> typing.Generator[bytes, bytes, None]: |
| 453 |
"""The acceptor authentication steps of CredSSP.""" |
| 454 |
in_token = yield from self._step_tls(in_token) |
| 455 |
|
| 456 |
auth_request = TSRequest.unpack(in_token or b"") |
| 457 |
|
| 458 |
# The version to use as the acceptor should be the smaller of the client and _CREDSSP_VERSION. |
| 459 |
self._selected_version = min(auth_request.version, _CREDSSP_VERSION) |
| 460 |
log.debug("Negotiated CredSSP version: %d" % self._selected_version) |
| 461 |
if self._selected_version < self._min_version: |
| 462 |
msg = ( |
| 463 |
f"The peer protocol version was {auth_request.version} and did not meet the minimum " |
| 464 |
f"requirements of {self._min_version}" |
| 465 |
) |
| 466 |
raise InvalidTokenError(context_msg=msg) |
| 467 |
|
| 468 |
try: |
| 469 |
log.debug("Starting CredSSP authentication phase") |
| 470 |
if not self._auth_context: |
| 471 |
auth_kwargs: typing.Dict[str, typing.Any] = {} |
| 472 |
if self._hostname: |
| 473 |
auth_kwargs["hostname"] = self._hostname |
| 474 |
if self._service: |
| 475 |
auth_kwargs["service"] = self._service |
| 476 |
self._auth_context = spnego.server(protocol="negotiate", options=self._options, **auth_kwargs) |
| 477 |
|
| 478 |
round = 0 |
| 479 |
while True: |
| 480 |
round += 1 |
| 481 |
nego_out_token = None |
| 482 |
|
| 483 |
if auth_request.nego_tokens: |
| 484 |
nego_out_token = self._auth_context.step(auth_request.nego_tokens[0].nego_token) |
| 485 |
|
| 486 |
if auth_request.pub_key_auth: |
| 487 |
break |
| 488 |
|
| 489 |
auth_response = TSRequest(_CREDSSP_VERSION, nego_tokens=NegoData(nego_out_token or b"")) |
| 490 |
auth_request = yield from self._yield_ts_request(auth_response, "Authentication %d" % round) |
| 491 |
|
| 492 |
except SpnegoError as e: |
| 493 |
# Version 2 and 5 don't support the errorCode field and the initiator won't expect a token back. |
| 494 |
log.warning("Received CredSSP error when accepting credentials: %s", e) |
| 495 |
if self._selected_version in [3, 4] or self._selected_version >= 6: |
| 496 |
error_token = TSRequest(_CREDSSP_VERSION, error_code=e.nt_status) |
| 497 |
yield from self._yield_ts_request(error_token, "Authentication failure") |
| 498 |
|
| 499 |
return |
| 500 |
|
| 501 |
actual_key = self._auth_context.unwrap(auth_request.pub_key_auth).data |
| 502 |
public_key = self._tls_context.public_key or b"" |
| 503 |
expected_key = _get_pub_key_auth(public_key, "initiate", nonce=auth_request.client_nonce) |
| 504 |
if actual_key != expected_key: |
| 505 |
raise BadBindingsError(context_msg="Public key verification failed, potential man in the middle attack") |
| 506 |
|
| 507 |
nego_token = NegoData(nego_out_token) if nego_out_token else None |
| 508 |
server_key = self._auth_context.wrap( |
| 509 |
_get_pub_key_auth(public_key, "accept", nonce=auth_request.client_nonce) |
| 510 |
).data |
| 511 |
pub_key_response = TSRequest(_CREDSSP_VERSION, nego_tokens=nego_token, pub_key_auth=server_key) |
| 512 |
auth_request = yield from self._yield_ts_request(pub_key_response, "Public key exchange") |
| 513 |
|
| 514 |
self._auth_stage = "Credential exchange" |
| 515 |
if not auth_request.auth_info: |
| 516 |
raise InvalidTokenError(context_msg="No credential received on CredSSP TSRequest from initiator") |
| 517 |
|
| 518 |
self._ts_credential = TSCredentials.unpack(self._auth_context.unwrap(auth_request.auth_info).data) |
| 519 |
self._complete = True |
| 520 |
|
| 521 |
def _step_tls(self, in_token: typing.Optional[bytes]) -> typing.Generator[bytes, bytes, bytes]: |
| 522 |
"""The TLS handshake phase of CredSSP.""" |
| 523 |
try: |
| 524 |
while True: |
| 525 |
# For an acceptor we start with a token (Client Hello), write this to the memory BIO before processing. |
| 526 |
if in_token: |
| 527 |
self._in_buff.write(in_token) |
| 528 |
|
| 529 |
want_read = False |
| 530 |
try: |
| 531 |
self._tls_object.do_handshake() |
| 532 |
except ssl.SSLWantReadError: |
| 533 |
# The handshake process requires more data to be exchanged. |
| 534 |
want_read = True |
| 535 |
|
| 536 |
# We need to keep on sending the TLS packets until there is nothing left to send. |
| 537 |
out_token = self._out_buff.read() |
| 538 |
if not out_token: |
| 539 |
break |
| 540 |
in_token = yield out_token |
| 541 |
|
| 542 |
# TLSv1.3 acceptor has no more work to be done after SSLWantReadError was not raised and it received |
| 543 |
# the last token from the user (first authentication token). |
| 544 |
if not want_read and self.usage == "accept": |
| 545 |
out_token = self.unwrap(in_token).data |
| 546 |
break |
| 547 |
|
| 548 |
except ssl.SSLError as e: |
| 549 |
raise InvalidTokenError(context_msg="TLS handshake for CredSSP: %s" % e) from e |
| 550 |
|
| 551 |
cipher, protocol, _ = self._tls_object.cipher() # type: ignore[misc] # This should always be present |
| 552 |
log.debug("TLS handshake complete, negotiation details: %s %s", protocol, cipher) |
| 553 |
return out_token |
| 554 |
|
| 555 |
def _yield_ts_request( |
| 556 |
self, |
| 557 |
ts_request: TSRequest, |
| 558 |
context_msg: str, |
| 559 |
) -> typing.Generator[bytes, bytes, TSRequest]: |
| 560 |
"""Exchanges a TSRequest between the initiator and acceptor.""" |
| 561 |
self._auth_stage = context_msg |
| 562 |
|
| 563 |
out_request = ts_request.pack() |
| 564 |
log.debug("CredSSP TSRequest output: %s" % to_text(base64.b64encode(out_request))) |
| 565 |
wrapped_response = yield self.wrap(out_request).data |
| 566 |
|
| 567 |
in_request = self.unwrap(wrapped_response).data |
| 568 |
log.debug("CredSSP TSRequest input: %s" % to_text(base64.b64encode(in_request))) |
| 569 |
response = TSRequest.unpack(in_request) |
| 570 |
|
| 571 |
if response.error_code: |
| 572 |
# The error code is an NtStatus value, try to see if it maps to a known error in our exception map. |
| 573 |
base_error = NativeError("Received NTStatus in TSRequest from acceptor", winerror=response.error_code) |
| 574 |
raise SpnegoError(base_error=base_error, context_msg=context_msg) |
| 575 |
|
| 576 |
return response |
| 577 |
|
| 578 |
def get_extra_info( |
| 579 |
self, |
| 580 |
name: str, |
| 581 |
default: typing.Any = None, |
| 582 |
) -> typing.Any: |
| 583 |
if name == "client_credential" and self.usage == "accept" and self._ts_credential: |
| 584 |
return self._ts_credential.credentials |
| 585 |
|
| 586 |
elif name == "sslcontext": |
| 587 |
return self._tls_context.context |
| 588 |
|
| 589 |
elif name == "ssl_object": |
| 590 |
return self._tls_object |
| 591 |
|
| 592 |
elif name == "auth_stage": |
| 593 |
return self._auth_stage |
| 594 |
|
| 595 |
elif name == "protocol_version" and self._selected_version is not None: |
| 596 |
return self._selected_version |
| 597 |
|
| 598 |
else: |
| 599 |
return default |
| 600 |
|
| 601 |
def query_message_sizes(self) -> SecPkgContextSizes: |
| 602 |
if not self._tls_object or not self.complete: |
| 603 |
raise NoContextError(context_msg="Cannot get message sizes until context has been established") |
| 604 |
|
| 605 |
cipher_negotiated, tls_protocol, _ = self._tls_object.cipher() # type: ignore[misc] |
| 606 |
trailer_length = _tls_trailer_length(0, tls_protocol, cipher_negotiated) |
| 607 |
|
| 608 |
return SecPkgContextSizes(header=trailer_length) |
| 609 |
|
| 610 |
@_wrap_ssl_error("Invalid TLS state when wrapping data") |
| 611 |
def wrap(self, data: bytes, encrypt: bool = True, qop: typing.Optional[int] = None) -> WrapResult: |
| 612 |
self._tls_object.write(data) |
| 613 |
return WrapResult(data=self._out_buff.read(), encrypted=True) |
| 614 |
|
| 615 |
def wrap_iov( |
| 616 |
self, |
| 617 |
iov: typing.Iterable[IOV], |
| 618 |
encrypt: bool = True, |
| 619 |
qop: typing.Optional[int] = None, |
| 620 |
) -> IOVWrapResult: |
| 621 |
raise OperationNotAvailableError(context_msg="CredSSP does not offer IOV wrapping") |
| 622 |
|
| 623 |
def wrap_winrm(self, data: bytes) -> WinRMWrapResult: |
| 624 |
enc_data = self.wrap(data).data |
| 625 |
cipher_negotiated, tls_protocol, _ = self._tls_object.cipher() # type: ignore[misc] |
| 626 |
trailer_length = _tls_trailer_length(len(data), tls_protocol, cipher_negotiated) |
| 627 |
|
| 628 |
return WinRMWrapResult(header=enc_data[:trailer_length], data=enc_data[trailer_length:], padding_length=0) |
| 629 |
|
| 630 |
@_wrap_ssl_error("Invalid TLS state when unwrapping data") |
| 631 |
def unwrap(self, data: bytes) -> UnwrapResult: |
| 632 |
self._in_buff.write(data) |
| 633 |
|
| 634 |
chunks = [] |
| 635 |
while True: |
| 636 |
try: |
| 637 |
chunks.append(self._tls_object.read()) |
| 638 |
except ssl.SSLWantReadError: |
| 639 |
break |
| 640 |
|
| 641 |
return UnwrapResult(data=b"".join(chunks), encrypted=True, qop=0) |
| 642 |
|
| 643 |
def unwrap_iov( |
| 644 |
self, |
| 645 |
iov: typing.Iterable[IOV], |
| 646 |
) -> IOVUnwrapResult: |
| 647 |
raise OperationNotAvailableError(context_msg="CredSSP does not offer IOV wrapping") |
| 648 |
|
| 649 |
def unwrap_winrm(self, header: bytes, data: bytes) -> bytes: |
| 650 |
return self.unwrap(header + data).data |
| 651 |
|
| 652 |
def sign(self, data: bytes, qop: typing.Optional[int] = None) -> bytes: |
| 653 |
raise OperationNotAvailableError(context_msg="CredSSP does not offer signing") |
| 654 |
|
| 655 |
def verify(self, data: bytes, mic: bytes) -> int: |
| 656 |
raise OperationNotAvailableError(context_msg="CredSSP does not offer verification") |
| 657 |
|
| 658 |
@property |
| 659 |
def _context_attr_map(self) -> typing.List[typing.Tuple[ContextReq, int]]: |
| 660 |
return [] # Not applicable to CredSSP. |