Estructura inicial funcional con documentación en el README.md de la FastAPI
This commit is contained in:
64
env/lib/python3.12/site-packages/spnego/__init__.py
vendored
Normal file
64
env/lib/python3.12/site-packages/spnego/__init__.py
vendored
Normal file
@@ -0,0 +1,64 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import json
|
||||
import logging
|
||||
import logging.config
|
||||
import os
|
||||
|
||||
from spnego._context import (
|
||||
ContextProxy,
|
||||
ContextReq,
|
||||
IOVUnwrapResult,
|
||||
IOVWrapResult,
|
||||
UnwrapResult,
|
||||
WinRMWrapResult,
|
||||
WrapResult,
|
||||
)
|
||||
from spnego._credential import (
|
||||
Credential,
|
||||
CredentialCache,
|
||||
KerberosCCache,
|
||||
KerberosKeytab,
|
||||
NTLMHash,
|
||||
Password,
|
||||
)
|
||||
from spnego.auth import client, server
|
||||
from spnego.exceptions import NegotiateOptions
|
||||
|
||||
__all__ = [
|
||||
"ContextProxy",
|
||||
"ContextReq",
|
||||
"Credential",
|
||||
"CredentialCache",
|
||||
"IOVUnwrapResult",
|
||||
"IOVWrapResult",
|
||||
"KerberosCCache",
|
||||
"KerberosKeytab",
|
||||
"NTLMHash",
|
||||
"Password",
|
||||
"NegotiateOptions",
|
||||
"UnwrapResult",
|
||||
"WinRMWrapResult",
|
||||
"WrapResult",
|
||||
"client",
|
||||
"server",
|
||||
]
|
||||
|
||||
|
||||
def _setup_logging(logger: logging.Logger) -> None:
|
||||
log_path = os.environ.get("PYSPNEGO_LOG_CFG", None)
|
||||
|
||||
if log_path is not None and os.path.exists(log_path): # pragma: no cover
|
||||
# log log config from JSON file
|
||||
with open(log_path, "rt") as f:
|
||||
config = json.load(f)
|
||||
|
||||
logging.config.dictConfig(config)
|
||||
else:
|
||||
# no logging was provided
|
||||
logger.addHandler(logging.NullHandler())
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_setup_logging(logger)
|
||||
926
env/lib/python3.12/site-packages/spnego/__main__.py
vendored
Normal file
926
env/lib/python3.12/site-packages/spnego/__main__.py
vendored
Normal file
@@ -0,0 +1,926 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
# PYTHON_ARGCOMPLETE_OK
|
||||
|
||||
# Copyright: (c) 2020 Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
"""
|
||||
Script that can be used to parse a Negotiate token and output a human readable structure. You can pass in an actual
|
||||
SPNEGO token or just a raw Kerberos or NTLM token, the script should be smart enough to detect the structure of the
|
||||
input.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os.path
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from spnego._asn1 import (
|
||||
unpack_asn1,
|
||||
unpack_asn1_object_identifier,
|
||||
unpack_asn1_sequence,
|
||||
)
|
||||
from spnego._context import GSSMech
|
||||
from spnego._kerberos import (
|
||||
KerberosV5Msg,
|
||||
parse_enum,
|
||||
parse_flags,
|
||||
parse_kerberos_token,
|
||||
)
|
||||
from spnego._ntlm_raw.crypto import hmac_md5, ntowfv1, ntowfv2, rc4k
|
||||
from spnego._ntlm_raw.messages import (
|
||||
Authenticate,
|
||||
AvId,
|
||||
Challenge,
|
||||
Negotiate,
|
||||
NegotiateFlags,
|
||||
NTClientChallengeV2,
|
||||
TargetInfo,
|
||||
Version,
|
||||
)
|
||||
from spnego._spnego import InitialContextToken, NegTokenInit, NegTokenResp, unpack_token
|
||||
from spnego._text import to_bytes
|
||||
from spnego._tls_struct import (
|
||||
DistinguishedNameType,
|
||||
TlsCipherSuite,
|
||||
TlsClientCertificateType,
|
||||
TlsCompressionMethod,
|
||||
TlsContentType,
|
||||
TlsECCurveType,
|
||||
TlsECPointFormat,
|
||||
TlsExtensionType,
|
||||
TlsHandshakeMessageType,
|
||||
TlsProtocolVersion,
|
||||
TlsPskKeyExchangeMode,
|
||||
TlsServerNameType,
|
||||
TlsSignatureScheme,
|
||||
TlsSupportedGroup,
|
||||
)
|
||||
|
||||
HAS_ARGCOMPLETE = False
|
||||
try:
|
||||
import argcomplete
|
||||
|
||||
HAS_ARGCOMPLETE = True
|
||||
except ImportError: # pragma: nocover
|
||||
pass
|
||||
|
||||
|
||||
HAS_YAML = False
|
||||
try:
|
||||
from ruamel import yaml
|
||||
|
||||
HAS_YAML = True
|
||||
except ImportError: # pragma: nocover
|
||||
pass
|
||||
|
||||
|
||||
def _parse_ntlm_version(
|
||||
version: typing.Optional[Version],
|
||||
) -> typing.Optional[typing.Dict[str, typing.Union[int, str]]]:
|
||||
if not version:
|
||||
return None
|
||||
|
||||
return {
|
||||
"Major": version.major,
|
||||
"Minor": version.minor,
|
||||
"Build": version.build,
|
||||
"Reserved": base64.b16encode(version.reserved).decode(),
|
||||
"NTLMRevision": version.revision,
|
||||
}
|
||||
|
||||
|
||||
def _parse_ntlm_target_info(
|
||||
target_info: typing.Optional[TargetInfo],
|
||||
) -> typing.Optional[typing.List[typing.Dict[str, typing.Any]]]:
|
||||
if target_info is None:
|
||||
return None
|
||||
|
||||
text_values = [
|
||||
AvId.nb_computer_name,
|
||||
AvId.nb_domain_name,
|
||||
AvId.dns_computer_name,
|
||||
AvId.dns_domain_name,
|
||||
AvId.dns_tree_name,
|
||||
AvId.target_name,
|
||||
]
|
||||
|
||||
info = []
|
||||
for av_id, raw_value in target_info.items():
|
||||
if av_id == AvId.eol:
|
||||
value = None
|
||||
elif av_id in text_values:
|
||||
value = raw_value
|
||||
elif av_id == AvId.flags:
|
||||
value = parse_flags(raw_value)
|
||||
elif av_id == AvId.timestamp:
|
||||
value = str(raw_value)
|
||||
elif av_id == AvId.single_host:
|
||||
value = {
|
||||
"Size": raw_value.size,
|
||||
"Z4": raw_value.z4,
|
||||
"CustomData": base64.b16encode(raw_value.custom_data).decode(),
|
||||
"MachineId": base64.b16encode(raw_value.machine_id).decode(),
|
||||
}
|
||||
else:
|
||||
value = base64.b16encode(raw_value).decode()
|
||||
|
||||
info.append({"AvId": parse_enum(av_id), "Value": value})
|
||||
|
||||
return info
|
||||
|
||||
|
||||
def _parse_ntlm_negotiate(data: Negotiate) -> typing.Dict[str, typing.Any]:
|
||||
b_data = data.pack()
|
||||
|
||||
msg = {
|
||||
"NegotiateFlags": parse_flags(data.flags, enum_type=NegotiateFlags),
|
||||
"DomainNameFields": {
|
||||
"Len": struct.unpack("<H", b_data[16:18])[0],
|
||||
"MaxLen": struct.unpack("<H", b_data[18:20])[0],
|
||||
"BufferOffset": struct.unpack("<I", b_data[20:24])[0],
|
||||
},
|
||||
"WorkstationFields": {
|
||||
"Len": struct.unpack("<H", b_data[24:26])[0],
|
||||
"MaxLen": struct.unpack("<H", b_data[26:28])[0],
|
||||
"BufferOffset": struct.unpack("<I", b_data[28:32])[0],
|
||||
},
|
||||
"Version": _parse_ntlm_version(data.version),
|
||||
"Payload": {
|
||||
"DomainName": data.domain_name,
|
||||
"Workstation": data.workstation,
|
||||
},
|
||||
}
|
||||
|
||||
return msg
|
||||
|
||||
|
||||
def _parse_ntlm_challenge(data: Challenge) -> typing.Dict[str, typing.Any]:
|
||||
b_data = data.pack()
|
||||
|
||||
msg = {
|
||||
"TargetNameFields": {
|
||||
"Len": struct.unpack("<H", b_data[12:14])[0],
|
||||
"MaxLen": struct.unpack("<H", b_data[14:16])[0],
|
||||
"BufferOffset": struct.unpack("<I", b_data[16:20])[0],
|
||||
},
|
||||
"NegotiateFlags": parse_flags(data.flags, enum_type=NegotiateFlags),
|
||||
"ServerChallenge": base64.b16encode(b_data[24:32]).decode(),
|
||||
"Reserved": base64.b16encode(b_data[32:40]).decode(),
|
||||
"TargetInfoFields": {
|
||||
"Len": struct.unpack("<H", b_data[40:42])[0],
|
||||
"MaxLen": struct.unpack("<H", b_data[42:44])[0],
|
||||
"BufferOffset": struct.unpack("<I", b_data[44:48])[0],
|
||||
},
|
||||
"Version": _parse_ntlm_version(data.version),
|
||||
"Payload": {
|
||||
"TargetName": data.target_name,
|
||||
"TargetInfo": _parse_ntlm_target_info(data.target_info),
|
||||
},
|
||||
}
|
||||
|
||||
return msg
|
||||
|
||||
|
||||
def _parse_ntlm_authenticate(data: Authenticate, password: typing.Optional[str]) -> typing.Dict[str, typing.Any]:
|
||||
b_data = data.pack()
|
||||
|
||||
msg: typing.Dict[str, typing.Any] = {
|
||||
"LmChallengeResponseFields": {
|
||||
"Len": struct.unpack("<H", b_data[12:14])[0],
|
||||
"MaxLen": struct.unpack("<H", b_data[14:16])[0],
|
||||
"BufferOffset": struct.unpack("<I", b_data[16:20])[0],
|
||||
},
|
||||
"NtChallengeResponseFields": {
|
||||
"Len": struct.unpack("<H", b_data[20:22])[0],
|
||||
"MaxLen": struct.unpack("<H", b_data[22:24])[0],
|
||||
"BufferOffset": struct.unpack("<I", b_data[24:28])[0],
|
||||
},
|
||||
"DomainNameFields": {
|
||||
"Len": struct.unpack("<H", b_data[28:30])[0],
|
||||
"MaxLen": struct.unpack("<H", b_data[30:32])[0],
|
||||
"BufferOffset": struct.unpack("<I", b_data[32:36])[0],
|
||||
},
|
||||
"UserNameFields": {
|
||||
"Len": struct.unpack("<H", b_data[36:38])[0],
|
||||
"MaxLen": struct.unpack("<H", b_data[38:40])[0],
|
||||
"BufferOffset": struct.unpack("<I", b_data[40:44])[0],
|
||||
},
|
||||
"WorkstationFields": {
|
||||
"Len": struct.unpack("<H", b_data[44:46])[0],
|
||||
"MaxLen": struct.unpack("<H", b_data[46:48])[0],
|
||||
"BufferOffset": struct.unpack("<I", b_data[48:52])[0],
|
||||
},
|
||||
"EncryptedRandomSessionKeyFields": {
|
||||
"Len": struct.unpack("<H", b_data[52:54])[0],
|
||||
"MaxLen": struct.unpack("<H", b_data[54:56])[0],
|
||||
"BufferOffset": struct.unpack("<I", b_data[56:60])[0],
|
||||
},
|
||||
"NegotiateFlags": parse_flags(data.flags, enum_type=NegotiateFlags),
|
||||
"Version": _parse_ntlm_version(data.version),
|
||||
"MIC": base64.b16encode(data.mic).decode() if data.mic else None,
|
||||
"Payload": {
|
||||
"LmChallengeResponse": None,
|
||||
"NtChallengeResponse": None,
|
||||
"DomainName": data.domain_name,
|
||||
"UserName": data.user_name,
|
||||
"Workstation": data.workstation,
|
||||
"EncryptedRandomSessionKey": None,
|
||||
},
|
||||
}
|
||||
|
||||
key_exchange_key = None
|
||||
lm_response_data = data.lm_challenge_response
|
||||
nt_response_data = data.nt_challenge_response
|
||||
|
||||
if lm_response_data:
|
||||
lm_response: typing.Dict[str, typing.Any] = {
|
||||
"ResponseType": None,
|
||||
"LMProofStr": None,
|
||||
}
|
||||
|
||||
if not nt_response_data or len(nt_response_data) == 24:
|
||||
lm_response["ResponseType"] = "LMv1"
|
||||
lm_response["LMProofStr"] = base64.b16encode(lm_response_data).decode()
|
||||
|
||||
else:
|
||||
lm_response["ResponseType"] = "LMv2"
|
||||
lm_response["LMProofStr"] = base64.b16encode(lm_response_data[:16]).decode()
|
||||
lm_response["ChallengeFromClient"] = base64.b16encode(lm_response_data[16:]).decode()
|
||||
|
||||
msg["Payload"]["LmChallengeResponse"] = lm_response
|
||||
|
||||
if nt_response_data:
|
||||
nt_response: typing.Dict[str, typing.Any] = {
|
||||
"ResponseType": None,
|
||||
"NTProofStr": None,
|
||||
}
|
||||
|
||||
if len(nt_response_data) == 24:
|
||||
nt_response["ResponseType"] = "NTLMv1"
|
||||
nt_response["NTProofStr"] = base64.b16encode(nt_response_data).decode()
|
||||
|
||||
# TODO: need to get a sane way to include the server challenge for ESS KXKEY.
|
||||
# if password and lm_response_data:
|
||||
# session_base_key = hashlib.new('md4', ntowfv1(password)).digest()
|
||||
# lmowf = lmowfv1(password)
|
||||
# if data.flags & NegotiateFlags.extended_session_security == 0:
|
||||
# key_exchange_key = kxkey(data.flags, session_base_key, lmowf, lm_response_data, b"")
|
||||
|
||||
else:
|
||||
nt_proof_str = nt_response_data[:16]
|
||||
nt_response["ResponseType"] = "NTLMv2"
|
||||
nt_response["NTProofStr"] = base64.b16encode(nt_proof_str).decode()
|
||||
|
||||
challenge = NTClientChallengeV2.unpack(nt_response_data[16:])
|
||||
b_challenge = nt_response_data[16:]
|
||||
|
||||
nt_response["ClientChallenge"] = {
|
||||
"RespType": challenge.resp_type,
|
||||
"HiRespType": challenge.hi_resp_type,
|
||||
"Reserved1": struct.unpack("<H", b_challenge[2:4])[0],
|
||||
"Reserved2": struct.unpack("<I", b_challenge[4:8])[0],
|
||||
"TimeStamp": str(challenge.time_stamp),
|
||||
"ChallengeFromClient": base64.b16encode(challenge.challenge_from_client).decode(),
|
||||
"Reserved3": struct.unpack("<I", b_challenge[24:28])[0],
|
||||
"AvPairs": _parse_ntlm_target_info(challenge.av_pairs),
|
||||
"Reserved4": struct.unpack("<I", b_challenge[-4:])[0],
|
||||
}
|
||||
|
||||
if password:
|
||||
response_key_nt = ntowfv2(msg["Payload"]["UserName"], ntowfv1(password), msg["Payload"]["DomainName"])
|
||||
key_exchange_key = hmac_md5(response_key_nt, nt_proof_str)
|
||||
|
||||
msg["Payload"]["NtChallengeResponse"] = nt_response
|
||||
|
||||
if data.encrypted_random_session_key:
|
||||
msg["Payload"]["EncryptedRandomSessionKey"] = base64.b16encode(data.encrypted_random_session_key).decode()
|
||||
|
||||
if data.flags & NegotiateFlags.key_exch and (data.flags & NegotiateFlags.sign or data.flags & NegotiateFlags.seal):
|
||||
session_key = None
|
||||
if key_exchange_key:
|
||||
session_key = rc4k(key_exchange_key, typing.cast(bytes, data.encrypted_random_session_key))
|
||||
|
||||
else:
|
||||
session_key = key_exchange_key
|
||||
|
||||
msg["SessionKey"] = base64.b16encode(session_key).decode() if session_key else "Failed to derive"
|
||||
|
||||
return msg
|
||||
|
||||
|
||||
def _parse_spnego_init(
|
||||
data: NegTokenInit,
|
||||
secret: typing.Optional[str] = None,
|
||||
encoding: typing.Optional[str] = None,
|
||||
) -> typing.Dict[str, typing.Any]:
|
||||
mech_types = [parse_enum(m, enum_type=GSSMech) for m in data.mech_types] if data.mech_types else None
|
||||
|
||||
mech_token = None
|
||||
if data.mech_token:
|
||||
mech_token = parse_token(data.mech_token, secret=secret, encoding=encoding)
|
||||
|
||||
encoding = encoding or "utf-8"
|
||||
|
||||
msg = {
|
||||
"mechTypes": mech_types,
|
||||
"reqFlags": parse_flags(data.req_flags) if data.req_flags is not None else None,
|
||||
"mechToken": mech_token,
|
||||
"mechListMIC": base64.b16encode(data.mech_list_mic).decode() if data.mech_list_mic is not None else None,
|
||||
}
|
||||
|
||||
if data.hint_name or data.hint_address:
|
||||
# This is a NegTokenInit2 structure.
|
||||
msg["negHints"] = {
|
||||
"hintName": data.hint_name.decode(encoding) if data.hint_name else None,
|
||||
"hintAddress": data.hint_address.decode(encoding) if data.hint_address else None,
|
||||
}
|
||||
|
||||
return msg
|
||||
|
||||
|
||||
def _parse_spnego_resp(
|
||||
data: NegTokenResp,
|
||||
secret: typing.Optional[str] = None,
|
||||
encoding: typing.Optional[str] = None,
|
||||
) -> typing.Dict[str, typing.Any]:
|
||||
supported_mech = parse_enum(data.supported_mech, enum_type=GSSMech) if data.supported_mech else None
|
||||
|
||||
response_token = None
|
||||
if data.response_token:
|
||||
response_token = parse_token(data.response_token, secret=secret, encoding=encoding)
|
||||
|
||||
msg = {
|
||||
"negState": parse_enum(data.neg_state) if data.neg_state is not None else None,
|
||||
"supportedMech": supported_mech,
|
||||
"responseToken": response_token,
|
||||
"mechListMIC": base64.b16encode(data.mech_list_mic).decode() if data.mech_list_mic is not None else None,
|
||||
}
|
||||
return msg
|
||||
|
||||
|
||||
def _parse_tls_handshake_client_hello(
|
||||
view: memoryview,
|
||||
) -> typing.Dict[str, typing.Any]:
|
||||
protocol_version = TlsProtocolVersion(struct.unpack(">H", view[:2])[0])
|
||||
view = view[2:]
|
||||
|
||||
random = view[:32]
|
||||
view = view[32:]
|
||||
|
||||
session_id_len = struct.unpack("B", view[:1])[0]
|
||||
view = view[1:]
|
||||
|
||||
session_id = view[:session_id_len]
|
||||
view = view[session_id_len:]
|
||||
|
||||
cipher_suites_len = struct.unpack(">H", view[:2])[0]
|
||||
view = view[2:]
|
||||
cipher_suites_view = view[:cipher_suites_len]
|
||||
view = view[cipher_suites_len:]
|
||||
|
||||
cipher_suites = []
|
||||
while cipher_suites_view:
|
||||
cs = TlsCipherSuite(struct.unpack(">H", cipher_suites_view[:2])[0])
|
||||
cipher_suites.append(f"{cs.name} - 0x{cs.value:04X}")
|
||||
cipher_suites_view = cipher_suites_view[2:]
|
||||
|
||||
compression_methods_len = struct.unpack("B", view[:1])[0]
|
||||
view = view[1:]
|
||||
compression_methods_view = view[:compression_methods_len]
|
||||
view = view[compression_methods_len:]
|
||||
|
||||
compression_methods = []
|
||||
while compression_methods_view:
|
||||
cm = TlsCompressionMethod(struct.unpack("B", compression_methods_view[:1])[0])
|
||||
compression_methods.append(parse_enum(cm))
|
||||
compression_methods_view = compression_methods_view[1:]
|
||||
|
||||
extensions_len = struct.unpack(">H", view[:2])[0]
|
||||
view = view[2:]
|
||||
extensions_view = view[:extensions_len]
|
||||
view = view[extensions_len:]
|
||||
extensions = _parse_tls_extensions(extensions_view, True)
|
||||
|
||||
return {
|
||||
"ProtocolVersion": parse_enum(protocol_version),
|
||||
"Random": base64.b16encode(random).decode(),
|
||||
"SessionID": base64.b16encode(session_id).decode(),
|
||||
"CipherSuites": cipher_suites,
|
||||
"CompressionMethods": compression_methods,
|
||||
"Extensions": extensions,
|
||||
}
|
||||
|
||||
|
||||
def _parse_tls_handshake_server_hello(
|
||||
view: memoryview,
|
||||
) -> typing.Dict[str, typing.Any]:
|
||||
protocol_version = TlsProtocolVersion(struct.unpack(">H", view[:2])[0])
|
||||
view = view[2:]
|
||||
|
||||
random = view[:32]
|
||||
view = view[32:]
|
||||
|
||||
session_id_len = struct.unpack("B", view[:1])[0]
|
||||
view = view[1:]
|
||||
|
||||
session_id = view[:session_id_len]
|
||||
view = view[session_id_len:]
|
||||
|
||||
cipher_suite = TlsCipherSuite(struct.unpack(">H", view[:2])[0])
|
||||
view = view[2:]
|
||||
|
||||
compression_method = TlsCompressionMethod(struct.unpack("B", view[:1])[0])
|
||||
view = view[1:]
|
||||
|
||||
extensions_len = struct.unpack(">H", view[:2])[0]
|
||||
view = view[2:]
|
||||
extensions_view = view[:extensions_len]
|
||||
view = view[extensions_len:]
|
||||
extensions = _parse_tls_extensions(extensions_view, False)
|
||||
|
||||
return {
|
||||
"ProtocolVersion": parse_enum(protocol_version),
|
||||
"Random": base64.b16encode(random).decode(),
|
||||
"SessionID": base64.b16encode(session_id).decode(),
|
||||
"CipherSuite": f"{cipher_suite.name} - 0x{cipher_suite.value:04X}",
|
||||
"CompressionMethod": parse_enum(compression_method),
|
||||
"Extensions": extensions,
|
||||
}
|
||||
|
||||
|
||||
def _parse_tls_handshake_certificate_request(
|
||||
view: memoryview,
|
||||
) -> typing.Dict[str, typing.Any]:
|
||||
cert_types_len = struct.unpack("B", view[:1])[0]
|
||||
view = view[1:]
|
||||
cert_types_view = view[:cert_types_len]
|
||||
view = view[cert_types_len:]
|
||||
|
||||
cert_types = []
|
||||
while cert_types_view:
|
||||
ct = TlsClientCertificateType(struct.unpack("B", cert_types_view[:1])[0])
|
||||
cert_types.append(parse_enum(ct))
|
||||
cert_types_view = cert_types_view[1:]
|
||||
|
||||
sig_algos_len = struct.unpack(">H", view[:2])[0]
|
||||
view = view[2:]
|
||||
sig_algos_view = view[:sig_algos_len]
|
||||
view = view[sig_algos_len:]
|
||||
|
||||
sig_algos = []
|
||||
while sig_algos_view:
|
||||
algo = TlsSignatureScheme(struct.unpack(">H", sig_algos_view[:2])[0])
|
||||
sig_algos.append(parse_enum(algo))
|
||||
sig_algos_view = sig_algos_view[2:]
|
||||
|
||||
dn_len = struct.unpack(">H", view[:2])[0]
|
||||
view = view[2:]
|
||||
dn_view = view[:dn_len]
|
||||
view = view[dn_len:]
|
||||
|
||||
dns = []
|
||||
while dn_view:
|
||||
entry_len = struct.unpack(">H", dn_view[:2])[0]
|
||||
dn_view = dn_view[2:]
|
||||
entry_view = dn_view[:entry_len]
|
||||
dn_view = dn_view[entry_len:]
|
||||
|
||||
for dn_entry in unpack_asn1_sequence(entry_view):
|
||||
for dn_set in unpack_asn1_sequence(dn_entry):
|
||||
dn_data = unpack_asn1(dn_set.b_data)[0]
|
||||
dn_oid, dn_str = unpack_asn1_sequence(dn_data)
|
||||
oid = DistinguishedNameType(unpack_asn1_object_identifier(dn_oid))
|
||||
|
||||
dns.append(
|
||||
{
|
||||
"OID": parse_enum(oid),
|
||||
"Value": dn_str.b_data.tobytes().decode("utf-8"),
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"CertificateTypes": cert_types,
|
||||
"SignatureAlgorithms": sig_algos,
|
||||
"CertificateAuthorities": dns,
|
||||
}
|
||||
|
||||
|
||||
def _parse_tls_handshake_server_key_exchange(
|
||||
view: memoryview,
|
||||
protocol_version: TlsProtocolVersion,
|
||||
) -> typing.Dict[str, typing.Any]:
|
||||
curve_type = TlsECCurveType(struct.unpack("B", view[:1])[0])
|
||||
view = view[1:]
|
||||
|
||||
curve = TlsSupportedGroup(struct.unpack(">H", view[:2])[0])
|
||||
view = view[2:]
|
||||
|
||||
pubkey_len = struct.unpack("B", view[:1])[0]
|
||||
view = view[1:]
|
||||
|
||||
pubkey = view[:pubkey_len].tobytes()
|
||||
view = view[pubkey_len:]
|
||||
|
||||
signature_algo = None
|
||||
if protocol_version >= TlsProtocolVersion.tls1_2:
|
||||
signature_algo = TlsSignatureScheme(struct.unpack(">H", view[:2])[0])
|
||||
view = view[2:]
|
||||
|
||||
signature_len = struct.unpack(">H", view[:2])[0]
|
||||
view = view[2:]
|
||||
|
||||
signature = view[:signature_len].tobytes()
|
||||
|
||||
return {
|
||||
"CurveType": parse_enum(curve_type),
|
||||
"Curve": parse_enum(curve),
|
||||
"PublicKey": base64.b16encode(pubkey).decode(),
|
||||
"SignatureAlgorithm": parse_enum(signature_algo) if signature_algo else None,
|
||||
"Signature": base64.b16encode(signature).decode(),
|
||||
}
|
||||
|
||||
|
||||
def _parse_tls_extensions(
|
||||
view: memoryview,
|
||||
is_client_hello: bool,
|
||||
) -> typing.List[typing.Dict[str, typing.Any]]:
|
||||
extensions = []
|
||||
|
||||
while view:
|
||||
ext_type = TlsExtensionType(struct.unpack(">H", view[:2])[0])
|
||||
view = view[2:]
|
||||
|
||||
ext_len = struct.unpack(">H", view[:2])[0]
|
||||
view = view[2:]
|
||||
|
||||
ext_data = view[:ext_len]
|
||||
view = view[ext_len:]
|
||||
|
||||
data: typing.Any = None
|
||||
if ext_len == 0:
|
||||
data = None
|
||||
|
||||
elif ext_type == TlsExtensionType.server_name:
|
||||
data_len = struct.unpack(">H", ext_data[:2])[0]
|
||||
data_view = ext_data[2 : 2 + data_len]
|
||||
data = []
|
||||
while data_view:
|
||||
name_type = TlsServerNameType(struct.unpack("B", data_view[:1])[0])
|
||||
name_len = struct.unpack(">H", data_view[1:3])[0]
|
||||
name = data_view[3 : 3 + name_len].tobytes().decode("utf-8")
|
||||
data.append(
|
||||
{
|
||||
"Type": parse_enum(name_type),
|
||||
"Name": name,
|
||||
}
|
||||
)
|
||||
data_view = data_view[3 + name_len :]
|
||||
|
||||
elif ext_type == TlsExtensionType.ec_point_formats:
|
||||
data_len = struct.unpack("B", ext_data[:1])[0]
|
||||
data_view = ext_data[1 : 1 + data_len]
|
||||
data = [parse_enum(TlsECPointFormat(b)) for b in list(data_view)]
|
||||
|
||||
elif ext_type == TlsExtensionType.supported_groups:
|
||||
data_len = struct.unpack(">H", ext_data[:2])[0]
|
||||
data_view = ext_data[2 : 2 + data_len]
|
||||
data = []
|
||||
while data_view:
|
||||
data.append(parse_enum(TlsSupportedGroup(struct.unpack(">H", data_view[:2])[0])))
|
||||
data_view = data_view[2:]
|
||||
|
||||
elif ext_type == TlsExtensionType.application_layer_protocol_negotiation:
|
||||
data_len = struct.unpack(">H", ext_data[:2])[0]
|
||||
data_view = ext_data[2 : 2 + data_len]
|
||||
data = []
|
||||
while data_view:
|
||||
alpn_len = struct.unpack("B", data_view[:1])[0]
|
||||
data_view = data_view[1:]
|
||||
data.append(data_view[:alpn_len].tobytes().decode())
|
||||
data_view = data_view[alpn_len:]
|
||||
|
||||
elif ext_type == TlsExtensionType.session_ticket:
|
||||
data = base64.b16encode(ext_data.tobytes()).decode()
|
||||
|
||||
elif ext_type == TlsExtensionType.signature_algorithms:
|
||||
data_len = struct.unpack(">H", ext_data[:2])[0]
|
||||
data_view = ext_data[2 : 2 + data_len]
|
||||
data = []
|
||||
while data_view:
|
||||
data.append(parse_enum(TlsSignatureScheme(struct.unpack(">H", data_view[:2])[0])))
|
||||
data_view = data_view[2:]
|
||||
|
||||
elif ext_type == TlsExtensionType.supported_versions:
|
||||
if is_client_hello:
|
||||
data_len = struct.unpack("B", ext_data[:1])[0]
|
||||
data_view = ext_data[1 : 1 + data_len]
|
||||
data = []
|
||||
while data_view:
|
||||
data.append(parse_enum(TlsProtocolVersion(struct.unpack(">H", data_view[:2])[0])))
|
||||
data_view = data_view[2:]
|
||||
|
||||
else:
|
||||
data = parse_enum(TlsProtocolVersion(struct.unpack(">H", ext_data[:2])[0]))
|
||||
|
||||
elif ext_type == TlsExtensionType.psk_key_exchange_modes:
|
||||
data_len = struct.unpack("B", ext_data[:1])[0]
|
||||
data_view = ext_data[1 : 1 + data_len]
|
||||
data = []
|
||||
while data_view:
|
||||
data.append(parse_enum(TlsPskKeyExchangeMode(struct.unpack("B", data_view[:1])[0])))
|
||||
data_view = data_view[1:]
|
||||
|
||||
elif ext_type == TlsExtensionType.key_share:
|
||||
if is_client_hello:
|
||||
data_len = struct.unpack(">H", ext_data[:2])[0]
|
||||
data_view = ext_data[2 : 2 + data_len]
|
||||
data = []
|
||||
while data_view:
|
||||
key_share_group = TlsSupportedGroup(struct.unpack(">H", data_view[:2])[0])
|
||||
key_exchange_len = struct.unpack(">H", data_view[2:4])[0]
|
||||
key_exchange = data_view[4 : 4 + key_exchange_len].tobytes()
|
||||
|
||||
data.append(
|
||||
{
|
||||
"Group": parse_enum(key_share_group),
|
||||
"Key": base64.b16encode(key_exchange).decode(),
|
||||
}
|
||||
)
|
||||
data_view = data_view[4 + key_exchange_len :]
|
||||
else:
|
||||
key_share_group = TlsSupportedGroup(struct.unpack(">H", ext_data[:2])[0])
|
||||
key_exchange_len = struct.unpack(">H", ext_data[2:4])[0]
|
||||
key_exchange = ext_data[4 : 4 + key_exchange_len].tobytes()
|
||||
data = {
|
||||
"Group": parse_enum(key_share_group),
|
||||
"Key": base64.b16encode(key_exchange).decode(),
|
||||
}
|
||||
|
||||
formated_data = {
|
||||
"ExtensionType": parse_enum(ext_type),
|
||||
}
|
||||
if data is not None:
|
||||
formated_data["Data"] = data
|
||||
if data is not None or ext_data:
|
||||
formated_data["RawData"] = base64.b16encode(ext_data).decode()
|
||||
extensions.append(formated_data)
|
||||
|
||||
return extensions
|
||||
|
||||
|
||||
def main(args: typing.List[str]) -> None:
|
||||
"""Main program entry point."""
|
||||
parsed_args = parse_args(args)
|
||||
|
||||
if parsed_args.token:
|
||||
b_data = to_bytes(parsed_args.token)
|
||||
else:
|
||||
if parsed_args.file:
|
||||
file_path = os.path.abspath(os.path.expanduser(os.path.expandvars(parsed_args.file)))
|
||||
b_file_path = to_bytes(file_path)
|
||||
if not os.path.exists(b_file_path):
|
||||
raise ValueError("Cannot find file at path '%s'" % file_path)
|
||||
|
||||
with open(b_file_path, mode="rb") as fd:
|
||||
b_data = fd.read()
|
||||
else:
|
||||
b_data = sys.stdin.buffer.read()
|
||||
|
||||
if re.match(b"^[a-fA-F0-9\\s]+$", b_data):
|
||||
# Input data was a hex string.
|
||||
b_data = base64.b16decode(re.sub(b"[\\s]", b"", b_data.strip().upper()))
|
||||
if re.match(b"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$", b_data):
|
||||
# Input data was a base64 string.
|
||||
b_data = base64.b64decode(b_data.strip())
|
||||
|
||||
token_info: typing.Union[typing.List, typing.Dict]
|
||||
if re.match(b"[\x00|\x14|\x15|\x16|\x17]\x03[\x01|\x02|\x03]", b_data):
|
||||
token_info = parse_tls_token(b_data)
|
||||
else:
|
||||
token_info = parse_token(b_data, secret=parsed_args.secret, encoding=parsed_args.encoding)
|
||||
|
||||
if parsed_args.output_format == "yaml" and HAS_YAML:
|
||||
y = yaml.YAML()
|
||||
y.default_flow_style = False
|
||||
y.dump(token_info, sys.stdout)
|
||||
else:
|
||||
print(json.dumps(token_info, indent=4))
|
||||
|
||||
|
||||
def parse_args(args: typing.List[str]) -> argparse.Namespace:
|
||||
"""Parse and return args."""
|
||||
parser = argparse.ArgumentParser(description="Parse Microsoft authentication tokens into a human readable format.")
|
||||
|
||||
data = parser.add_mutually_exclusive_group()
|
||||
|
||||
data.add_argument(
|
||||
"-t", "--token", dest="token", help="Raw base64 encoded or hex string token as a command line argument."
|
||||
)
|
||||
|
||||
data.add_argument(
|
||||
"-f",
|
||||
"--file",
|
||||
default="",
|
||||
dest="file",
|
||||
help="Path to file that contains raw bytes, base64, or hex string of token to parse, Defaults to reading from "
|
||||
"stdin if neither -t or -f is specified.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--encoding",
|
||||
dest="encoding",
|
||||
help="The encoding to use when trying to decode text fields from bytes in tokens that don't have a negotiated "
|
||||
"encoding. This defaults to 'windows-1252' for NTLM tokens and 'utf-8' for Kerberos/SPNEGO tokens.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--format",
|
||||
"--output-format",
|
||||
choices=["json", "yaml"],
|
||||
default="json",
|
||||
dest="output_format",
|
||||
type=lambda s: s.lower(),
|
||||
help="Set the output format of the token, default is (json). Using yaml requires the ruamel.yaml Python "
|
||||
"library to be installed pip install pyspnego[yaml].",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--secret",
|
||||
"--password",
|
||||
dest="secret",
|
||||
default=None,
|
||||
help="Optional info that is the secret information for a protocol that can be used to decrypt encrypted "
|
||||
"fields and/or derive the unique session key in the exchange. This is currently only supported by NTLM "
|
||||
"tokens to generate the session key.",
|
||||
)
|
||||
|
||||
if HAS_ARGCOMPLETE:
|
||||
argcomplete.autocomplete(parser)
|
||||
|
||||
parsed_args = parser.parse_args(args)
|
||||
|
||||
if parsed_args.output_format == "yaml" and not HAS_YAML:
|
||||
raise ValueError("Cannot output as yaml as ruamel.yaml is not installed.")
|
||||
|
||||
return parsed_args
|
||||
|
||||
|
||||
def parse_token(
|
||||
b_data: bytes,
|
||||
secret: typing.Optional[str] = None,
|
||||
encoding: typing.Optional[str] = None,
|
||||
mech: typing.Optional[typing.Union[str, GSSMech]] = None,
|
||||
) -> typing.Dict[str, typing.Any]:
|
||||
"""
|
||||
:param b_data: A byte string of the token to parse. This can be a NTLM or GSSAPI (SPNEGO/Kerberos) token.
|
||||
:param secret: The secret data used to decrypt fields and/or derive session keys.
|
||||
:param encoding: The encoding to use for token fields that represent text. This is only used for fields where there
|
||||
is no negotiation for the encoding of that particular field. Defaults to 'windows-1252' for NTLM and 'utf-8'
|
||||
for Kerberos.
|
||||
:return: A dict containing the parsed token data.
|
||||
"""
|
||||
gss_mech: typing.Optional[GSSMech] = None
|
||||
if mech and not isinstance(mech, GSSMech):
|
||||
gss_mech = GSSMech.from_oid(mech)
|
||||
|
||||
try:
|
||||
token = unpack_token(b_data, mech=gss_mech, unwrap=True, encoding=encoding)
|
||||
except Exception as e:
|
||||
return {
|
||||
"MessageType": "Unknown - Failed to parse see Data for more details.",
|
||||
"Data": "Failed to parse token: %s" % str(e),
|
||||
"RawData": base64.b16encode(b_data).decode(),
|
||||
}
|
||||
|
||||
msg_type = "Unknown"
|
||||
data: typing.Union[str, typing.Dict[str, typing.Any]] = "Failed to parse SPNEGO token due to unknown mech type"
|
||||
|
||||
# SPNEGO messages.
|
||||
if isinstance(token, InitialContextToken):
|
||||
msg_type = "SPNEGO InitialContextToken"
|
||||
data = {
|
||||
"thisMech": parse_enum(token.this_mech, enum_type=GSSMech),
|
||||
"innerContextToken": parse_token(
|
||||
token.inner_context_token, mech=token.this_mech, secret=secret, encoding=encoding
|
||||
),
|
||||
}
|
||||
|
||||
elif isinstance(token, NegTokenInit):
|
||||
data = _parse_spnego_init(token, secret, encoding)
|
||||
if "negHints" in data:
|
||||
msg_type = "SPNEGO NegTokenInit2"
|
||||
|
||||
else:
|
||||
msg_type = "SPNEGO NegTokenInit"
|
||||
|
||||
elif isinstance(token, NegTokenResp):
|
||||
msg_type = "SPNEGO NegTokenResp"
|
||||
data = _parse_spnego_resp(token, secret, encoding)
|
||||
|
||||
# NTLM messages.
|
||||
elif isinstance(token, (Negotiate, Challenge, Authenticate)):
|
||||
msg_type = parse_enum(token.MESSAGE_TYPE)
|
||||
|
||||
if isinstance(token, Negotiate):
|
||||
data = _parse_ntlm_negotiate(token)
|
||||
|
||||
elif isinstance(token, Challenge):
|
||||
data = _parse_ntlm_challenge(token)
|
||||
|
||||
else:
|
||||
data = _parse_ntlm_authenticate(token, secret)
|
||||
|
||||
# Kerberos messages.
|
||||
elif isinstance(token, KerberosV5Msg):
|
||||
msg_type = parse_enum(token.MESSAGE_TYPE)
|
||||
data = parse_kerberos_token(token, secret, encoding)
|
||||
|
||||
return {
|
||||
"MessageType": msg_type,
|
||||
"Data": data,
|
||||
"RawData": base64.b16encode(b_data).decode(),
|
||||
}
|
||||
|
||||
|
||||
def parse_tls_token(
|
||||
b_data: bytes,
|
||||
) -> typing.List[typing.Dict[str, typing.Any]]:
|
||||
"""
|
||||
:param b_data: A byte string of the TLS token to parse.
|
||||
:return: A dict containing the parsed TLS token data.
|
||||
"""
|
||||
view = memoryview(b_data)
|
||||
|
||||
res = []
|
||||
while view:
|
||||
content_type = TlsContentType(struct.unpack("B", view[:1])[0])
|
||||
protocol_version = TlsProtocolVersion(struct.unpack(">H", view[1:3])[0])
|
||||
token_length = struct.unpack(">H", view[3:5])[0]
|
||||
token_view = view[5 : 5 + token_length]
|
||||
|
||||
data: typing.Optional[typing.List[typing.Dict[str, typing.Any]]] = None
|
||||
if content_type == TlsContentType.handshake:
|
||||
data = []
|
||||
|
||||
while token_view:
|
||||
handshake_type = TlsHandshakeMessageType(struct.unpack("B", token_view[:1])[0])
|
||||
message_len = struct.unpack(">L", b"\x00" + token_view[1:4])[0]
|
||||
handshake_view = token_view[4 : 4 + message_len]
|
||||
|
||||
handshake_data: typing.Optional[typing.Dict[str, typing.Any]] = None
|
||||
if handshake_type == TlsHandshakeMessageType.client_hello:
|
||||
handshake_data = _parse_tls_handshake_client_hello(handshake_view)
|
||||
|
||||
elif handshake_type == TlsHandshakeMessageType.server_hello:
|
||||
handshake_data = _parse_tls_handshake_server_hello(handshake_view)
|
||||
|
||||
elif handshake_type == TlsHandshakeMessageType.certificate:
|
||||
cert_len = struct.unpack(">I", b"\x00" + handshake_view[:3])[0]
|
||||
handshake_data = {
|
||||
"Certificate": base64.b16encode(handshake_view[3 : 3 + cert_len].tobytes()).decode(),
|
||||
}
|
||||
|
||||
elif handshake_type == TlsHandshakeMessageType.certificate_request:
|
||||
handshake_data = _parse_tls_handshake_certificate_request(handshake_view)
|
||||
|
||||
elif handshake_type == TlsHandshakeMessageType.server_key_exchange:
|
||||
handshake_data = _parse_tls_handshake_server_key_exchange(handshake_view, protocol_version)
|
||||
|
||||
elif handshake_type == TlsHandshakeMessageType.client_key_exchange:
|
||||
key_len = struct.unpack("B", handshake_view[:1])[0]
|
||||
handshake_data = {
|
||||
"PublicKey": base64.b16encode(handshake_view[1 : 1 + key_len].tobytes()).decode(),
|
||||
}
|
||||
|
||||
formatted_handshake_data: typing.Dict[str, typing.Any] = {
|
||||
"HandshakeType": parse_enum(handshake_type),
|
||||
}
|
||||
if handshake_data is not None:
|
||||
formatted_handshake_data["Data"] = handshake_data
|
||||
formatted_handshake_data["RawData"] = base64.b16encode(token_view[: 4 + message_len].tobytes()).decode()
|
||||
data.append(formatted_handshake_data)
|
||||
token_view = token_view[4 + message_len :]
|
||||
|
||||
formatted_data: typing.Dict[str, typing.Any] = {
|
||||
"ContentType": parse_enum(content_type),
|
||||
"ProtocolVersion": parse_enum(protocol_version),
|
||||
}
|
||||
if data is not None:
|
||||
formatted_data["Data"] = data
|
||||
|
||||
formatted_data["RawData"] = base64.b16encode(view[: 5 + token_length].tobytes()).decode()
|
||||
|
||||
res.append(formatted_data)
|
||||
view = view[5 + token_length :]
|
||||
|
||||
return res
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: nocover
|
||||
main(sys.argv[1:])
|
||||
600
env/lib/python3.12/site-packages/spnego/_asn1.py
vendored
Normal file
600
env/lib/python3.12/site-packages/spnego/_asn1.py
vendored
Normal file
@@ -0,0 +1,600 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import collections
|
||||
import datetime
|
||||
import enum
|
||||
import struct
|
||||
import typing
|
||||
|
||||
from spnego._text import to_bytes, to_text
|
||||
|
||||
ASN1Value = collections.namedtuple("ASN1Value", ["tag_class", "constructed", "tag_number", "b_data"])
|
||||
"""A representation of an ASN.1 TLV as a Python object.
|
||||
|
||||
Defines the ASN.1 Type Length Value (TLV) values as separate objects for easier parsing. This is returned by
|
||||
:method:`unpack_asn1`.
|
||||
|
||||
Attributes:
|
||||
tag_class (TagClass): The tag class of the TLV.
|
||||
constructed (bool): Whether the value is constructed or 0, 1, or more element encodings (True) or not (False).
|
||||
tag_number (Union[TypeTagNumber, int]): The tag number of the value, can be a TypeTagNumber if the tag_class
|
||||
is `universal` otherwise it's an explicit tag number value.
|
||||
b_data (bytes): The raw byes of the TLV value.
|
||||
"""
|
||||
|
||||
|
||||
class TagClass(enum.IntEnum):
|
||||
universal = 0
|
||||
application = 1
|
||||
context_specific = 2
|
||||
private = 3
|
||||
|
||||
@classmethod
|
||||
def native_labels(cls) -> typing.Dict["TagClass", str]:
|
||||
return {
|
||||
TagClass.universal: "Universal",
|
||||
TagClass.application: "Application",
|
||||
TagClass.context_specific: "Context-specific",
|
||||
TagClass.private: "Private",
|
||||
}
|
||||
|
||||
|
||||
class TypeTagNumber(enum.IntEnum):
|
||||
end_of_content = 0
|
||||
boolean = 1
|
||||
integer = 2
|
||||
bit_string = 3
|
||||
octet_string = 4
|
||||
null = 5
|
||||
object_identifier = 6
|
||||
object_descriptor = 7
|
||||
external = 8
|
||||
real = 9
|
||||
enumerated = 10
|
||||
embedded_pdv = 11
|
||||
utf8_string = 12
|
||||
relative_oid = 13
|
||||
time = 14
|
||||
reserved = 15
|
||||
sequence = 16
|
||||
sequence_of = 16
|
||||
set = 17
|
||||
set_of = 17
|
||||
numeric_string = 18
|
||||
printable_string = 19
|
||||
t61_string = 20
|
||||
videotex_string = 21
|
||||
ia5_string = 22
|
||||
utc_time = 23
|
||||
generalized_time = 24
|
||||
graphic_string = 25
|
||||
visible_string = 26
|
||||
general_string = 27
|
||||
universal_string = 28
|
||||
character_string = 29
|
||||
bmp_string = 30
|
||||
date = 31
|
||||
time_of_day = 32
|
||||
date_time = 33
|
||||
duration = 34
|
||||
oid_iri = 35
|
||||
relative_oid_iri = 36
|
||||
|
||||
@classmethod
|
||||
def native_labels(cls) -> typing.Dict[int, str]:
|
||||
return {
|
||||
TypeTagNumber.end_of_content: "End-of-Content (EOC)",
|
||||
TypeTagNumber.boolean: "BOOLEAN",
|
||||
TypeTagNumber.integer: "INTEGER",
|
||||
TypeTagNumber.bit_string: "BIT STRING",
|
||||
TypeTagNumber.octet_string: "OCTET STRING",
|
||||
TypeTagNumber.null: "NULL",
|
||||
TypeTagNumber.object_identifier: "OBJECT IDENTIFIER",
|
||||
TypeTagNumber.object_descriptor: "Object Descriptor",
|
||||
TypeTagNumber.external: "EXTERNAL",
|
||||
TypeTagNumber.real: "REAL (float)",
|
||||
TypeTagNumber.enumerated: "ENUMERATED",
|
||||
TypeTagNumber.embedded_pdv: "EMBEDDED PDV",
|
||||
TypeTagNumber.utf8_string: "UTF8String",
|
||||
TypeTagNumber.relative_oid: "RELATIVE-OID",
|
||||
TypeTagNumber.time: "TIME",
|
||||
TypeTagNumber.reserved: "RESERVED",
|
||||
TypeTagNumber.sequence: "SEQUENCE or SEQUENCE OF",
|
||||
TypeTagNumber.set: "SET or SET OF",
|
||||
TypeTagNumber.numeric_string: "NumericString",
|
||||
TypeTagNumber.printable_string: "PrintableString",
|
||||
TypeTagNumber.t61_string: "T61String",
|
||||
TypeTagNumber.videotex_string: "VideotexString",
|
||||
TypeTagNumber.ia5_string: "IA5String",
|
||||
TypeTagNumber.utc_time: "UTCTime",
|
||||
TypeTagNumber.generalized_time: "GeneralizedTime",
|
||||
TypeTagNumber.graphic_string: "GraphicString",
|
||||
TypeTagNumber.visible_string: "VisibleString",
|
||||
TypeTagNumber.general_string: "GeneralString",
|
||||
TypeTagNumber.universal_string: "UniversalString",
|
||||
TypeTagNumber.character_string: "CHARACTER",
|
||||
TypeTagNumber.bmp_string: "BMPString",
|
||||
TypeTagNumber.date: "DATE",
|
||||
TypeTagNumber.time_of_day: "TIME-OF-DAY",
|
||||
TypeTagNumber.date_time: "DATE-TIME",
|
||||
TypeTagNumber.duration: "DURATION",
|
||||
TypeTagNumber.oid_iri: "OID-IRI",
|
||||
TypeTagNumber.relative_oid_iri: "RELATIVE-OID-IRI",
|
||||
}
|
||||
|
||||
|
||||
def extract_asn1_tlv(
|
||||
tlv: typing.Union[bytes, ASN1Value],
|
||||
tag_class: TagClass,
|
||||
tag_number: typing.Union[int, TypeTagNumber],
|
||||
) -> bytes:
|
||||
"""Extract the bytes and validates the existing tag of an ASN.1 value."""
|
||||
if isinstance(tlv, ASN1Value):
|
||||
if tag_class == TagClass.universal:
|
||||
label_name = TypeTagNumber.native_labels().get(tag_number, "Unknown tag type")
|
||||
msg = "Invalid ASN.1 %s tags, actual tag class %s and tag number %s" % (
|
||||
label_name,
|
||||
f"{type(tlv.tag_class).__name__}.{tlv.tag_class.name}",
|
||||
(
|
||||
f"{type(tlv.tag_number).__name__}.{tlv.tag_number.name}"
|
||||
if isinstance(tlv.tag_number, TypeTagNumber)
|
||||
else tlv.tag_number
|
||||
),
|
||||
)
|
||||
|
||||
else:
|
||||
msg = "Invalid ASN.1 tags, actual tag %s and number %s, expecting class %s and number %s" % (
|
||||
f"{type(tlv.tag_class).__name__}.{tlv.tag_class.name}",
|
||||
(
|
||||
f"{type(tlv.tag_number).__name__}.{tlv.tag_number.name}"
|
||||
if isinstance(tlv.tag_number, TypeTagNumber)
|
||||
else tlv.tag_number
|
||||
),
|
||||
f"{type(tag_class).__name__}.{tag_class.name}",
|
||||
(
|
||||
f"{type(tag_number).__name__}.{tag_number.name}"
|
||||
if isinstance(tag_number, TypeTagNumber)
|
||||
else tag_number
|
||||
),
|
||||
)
|
||||
|
||||
if tlv.tag_class != tag_class or tlv.tag_number != tag_number:
|
||||
raise ValueError(msg)
|
||||
|
||||
return tlv.b_data
|
||||
|
||||
return tlv
|
||||
|
||||
|
||||
def get_sequence_value(
|
||||
sequence: typing.Dict[int, ASN1Value],
|
||||
tag: int,
|
||||
structure_name: str,
|
||||
field_name: typing.Optional[str] = None,
|
||||
unpack_func: typing.Optional[typing.Callable[[typing.Union[bytes, ASN1Value]], typing.Any]] = None,
|
||||
) -> typing.Any:
|
||||
"""Gets an optional tag entry in a tagged sequence will a further unpacking of the value."""
|
||||
if tag not in sequence:
|
||||
return
|
||||
|
||||
if not unpack_func:
|
||||
return sequence[tag]
|
||||
|
||||
try:
|
||||
return unpack_func(sequence[tag])
|
||||
except ValueError as e:
|
||||
where = "%s in %s" % (field_name, structure_name) if field_name else structure_name
|
||||
raise ValueError("Failed unpacking %s: %s" % (where, str(e))) from e
|
||||
|
||||
|
||||
def pack_asn1(
|
||||
tag_class: TagClass,
|
||||
constructed: bool,
|
||||
tag_number: typing.Union[TypeTagNumber, int],
|
||||
b_data: bytes,
|
||||
) -> bytes:
|
||||
"""Pack the ASN.1 value into the ASN.1 bytes.
|
||||
|
||||
Will pack the raw bytes into an ASN.1 Type Length Value (TLV) value. A TLV is in the form:
|
||||
|
||||
| Identifier Octet(s) | Length Octet(s) | Data Octet(s) |
|
||||
|
||||
Args:
|
||||
tag_class: The tag class of the data.
|
||||
constructed: Whether the data is constructed (True), i.e. contains 0, 1, or more element encodings, or is
|
||||
primitive (False).
|
||||
tag_number: The type tag number if tag_class is universal else the explicit tag number of the TLV.
|
||||
b_data: The encoded value to pack into the ASN.1 TLV.
|
||||
|
||||
Returns:
|
||||
bytes: The ASN.1 value as raw bytes.
|
||||
"""
|
||||
b_asn1_data = bytearray()
|
||||
|
||||
# ASN.1 Identifier octet is
|
||||
#
|
||||
# | Octet 1 | | Octet 2 |
|
||||
# | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 |
|
||||
# | Class | P/C | Tag Number (0-30) | | More | Tag number |
|
||||
#
|
||||
# If Tag Number is >= 31 the first 5 bits are 1 and the 2nd octet is used to encode the length.
|
||||
if tag_class < 0 or tag_class > 3:
|
||||
raise ValueError("tag_class must be between 0 and 3")
|
||||
|
||||
identifier_octets = tag_class << 6
|
||||
identifier_octets |= (1 if constructed else 0) << 5
|
||||
|
||||
if tag_number < 31:
|
||||
identifier_octets |= tag_number
|
||||
b_asn1_data.append(identifier_octets)
|
||||
else:
|
||||
# Set the first 5 bits of the first octet to 1 and encode the tag number in subsequent octets.
|
||||
identifier_octets |= 31
|
||||
b_asn1_data.append(identifier_octets)
|
||||
b_asn1_data.extend(_pack_asn1_octet_number(tag_number))
|
||||
|
||||
# ASN.1 Length octet for DER encoding is always in the definite form. This form packs the lengths in the following
|
||||
# octet structure:
|
||||
#
|
||||
# | Octet 1 | | Octet n |
|
||||
# | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 |
|
||||
# | Long form | Short = length, Long = num octets | | Big endian length for long |
|
||||
#
|
||||
# Basically if the length < 127 it's encoded in the first octet, otherwise the first octet 7 bits indicates how
|
||||
# many subsequent octets were used to encode the length.
|
||||
length = len(b_data)
|
||||
if length < 128:
|
||||
b_asn1_data.append(length)
|
||||
else:
|
||||
length_octets = bytearray()
|
||||
while length:
|
||||
length_octets.append(length & 0b11111111)
|
||||
length >>= 8
|
||||
|
||||
# Reverse the octets so the higher octets are first, add the initial length octet with the MSB set and add them
|
||||
# all to the main ASN.1 byte array.
|
||||
length_octets.reverse()
|
||||
b_asn1_data.append(len(length_octets) | 0b10000000)
|
||||
b_asn1_data.extend(length_octets)
|
||||
|
||||
return bytes(b_asn1_data) + b_data
|
||||
|
||||
|
||||
def pack_asn1_bit_string(
|
||||
value: bytes,
|
||||
tag: bool = True,
|
||||
) -> bytes:
|
||||
# First octet is the number of unused bits in the last octet from the LSB.
|
||||
b_data = b"\x00" + value
|
||||
if tag:
|
||||
b_data = pack_asn1(TagClass.universal, False, TypeTagNumber.bit_string, b_data)
|
||||
|
||||
return b_data
|
||||
|
||||
|
||||
def pack_asn1_enumerated(
|
||||
value: int,
|
||||
tag: bool = True,
|
||||
) -> bytes:
|
||||
"""Packs an int into an ASN.1 ENUMERATED byte value with optional universal tagging."""
|
||||
b_data = pack_asn1_integer(value, tag=False)
|
||||
if tag:
|
||||
b_data = pack_asn1(TagClass.universal, False, TypeTagNumber.enumerated, b_data)
|
||||
|
||||
return b_data
|
||||
|
||||
|
||||
def pack_asn1_general_string(
|
||||
value: typing.Union[str, bytes],
|
||||
tag: bool = True,
|
||||
encoding: str = "ascii",
|
||||
) -> bytes:
|
||||
"""Packs an string value into an ASN.1 GeneralString byte value with optional universal tagging."""
|
||||
b_data = to_bytes(value, encoding=encoding)
|
||||
if tag:
|
||||
b_data = pack_asn1(TagClass.universal, False, TypeTagNumber.general_string, b_data)
|
||||
|
||||
return b_data
|
||||
|
||||
|
||||
def pack_asn1_integer(
|
||||
value: int,
|
||||
tag: bool = True,
|
||||
) -> bytes:
|
||||
"""Packs an int value into an ASN.1 INTEGER byte value with optional universal tagging."""
|
||||
# Thanks to https://github.com/andrivet/python-asn1 for help with the negative value logic.
|
||||
is_negative = False
|
||||
limit = 0x7F
|
||||
if value < 0:
|
||||
value = -value
|
||||
is_negative = True
|
||||
limit = 0x80
|
||||
|
||||
b_int = bytearray()
|
||||
while value > limit:
|
||||
val = value & 0xFF
|
||||
|
||||
if is_negative:
|
||||
val = 0xFF - val
|
||||
|
||||
b_int.append(val)
|
||||
value >>= 8
|
||||
|
||||
b_int.append(((0xFF - value) if is_negative else value) & 0xFF)
|
||||
|
||||
if is_negative:
|
||||
for idx, val in enumerate(b_int):
|
||||
if val < 0xFF:
|
||||
b_int[idx] += 1
|
||||
break
|
||||
|
||||
b_int[idx] = 0
|
||||
|
||||
if is_negative and b_int[-1] == 0x7F: # Two's complement corner case
|
||||
b_int.append(0xFF)
|
||||
|
||||
b_int.reverse()
|
||||
|
||||
b_value = bytes(b_int)
|
||||
if tag:
|
||||
b_value = pack_asn1(TagClass.universal, False, TypeTagNumber.integer, b_value)
|
||||
|
||||
return b_value
|
||||
|
||||
|
||||
def pack_asn1_object_identifier(
|
||||
oid: str,
|
||||
tag: bool = True,
|
||||
) -> bytes:
|
||||
"""Packs an str value into an ASN.1 OBJECT IDENTIFIER byte value with optional universal tagging."""
|
||||
b_oid = bytearray()
|
||||
oid_split = [int(i) for i in oid.split(".")]
|
||||
|
||||
if len(oid_split) < 2:
|
||||
raise ValueError("An OID must have 2 or more elements split by '.'")
|
||||
|
||||
# The first byte of the OID is the first 2 elements (x.y) as (x * 40) + y
|
||||
b_oid.append((oid_split[0] * 40) + oid_split[1])
|
||||
|
||||
for val in oid_split[2:]:
|
||||
b_oid.extend(_pack_asn1_octet_number(val))
|
||||
|
||||
b_value = bytes(b_oid)
|
||||
if tag:
|
||||
b_value = pack_asn1(TagClass.universal, False, TypeTagNumber.object_identifier, b_value)
|
||||
|
||||
return b_value
|
||||
|
||||
|
||||
def pack_asn1_octet_string(
|
||||
b_data: bytes,
|
||||
tag: bool = True,
|
||||
) -> bytes:
|
||||
"""Packs an bytes value into an ASN.1 OCTET STRING byte value with optional universal tagging."""
|
||||
if tag:
|
||||
b_data = pack_asn1(TagClass.universal, False, TypeTagNumber.octet_string, b_data)
|
||||
|
||||
return b_data
|
||||
|
||||
|
||||
def pack_asn1_sequence(
|
||||
sequence: typing.List[bytes],
|
||||
tag: bool = True,
|
||||
) -> bytes:
|
||||
"""Packs a list of encoded bytes into an ASN.1 SEQUENCE byte value with optional universal tagging."""
|
||||
b_data = b"".join(sequence)
|
||||
if tag:
|
||||
b_data = pack_asn1(TagClass.universal, True, TypeTagNumber.sequence, b_data)
|
||||
|
||||
return b_data
|
||||
|
||||
|
||||
def _pack_asn1_octet_number(num: int) -> bytes:
|
||||
"""Packs an int number into an ASN.1 integer value that spans multiple octets."""
|
||||
num_octets = bytearray()
|
||||
|
||||
while num:
|
||||
# Get the 7 bit value of the number.
|
||||
octet_value = num & 0b01111111
|
||||
|
||||
# Set the MSB if this isn't the first octet we are processing (overall last octet)
|
||||
if len(num_octets):
|
||||
octet_value |= 0b10000000
|
||||
|
||||
num_octets.append(octet_value)
|
||||
|
||||
# Shift the number by 7 bits as we've just processed them.
|
||||
num >>= 7
|
||||
|
||||
# Finally we reverse the order so the higher octets are first.
|
||||
num_octets.reverse()
|
||||
|
||||
return num_octets
|
||||
|
||||
|
||||
def unpack_asn1(b_data: bytes) -> typing.Tuple[ASN1Value, bytes]:
|
||||
"""Unpacks an ASN.1 TLV into each element.
|
||||
|
||||
Unpacks the raw ASN.1 value into a `ASN1Value` tuple and returns the remaining bytes that are not part of the
|
||||
ASN.1 TLV.
|
||||
|
||||
Args:
|
||||
b_data: The raw bytes to unpack as an ASN.1 TLV.
|
||||
|
||||
Returns:
|
||||
ASN1Value: The ASN.1 value that is unpacked from the raw bytes passed in.
|
||||
bytes: Any remaining bytes that are not part of the ASN1Value.
|
||||
"""
|
||||
octet1 = struct.unpack("B", b_data[:1])[0]
|
||||
tag_class = TagClass((octet1 & 0b11000000) >> 6)
|
||||
constructed = bool(octet1 & 0b00100000)
|
||||
tag_number = octet1 & 0b00011111
|
||||
|
||||
length_offset = 1
|
||||
if tag_number == 31:
|
||||
tag_number, octet_count = _unpack_asn1_octet_number(b_data[1:])
|
||||
length_offset += octet_count
|
||||
|
||||
if tag_class == TagClass.universal:
|
||||
tag_number = TypeTagNumber(tag_number)
|
||||
|
||||
b_data = b_data[length_offset:]
|
||||
|
||||
length = struct.unpack("B", b_data[:1])[0]
|
||||
length_octets = 1
|
||||
|
||||
if length & 0b10000000:
|
||||
# If the MSB is set then the length octet just contains the number of octets that encodes the actual length.
|
||||
length_octets += length & 0b01111111
|
||||
length = 0
|
||||
|
||||
for idx in range(1, length_octets):
|
||||
octet_val = struct.unpack("B", b_data[idx : idx + 1])[0]
|
||||
length += octet_val << (8 * (length_octets - 1 - idx))
|
||||
|
||||
value = ASN1Value(
|
||||
tag_class=tag_class,
|
||||
constructed=constructed,
|
||||
tag_number=tag_number,
|
||||
b_data=b_data[length_octets : length_octets + length],
|
||||
)
|
||||
|
||||
return value, b_data[length_octets + length :]
|
||||
|
||||
|
||||
def unpack_asn1_bit_string(value: typing.Union[ASN1Value, bytes]) -> bytes:
|
||||
"""Unpacks an ASN.1 BIT STRING value."""
|
||||
b_data = extract_asn1_tlv(value, TagClass.universal, TypeTagNumber.bit_string)
|
||||
|
||||
# First octet is the number of unused bits in the last octet from the LSB.
|
||||
unused_bits = struct.unpack("B", b_data[:1])[0]
|
||||
last_octet = struct.unpack("B", b_data[-2:-1])[0]
|
||||
last_octet = (last_octet >> unused_bits) << unused_bits
|
||||
|
||||
return b_data[1:-1] + struct.pack("B", last_octet)
|
||||
|
||||
|
||||
def unpack_asn1_boolean(value: typing.Union[ASN1Value, bytes]) -> bool:
|
||||
"""Unpacks an ASN.1 BOOLEAN value."""
|
||||
b_data = extract_asn1_tlv(value, TagClass.universal, TypeTagNumber.boolean)
|
||||
|
||||
return b_data != b"\x00"
|
||||
|
||||
|
||||
def unpack_asn1_enumerated(value: typing.Union[ASN1Value, bytes]) -> int:
|
||||
"""Unpacks an ASN.1 ENUMERATED value."""
|
||||
b_data = extract_asn1_tlv(value, TagClass.universal, TypeTagNumber.enumerated)
|
||||
|
||||
return unpack_asn1_integer(b_data)
|
||||
|
||||
|
||||
def unpack_asn1_general_string(value: typing.Union[ASN1Value, bytes]) -> bytes:
|
||||
"""Unpacks an ASN.1 GeneralString value."""
|
||||
return extract_asn1_tlv(value, TagClass.universal, TypeTagNumber.general_string)
|
||||
|
||||
|
||||
def unpack_asn1_generalized_time(value: typing.Union[ASN1Value, bytes]) -> datetime.datetime:
|
||||
"""Unpacks an ASN.1 GeneralizedTime value."""
|
||||
data = to_text(extract_asn1_tlv(value, TagClass.universal, TypeTagNumber.generalized_time))
|
||||
|
||||
# While ASN.1 can have a timezone encoded, KerberosTime is the only thing we use and it is always in UTC with the
|
||||
# Z prefix. We strip out the Z because Python 2 doesn't support the %z identifier and add the UTC tz to the object.
|
||||
# https://www.rfc-editor.org/rfc/rfc4120#section-5.2.3
|
||||
if data.endswith("Z"):
|
||||
data = data[:-1]
|
||||
|
||||
err = None
|
||||
for datetime_format in ["%Y%m%d%H%M%S.%f", "%Y%m%d%H%M%S"]:
|
||||
try:
|
||||
dt = datetime.datetime.strptime(data, datetime_format)
|
||||
return dt.replace(tzinfo=datetime.timezone.utc)
|
||||
except ValueError as e:
|
||||
err = e
|
||||
|
||||
else:
|
||||
raise err # type: ignore
|
||||
|
||||
|
||||
def unpack_asn1_integer(value: typing.Union[ASN1Value, bytes]) -> int:
|
||||
"""Unpacks an ASN.1 INTEGER value."""
|
||||
b_int = bytearray(extract_asn1_tlv(value, TagClass.universal, TypeTagNumber.integer))
|
||||
|
||||
is_negative = b_int[0] & 0b10000000
|
||||
if is_negative:
|
||||
# Get the two's compliment.
|
||||
for i in range(len(b_int)):
|
||||
b_int[i] = 0xFF - b_int[i]
|
||||
|
||||
for i in range(len(b_int) - 1, -1, -1):
|
||||
if b_int[i] == 0xFF:
|
||||
b_int[i - 1] += 1
|
||||
b_int[i] = 0
|
||||
break
|
||||
|
||||
else:
|
||||
b_int[i] += 1
|
||||
break
|
||||
|
||||
int_value = 0
|
||||
for val in b_int:
|
||||
int_value = (int_value << 8) | val
|
||||
|
||||
if is_negative:
|
||||
int_value *= -1
|
||||
|
||||
return int_value
|
||||
|
||||
|
||||
def unpack_asn1_object_identifier(value: typing.Union[ASN1Value, bytes]) -> str:
|
||||
"""Unpacks an ASN.1 OBJECT IDENTIFIER value."""
|
||||
b_data = extract_asn1_tlv(value, TagClass.universal, TypeTagNumber.object_identifier)
|
||||
|
||||
first_element = struct.unpack("B", b_data[:1])[0]
|
||||
second_element = first_element % 40
|
||||
ids = [(first_element - second_element) // 40, second_element]
|
||||
|
||||
idx = 1
|
||||
while idx != len(b_data):
|
||||
oid, octet_len = _unpack_asn1_octet_number(b_data[idx:])
|
||||
ids.append(oid)
|
||||
idx += octet_len
|
||||
|
||||
return ".".join([str(i) for i in ids])
|
||||
|
||||
|
||||
def unpack_asn1_octet_string(value: typing.Union[ASN1Value, bytes]) -> bytes:
|
||||
"""Unpacks an ASN.1 OCTET STRING value."""
|
||||
return extract_asn1_tlv(value, TagClass.universal, TypeTagNumber.octet_string)
|
||||
|
||||
|
||||
def unpack_asn1_sequence(value: typing.Union[ASN1Value, bytes]) -> typing.List[ASN1Value]:
|
||||
"""Unpacks an ASN.1 SEQUENCE value."""
|
||||
b_data = extract_asn1_tlv(value, TagClass.universal, TypeTagNumber.sequence)
|
||||
|
||||
values = []
|
||||
while b_data:
|
||||
v, b_data = unpack_asn1(b_data)
|
||||
values.append(v)
|
||||
|
||||
return values
|
||||
|
||||
|
||||
def unpack_asn1_tagged_sequence(value: typing.Union[ASN1Value, bytes]) -> typing.Dict[int, ASN1Value]:
|
||||
"""Unpacks an ASN.1 SEQUENCE value as a dictionary."""
|
||||
return dict([(e.tag_number, unpack_asn1(e.b_data)[0]) for e in unpack_asn1_sequence(value)])
|
||||
|
||||
|
||||
def _unpack_asn1_octet_number(b_data: bytes) -> typing.Tuple[int, int]:
|
||||
"""Unpacks an ASN.1 INTEGER value that can span across multiple octets."""
|
||||
i = 0
|
||||
idx = 0
|
||||
while True:
|
||||
element = struct.unpack("B", b_data[idx : idx + 1])[0]
|
||||
idx += 1
|
||||
|
||||
i = (i << 7) + (element & 0b01111111)
|
||||
if not element & 0b10000000:
|
||||
break
|
||||
|
||||
return i, idx # int value and the number of octets used.
|
||||
840
env/lib/python3.12/site-packages/spnego/_context.py
vendored
Normal file
840
env/lib/python3.12/site-packages/spnego/_context.py
vendored
Normal file
@@ -0,0 +1,840 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import abc
|
||||
import dataclasses
|
||||
import enum
|
||||
import typing
|
||||
import warnings
|
||||
|
||||
from spnego._credential import Credential
|
||||
from spnego._text import to_text
|
||||
from spnego.channel_bindings import GssChannelBindings
|
||||
from spnego.exceptions import FeatureMissingError, NegotiateOptions, SpnegoError
|
||||
from spnego.iov import BufferType, IOVBuffer, IOVResBuffer
|
||||
|
||||
F = typing.TypeVar("F", bound=typing.Callable[..., typing.Any])
|
||||
NativeIOV = typing.TypeVar("NativeIOV", bound=typing.Any)
|
||||
IOV = typing.Union[
|
||||
IOVBuffer,
|
||||
IOVResBuffer,
|
||||
typing.Tuple[typing.Union[BufferType, int], typing.Union[bool, bytes, int]],
|
||||
typing.Union[BufferType, int],
|
||||
bytes,
|
||||
]
|
||||
|
||||
|
||||
def split_username(username: typing.Optional[str]) -> typing.Tuple[typing.Optional[str], typing.Optional[str]]:
|
||||
"""Splits a username and returns the domain component.
|
||||
|
||||
Will split a username in the Netlogon form `DOMAIN\\username` and return the domain and user part as separate
|
||||
strings. If the user does not contain the `DOMAIN\\` prefix or is in the `UPN` form then then user stays the same
|
||||
and the domain is an empty string.
|
||||
|
||||
Args:
|
||||
username: The username to split
|
||||
|
||||
Returns:
|
||||
Tuple[Optional[str], Optional[str]]: The domain and username.
|
||||
"""
|
||||
if username is None:
|
||||
return None, None
|
||||
|
||||
domain: typing.Optional[str]
|
||||
if "\\" in username:
|
||||
domain, username = username.split("\\", 1)
|
||||
else:
|
||||
domain = None
|
||||
|
||||
return to_text(domain, nonstring="passthru"), to_text(username, nonstring="passthru")
|
||||
|
||||
|
||||
def wrap_system_error(error_type: typing.Type, context: typing.Optional[str] = None) -> typing.Callable[[F], F]:
|
||||
"""Wraps a function that makes a native GSSAPI/SSPI syscall and convert native exceptions to a SpnegoError.
|
||||
|
||||
Wraps a function that can potentially raise a WindowsError or GSSError and converts it to the common SpnegoError
|
||||
that is exposed by this library. This is to ensure the context proxy functions raise a common set of errors rather
|
||||
than a specific error for the provider. The underlying error is preserved in the SpnegoError if the user wishes to
|
||||
inspect that.
|
||||
|
||||
Args:
|
||||
error_type: The native error type that need to be wrapped.
|
||||
context: An optional context message to add to the error if raised.
|
||||
"""
|
||||
|
||||
def decorator(func: F) -> F:
|
||||
def wrapper(*args: typing.Any, **kwargs: typing.Any) -> F:
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
|
||||
except error_type as native_err:
|
||||
raise SpnegoError(base_error=native_err, context_msg=context) from native_err
|
||||
|
||||
return typing.cast(F, wrapper)
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
class WrapResult(typing.NamedTuple):
|
||||
"""Result of the `wrap()` function."""
|
||||
|
||||
data: bytes #: The bytes of the wrapped data.
|
||||
encrypted: bool #: Whether the data was encrypted (True) or not (False).
|
||||
|
||||
|
||||
class IOVWrapResult(typing.NamedTuple):
|
||||
"""Result of the `wrap_iov()` function."""
|
||||
|
||||
buffers: typing.Tuple[IOVResBuffer, ...] #: The wrapped IOV buffers.
|
||||
encrypted: bool #: Whether the buffer data was encrypted (True) or not (False).
|
||||
|
||||
|
||||
class WinRMWrapResult(typing.NamedTuple):
|
||||
"""Result of the `wrap_winrm()` function."""
|
||||
|
||||
header: bytes #: The header of the wrapped result.
|
||||
data: bytes #: The wrapped data included any padding.
|
||||
padding_length: int #: The length of the bytes added to the data for padding.
|
||||
|
||||
|
||||
class UnwrapResult(typing.NamedTuple):
|
||||
"""Result of the `unwrap()` function."""
|
||||
|
||||
data: bytes #: The bytes of the unwrapped data.
|
||||
encrypted: bool #: Whether the input data was encrypted (True) or not (False)
|
||||
qop: int #: The Quality of Protection used for the encrypted data.
|
||||
|
||||
|
||||
class IOVUnwrapResult(typing.NamedTuple):
|
||||
"""Result of the `unwrap_iov()` function."""
|
||||
|
||||
buffers: typing.Tuple[IOVResBuffer, ...] #: The unwrapped IOV buffers.
|
||||
encrypted: bool #: Whether the input buffers were encrypted (True) or not (False)
|
||||
qop: int #: The Quality of Protection used for the encrypted buffers.
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class SecPkgContextSizes:
|
||||
"""Sizes of important structures used for messages.
|
||||
|
||||
This dataclass exposes the sizes of important structures used in message
|
||||
support functions like wrap, wrap_iov, sign, etc. Use
|
||||
:meth:`ContextReq.query_message_sizes` to retrieve this value for an
|
||||
authenticated context.
|
||||
|
||||
Currently only ``header`` is exposed but other sizes may be added in the
|
||||
future if needed.
|
||||
|
||||
Attributes:
|
||||
header: The size of the header/signature of a wrapped token. This
|
||||
corresponds to cbSecurityTrailer in SecPkgContext_Sizes in SSPI and
|
||||
the size of the allocated GSS_IOV_BUFFER_TYPE_HEADER IOV buffer.
|
||||
"""
|
||||
|
||||
header: int
|
||||
|
||||
|
||||
class ContextReq(enum.IntFlag):
|
||||
none = 0x00000000
|
||||
|
||||
# GSSAPI|SSPI flags
|
||||
delegate = 0x00000001
|
||||
mutual_auth = 0x00000002
|
||||
replay_detect = 0x00000004
|
||||
sequence_detect = 0x00000008
|
||||
confidentiality = 0x00000010
|
||||
integrity = 0x00000020
|
||||
# anonymous = 0x00000040 # TODO: Add support for anonymous auth.
|
||||
dce_style = 0x00001000
|
||||
identify = 0x00002000
|
||||
# Requires newer python-gssapi version to support https://github.com/pythongssapi/python-gssapi/pull/218
|
||||
delegate_policy = 0x00080000
|
||||
|
||||
# Special flag that disables integrity/confidentiality on Kerberos/Negotiate
|
||||
# This should not be set with integrity or confidentiality.
|
||||
no_integrity = 0x10000000
|
||||
|
||||
# mutual_auth | replay_detect | sequence_detect | confidentiality | integrity
|
||||
default = 0x00000002 | 0x00000004 | 0x00000008 | 0x00000010 | 0x00000020
|
||||
|
||||
|
||||
class GSSMech(str, enum.Enum):
|
||||
ntlm = "1.3.6.1.4.1.311.2.2.10"
|
||||
spnego = "1.3.6.1.5.5.2"
|
||||
|
||||
# Kerberos has been put under several OIDs over time, we should only be using 'kerberos'.
|
||||
kerberos = "1.2.840.113554.1.2.2" # The actual Kerberos OID, this should be the one used.
|
||||
_ms_kerberos = "1.2.840.48018.1.2.2"
|
||||
_kerberos_draft = "1.3.5.1.5.2"
|
||||
_iakerb = "1.3.6.1.5.2"
|
||||
|
||||
# Not implemented.
|
||||
kerberos_u2u = "1.2.840.113554.1.2.2.3"
|
||||
negoex = "1.3.6.1.4.1.311.2.2.30"
|
||||
|
||||
@classmethod
|
||||
def native_labels(cls) -> typing.Dict[str, str]:
|
||||
return {
|
||||
GSSMech.ntlm: "NTLM",
|
||||
GSSMech.ntlm.value: "NTLM",
|
||||
GSSMech.spnego: "SPNEGO",
|
||||
GSSMech.spnego.value: "SPNEGO",
|
||||
GSSMech.kerberos: "Kerberos",
|
||||
GSSMech.kerberos.value: "Kerberos",
|
||||
GSSMech._ms_kerberos: "MS Kerberos",
|
||||
GSSMech._ms_kerberos.value: "MS Kerberos",
|
||||
GSSMech._kerberos_draft: "Kerberos (draft)",
|
||||
GSSMech._kerberos_draft.value: "Kerberos (draft)",
|
||||
GSSMech._iakerb: "IAKerberos",
|
||||
GSSMech._iakerb.value: "IAKerberos",
|
||||
GSSMech.kerberos_u2u: "Kerberos User to User",
|
||||
GSSMech.kerberos_u2u.value: "Kerberos User to User",
|
||||
GSSMech.negoex: "NEGOEX",
|
||||
GSSMech.negoex.value: "NEGOEX",
|
||||
}
|
||||
|
||||
@property
|
||||
def common_name(self) -> str:
|
||||
if self.is_kerberos_oid:
|
||||
return "kerberos"
|
||||
|
||||
return self.name
|
||||
|
||||
@property
|
||||
def is_kerberos_oid(self) -> bool:
|
||||
"""Determines if the mech is a Kerberos mech.
|
||||
|
||||
Kerberos has been known under serveral OIDs in the past. This tells the caller whether the OID is one of those
|
||||
"known" OIDs.
|
||||
|
||||
Returns:
|
||||
bool: Whether the mech is a Kerberos mech (True) or not (False).
|
||||
"""
|
||||
return self in [GSSMech.kerberos, GSSMech._ms_kerberos, GSSMech._kerberos_draft, GSSMech._iakerb]
|
||||
|
||||
@staticmethod
|
||||
def from_oid(oid: str) -> "GSSMech":
|
||||
"""Converts an OID string to a GSSMech value.
|
||||
|
||||
Converts an OID string to a GSSMech value if it is known.
|
||||
|
||||
Args:
|
||||
oid: The OID as a string to convert from.
|
||||
|
||||
Raises:
|
||||
ValueError: if the OID is not a known GSSMech.
|
||||
"""
|
||||
for mech in GSSMech:
|
||||
if mech.value == oid:
|
||||
return mech
|
||||
else:
|
||||
raise ValueError("'%s' is not a valid GSSMech OID" % oid)
|
||||
|
||||
|
||||
class ContextProxy(metaclass=abc.ABCMeta):
|
||||
"""Base class for a authentication context.
|
||||
|
||||
A base class the defined a common entry point for the various authentication context's that are used in this
|
||||
library. For a new context to be added it must implement the abstract functions in this class and translate the
|
||||
calls to what is required internally.
|
||||
|
||||
Args:
|
||||
credentials: A list of credentials to use for authentication.
|
||||
hostname: The principal part of the SPN. This is required for Kerberos auth to build the SPN.
|
||||
service: The service part of the SPN. This is required for Kerberos auth to build the SPN.
|
||||
channel_bindings: The optional :class:`spnego.channel_bindings.GssChannelBindings` for the context.
|
||||
context_req: The :class:`spnego.ContextReq` flags to use when setting up the context.
|
||||
usage: The usage of the context, `initiate` for a client and `accept` for a server.
|
||||
protocol: The protocol to authenticate with, can be `ntlm`, `kerberos`, or `negotiate`. Not all providers
|
||||
support all three protocols as that is handled by :class:`SPNEGOContext`.
|
||||
options: The :class:`spnego.NegotiateOptions` that define pyspnego specific options to control the negotiation.
|
||||
|
||||
Attributes:
|
||||
usage (str): The usage of the context, `initiate` for a client and `accept` for a server.
|
||||
protocol (str): The protocol to set the context up with; `ntlm`, `kerberos`, or `negotiate`.
|
||||
spn (str): The service principal name of the service to connect to.
|
||||
channel_bindings (spnego.channel_bindings.GssChannelBindings): Optional channel bindings to provide with the
|
||||
context.
|
||||
options (NegotiateOptions): The user specified negotiation options.
|
||||
context_req (ContextReq): The context requirements flags as an int value specific to the context provider.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
credentials: typing.List[Credential],
|
||||
hostname: typing.Optional[str],
|
||||
service: typing.Optional[str],
|
||||
channel_bindings: typing.Optional[GssChannelBindings],
|
||||
context_req: ContextReq,
|
||||
usage: str,
|
||||
protocol: str,
|
||||
options: NegotiateOptions,
|
||||
) -> None:
|
||||
self.usage = usage.lower()
|
||||
if self.usage not in ["initiate", "accept"]:
|
||||
raise ValueError("Invalid usage '%s', must be initiate or accept" % self.usage)
|
||||
|
||||
self.protocol = protocol.lower()
|
||||
if self.protocol not in ["ntlm", "kerberos", "negotiate", "credssp"]:
|
||||
raise ValueError("Invalid protocol '%s', must be ntlm, kerberos, negotiate, or credssp" % self.protocol)
|
||||
|
||||
if self.protocol not in self.available_protocols(options=options):
|
||||
raise ValueError("Protocol %s is not available" % self.protocol)
|
||||
|
||||
self._hostname = hostname
|
||||
self._service = service
|
||||
self.spn = None
|
||||
if service or hostname:
|
||||
self.spn = to_text("%s/%s" % (service if service else "HOST", hostname or "unspecified"))
|
||||
|
||||
self.channel_bindings = channel_bindings
|
||||
self.options = NegotiateOptions(options)
|
||||
|
||||
self.context_req = context_req # Generic context requirements.
|
||||
self._context_req = 0 # Provider specific context requirements.
|
||||
for generic, provider in self._context_attr_map:
|
||||
if context_req & generic:
|
||||
self._context_req |= provider
|
||||
|
||||
self._context_attr = 0 # Provider specific context attributes, set by self.step().
|
||||
|
||||
# Whether the context is wrapped inside another context - set by NegotiateProxy.
|
||||
self._is_wrapped = False
|
||||
|
||||
if options & NegotiateOptions.wrapping_iov and not self.iov_available():
|
||||
raise FeatureMissingError(NegotiateOptions.wrapping_iov)
|
||||
|
||||
@property
|
||||
def username(self) -> None:
|
||||
warnings.warn("username is deprecated", category=DeprecationWarning)
|
||||
return None
|
||||
|
||||
@property
|
||||
def password(self) -> None:
|
||||
warnings.warn("password is deprecated", category=DeprecationWarning)
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def available_protocols(cls, options: typing.Optional[NegotiateOptions] = None) -> typing.List[str]:
|
||||
"""A list of protocols that the provider can offer.
|
||||
|
||||
Returns a list of protocols the underlying provider can implement. Currently only kerberos, negotiate, or ntlm
|
||||
is understood. The protocols that are available for each proxy context depend on the OS platform and what
|
||||
libraries are installed. See each proxy's `available_protocols` function for more info.
|
||||
|
||||
Args:
|
||||
options: The context requirements of :class:`NegotiationOptions` that state what the client requires.
|
||||
|
||||
Returns:
|
||||
List[str]: The list of protocols that the context can use.
|
||||
"""
|
||||
return ["kerberos", "negotiate", "ntlm"] # pragma: no cover
|
||||
|
||||
@classmethod
|
||||
def iov_available(cls) -> bool:
|
||||
"""Whether the context supports IOV wrapping and unwrapping.
|
||||
|
||||
Will return a bool that states whether the context supports IOV wrapping or unwrapping. The NTLM protocol on
|
||||
Linux does not support IOV and some Linux gssapi implementations do not expose the extension headers for this
|
||||
function. This gives the caller a sane way to determine whether it can use :meth:`wrap_iov` or
|
||||
:meth:`unwrap_iov`.
|
||||
|
||||
Returns:
|
||||
bool: Whether the context provider supports IOV wrapping and unwrapping (True) or not (False).
|
||||
"""
|
||||
return True # pragma: no cover
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def client_principal(self) -> typing.Optional[str]:
|
||||
"""The principal that was used authenticated by the acceptor.
|
||||
|
||||
The name of the client principal that was used in the authentication context. This is `None` when
|
||||
`usage='initiate'` or the context has not been completed. The format of the principal name is dependent on the
|
||||
protocol and underlying library that was used to complete the authentication.
|
||||
|
||||
Returns:
|
||||
Optional[str]: The client principal name.
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def complete(self) -> bool:
|
||||
"""Whether the context has completed the authentication process.
|
||||
|
||||
Will return a bool that states whether the authentication process has completed successfully.
|
||||
|
||||
Returns:
|
||||
bool: The authentication process is complete (True) or not (False).
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
@property
|
||||
def context_attr(self) -> ContextReq:
|
||||
"""The context attributes that were negotiated.
|
||||
|
||||
This is the context attributes that were negotiated with the counterpart server. These attributes are only
|
||||
valid once the context is fully established.
|
||||
|
||||
Returns:
|
||||
ContextReq: The flags that were negotiated.
|
||||
"""
|
||||
attr = 0
|
||||
for generic, provider in self._context_attr_map:
|
||||
if self._context_attr & provider:
|
||||
attr |= generic
|
||||
|
||||
return ContextReq(attr)
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def negotiated_protocol(self) -> typing.Optional[str]:
|
||||
"""The name of the negotiated protocol.
|
||||
|
||||
Once the authentication process has compeleted this will return the name of the negotiated context that was
|
||||
used. For pure NTLM and Kerberos this will always be `ntlm` or `kerberos` respectively but for SPNEGO this can
|
||||
be either of those two.
|
||||
|
||||
Returns:
|
||||
Optional[str]: The protocol that was negotiated, can be `ntlm`, `kerberos`, or `negotiate. Will be `None`
|
||||
for the acceptor until it receives the first token from the initiator. Once the context is establish
|
||||
`negotiate` will change to either `ntlm` or `kerberos` to reflect the protocol that was used by SPNEGO.
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def session_key(self) -> bytes:
|
||||
"""The derived session key.
|
||||
|
||||
Once the authentication process is complete, this will return the derived session key. It is recommended to not
|
||||
use this key for your own encryption processes and is only exposed because some libraries use this key in their
|
||||
protocols.
|
||||
|
||||
Returns:
|
||||
bytes: The derived session key from the authenticated context.
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
@abc.abstractmethod
|
||||
def new_context(self) -> "ContextProxy":
|
||||
"""Creates a new security context.
|
||||
|
||||
Creates a new security context based on the current credential and
|
||||
options of the current context. This is useful when needing to set up a
|
||||
new security context without having to retrieve the credentials again.
|
||||
|
||||
Returns:
|
||||
ContextProxy: The new security context.
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
@abc.abstractmethod
|
||||
def query_message_sizes(self) -> SecPkgContextSizes:
|
||||
"""Gets the important structure sizes for message functions.
|
||||
|
||||
Will get the important sizes for the various message functions used by
|
||||
the current authentication context. This must only be called once the
|
||||
context has been authenticated.
|
||||
|
||||
Returns:
|
||||
SecPkgContextSizes: The sizes for the current context.
|
||||
|
||||
Raises:
|
||||
NoContextError: The security context is not ready to be queried.
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
@abc.abstractmethod
|
||||
def step(
|
||||
self,
|
||||
in_token: typing.Optional[bytes] = None,
|
||||
*,
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
) -> typing.Optional[bytes]:
|
||||
"""Performs a negotiation step.
|
||||
|
||||
This method performs a negotiation step and processes/generates a token. This token should be then sent to the
|
||||
counterpart context to continue the authentication process.
|
||||
|
||||
This should not be called once :meth:`complete` is True as the security context is complete.
|
||||
|
||||
For the initiator this is equivalent to `gss_init_sec_context`_ for GSSAPI and `InitializeSecurityContext`_ for
|
||||
SSPI.
|
||||
|
||||
For the acceptor this is equivalent to `gss_accept_sec_context`_ for GSSAPI and `AcceptSecurityContext`_ for
|
||||
SSPI.
|
||||
|
||||
Args:
|
||||
in_token: The input token to process (or None to process no input token).
|
||||
channel_bindings: Optional channel bindings ot use in this step. Will take priority over channel bindings
|
||||
set in the context if both are specified.
|
||||
|
||||
Returns:
|
||||
Optional[bytes]: The output token (or None if no output token is generated.
|
||||
|
||||
.. _gss_init_sec_context:
|
||||
https://tools.ietf.org/html/rfc2744.html#section-5.19
|
||||
|
||||
.. _InitializeSecurityContext:
|
||||
https://docs.microsoft.com/en-us/windows/win32/api/sspi/nf-sspi-initializesecuritycontextw
|
||||
|
||||
.. _gss_accept_sec_context:
|
||||
https://tools.ietf.org/html/rfc2744.html#section-5.1
|
||||
|
||||
.. _AcceptSecurityContext:
|
||||
https://docs.microsoft.com/en-us/windows/win32/api/sspi/nf-sspi-acceptsecuritycontext
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
@abc.abstractmethod
|
||||
def wrap(self, data: bytes, encrypt: bool = True, qop: typing.Optional[int] = None) -> WrapResult:
|
||||
"""Wrap a message, optionally with encryption.
|
||||
|
||||
This wraps a message, signing it and optionally encrypting it. The :meth:`unwrap` will unwrap a message.
|
||||
|
||||
This is the equivalent to `gss_wrap`_ for GSSAPI and `EncryptMessage`_ for SSPI.
|
||||
|
||||
The SSPI function's `EncryptMessage`_ is called with the following buffers::
|
||||
|
||||
SecBufferDesc(SECBUFFER_VERSION, [
|
||||
SecBuffer(SECBUFFER_TOKEN, sizes.cbSecurityTrailer, b""),
|
||||
SecBuffer(SECBUFFER_DATA, len(data), data),
|
||||
SecBuffer(SECBUFFER_PADDING, sizes.cbBlockSize, b""),
|
||||
])
|
||||
|
||||
Args:
|
||||
data: The data to wrap.
|
||||
encrypt: Whether to encrypt the data (True) or just wrap it with a MIC (False).
|
||||
qop: The desired Quality of Protection (or None to use the default).
|
||||
|
||||
Returns:
|
||||
WrapResult: The wrapped result which contains the wrapped message and whether it was encrypted or not.
|
||||
|
||||
.. _gss_wrap:
|
||||
https://tools.ietf.org/html/rfc2744.html#section-5.33
|
||||
|
||||
.. _EncryptMessage:
|
||||
https://docs.microsoft.com/en-us/windows/win32/secauthn/encryptmessage--general
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
@abc.abstractmethod
|
||||
def wrap_iov(
|
||||
self,
|
||||
iov: typing.Iterable[IOV],
|
||||
encrypt: bool = True,
|
||||
qop: typing.Optional[int] = None,
|
||||
) -> IOVWrapResult:
|
||||
"""Wrap/Encrypt an IOV buffer.
|
||||
|
||||
This method wraps/encrypts an IOV buffer. The IOV buffers control how the data is to be processed. Because
|
||||
IOV wrapping is an extension to GSSAPI and not implemented for NTLM on Linux, this method may not always be
|
||||
available to the caller. Check the :meth:`iov_available` property.
|
||||
|
||||
This is the equivalent to `gss_wrap_iov`_ for GSSAPI and `EncryptMessage`_ for SSPI.
|
||||
|
||||
Args:
|
||||
iov: A list of :class:`spnego.iov.IOVBuffer` buffers to wrap.
|
||||
encrypt: Whether to encrypt the message (True) or just wrap it with a MIC (False).
|
||||
qop: The desired Quality of Protection (or None to use the default).
|
||||
|
||||
Returns:
|
||||
IOVWrapResult: The wrapped result which contains the wrapped IOVBuffer bytes and whether it was encrypted
|
||||
or not.
|
||||
|
||||
.. _gss_wrap_iov:
|
||||
http://k5wiki.kerberos.org/wiki/Projects/GSSAPI_DCE
|
||||
|
||||
.. _EncryptMessage:
|
||||
https://docs.microsoft.com/en-us/windows/win32/secauthn/encryptmessage--general
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
@abc.abstractmethod
|
||||
def wrap_winrm(self, data: bytes) -> WinRMWrapResult:
|
||||
"""Wrap/Encrypt data for use with WinRM.
|
||||
|
||||
This method wraps/encrypts bytes for use with WinRM message encryption.
|
||||
|
||||
Args:
|
||||
data: The data to wrap.
|
||||
|
||||
Returns:
|
||||
WinRMWrapResult: The wrapped result for use with WinRM message encryption.
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
@abc.abstractmethod
|
||||
def unwrap(self, data: bytes) -> UnwrapResult:
|
||||
"""Unwrap a message.
|
||||
|
||||
This unwraps a message created by :meth:`wrap`.
|
||||
|
||||
This is the equivalent to `gss_unwrap`_ for GSSAPI and `DecryptMessage`_ for SSPI.
|
||||
|
||||
The SSPI function's `DecryptMessage`_ is called with the following buffers::
|
||||
|
||||
SecBufferDesc(SECBUFFER_VERSION, [
|
||||
SecBuffer(SECBUFFER_STREAM, len(data), data),
|
||||
SecBuffer(SECBUFFER_DATA, 0, b""),
|
||||
])
|
||||
|
||||
Args:
|
||||
data: The data to unwrap.
|
||||
|
||||
Returns:
|
||||
UnwrapResult: The unwrapped message, whether it was encrypted, and the QoP used.
|
||||
|
||||
.. _gss_unwrap:
|
||||
https://tools.ietf.org/html/rfc2744.html#section-5.31
|
||||
|
||||
.. _DecryptMessage:
|
||||
https://docs.microsoft.com/en-us/windows/win32/secauthn/decryptmessage--general
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
@abc.abstractmethod
|
||||
def unwrap_iov(
|
||||
self,
|
||||
iov: typing.Iterable[IOV],
|
||||
) -> IOVUnwrapResult:
|
||||
"""Unwrap/Decrypt an IOV buffer.
|
||||
|
||||
This method unwraps/decrypts an IOV buffer. The IOV buffers control how the data is to be processed. Because
|
||||
IOV wrapping is an extension to GSSAPI and not implemented for NTLM on Linux, this method may not always be
|
||||
available to the caller. Check the :meth:`iov_available` property.
|
||||
|
||||
This is the equivalent to `gss_unwrap_iov`_ for GSSAPI and `DecryptMessage`_ for SSPI.
|
||||
|
||||
Args:
|
||||
iov: A list of :class:`spnego.iov.IOVBuffer` buffers to unwrap.
|
||||
|
||||
Returns:
|
||||
IOVUnwrapResult: The unwrapped buffer bytes, whether it was encrypted, and the QoP used.
|
||||
|
||||
.. _gss_unwrap_iov:
|
||||
http://k5wiki.kerberos.org/wiki/Projects/GSSAPI_DCE
|
||||
|
||||
.. _DecryptMessage:
|
||||
https://docs.microsoft.com/en-us/windows/win32/secauthn/decryptmessage--general
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
@abc.abstractmethod
|
||||
def unwrap_winrm(self, header: bytes, data: bytes) -> bytes:
|
||||
"""Unwrap/Decrypt a WinRM message.
|
||||
|
||||
This method unwraps/decrypts a WinRM message. It handles the complexities of unwrapping the data and dealing
|
||||
with the various system library calls.
|
||||
|
||||
Args:
|
||||
header: The header portion of the WinRM wrapped result.
|
||||
data: The data portion of the WinRM wrapped result.
|
||||
|
||||
Returns:
|
||||
bytes: The unwrapped message.
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
@abc.abstractmethod
|
||||
def sign(self, data: bytes, qop: typing.Optional[int] = None) -> bytes:
|
||||
"""Generates a signature/MIC for a message.
|
||||
|
||||
This method generates a MIC for the given data. This is unlike wrap which bundles the MIC and the message
|
||||
together. The :meth:`verify` method can be used to verify a MIC.
|
||||
|
||||
This is the equivalent to `gss_get_mic`_ for GSSAPI and `MakeSignature`_ for SSPI.
|
||||
|
||||
Args:
|
||||
data: The data to generate the MIC for.
|
||||
qop: The desired Quality of Protection (or None to use the default).
|
||||
|
||||
Returns:
|
||||
bytes: The MIC for the data requested.
|
||||
|
||||
.. _gss_get_mic:
|
||||
https://tools.ietf.org/html/rfc2744.html#section-5.15
|
||||
|
||||
.. _MakeSignature:
|
||||
https://docs.microsoft.com/en-us/windows/win32/api/sspi/nf-sspi-makesignature
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
@abc.abstractmethod
|
||||
def verify(self, data: bytes, mic: bytes) -> int:
|
||||
"""Verify the signature/MIC for a message.
|
||||
|
||||
Will verify that the given MIC matches the given data. If the MIC does not match the given data, an exception
|
||||
will be raised. The :meth:`sign` method can be used to sign data.
|
||||
|
||||
This is the equivalent to `gss_verify_mic`_ for GSSAPI and `VerifySignature`_ for SSPI.
|
||||
|
||||
Args:
|
||||
data: The data to verify against the MIC.
|
||||
mic: The MIC to verify against the data.
|
||||
|
||||
Returns:
|
||||
int: The QoP (Quality of Protection) used.
|
||||
|
||||
.. _gss_verify_mic:
|
||||
https://tools.ietf.org/html/rfc2744.html#section-5.32
|
||||
|
||||
.. _VerifySignature:
|
||||
https://docs.microsoft.com/en-us/windows/win32/api/sspi/nf-sspi-verifysignature
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
# Internal properties/functions not for public use.
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def _context_attr_map(self) -> typing.List[typing.Tuple[ContextReq, int]]:
|
||||
"""Map the generic ContextReq into the provider specific flags.
|
||||
|
||||
Will return a list of tuples that give the provider specific flag value for the generic ContextReq that is
|
||||
exposed to end users.
|
||||
|
||||
Returns:
|
||||
List[Tuple[ContextReq, int], ...]: A list of tuples where tuple[0] is the ContextReq flag and tuple[1] is
|
||||
the relevant provider specific flag for our common one.
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
|
||||
def get_extra_info(
|
||||
self,
|
||||
name: str,
|
||||
default: typing.Any = None,
|
||||
) -> typing.Any:
|
||||
"""Return information about the security context.
|
||||
|
||||
Returns extra information about the security context that is not defined
|
||||
as part of the standard :class:`ContextProxy` attributes or properties.
|
||||
By default there is no context specific information and it's up to the
|
||||
sub classes to implement their own.
|
||||
|
||||
These names can be queried for a CredSSP context.
|
||||
|
||||
client_credential:
|
||||
Used on an `acceptor` CredSSP context and contains the delegated
|
||||
credential sent by the client to the server. This is only
|
||||
available once the context is complete otherwise the default
|
||||
value is returned. The types returned can be
|
||||
:class:`TSPasswordCreds`, :class:`TSSmartCardCreds`, or
|
||||
:class:`TSRemoteGuardCreds`.
|
||||
|
||||
sslcontext:
|
||||
The :class:`ssl.SSLContext` instance used for the CredSSP
|
||||
context.
|
||||
|
||||
ssl_object:
|
||||
The :class:`ssl.SSLObject` instance used for the CredSSP
|
||||
context.
|
||||
|
||||
auth_stage - added in 0.5.0:
|
||||
A string representing that sub authentication stage being
|
||||
performed in the CredSSP authentication stepping. The value
|
||||
here is meant to be a human friendly representation and not
|
||||
something to be relied upon.
|
||||
|
||||
protocol_version - added in 0.5.0:
|
||||
The CredSSP protocol version that was negotiated between the
|
||||
initiator and acceptor. This is the minimum version number
|
||||
offered by both parties once the Negotiate authentication stage
|
||||
is complete.
|
||||
|
||||
Args:
|
||||
name: The name/id of the information to retrieve.
|
||||
default: The default value to return if the information is not
|
||||
available on the current context proxy.
|
||||
|
||||
Args:
|
||||
name: The name/id of the information to retrieve.
|
||||
default: The default value to return if the information is not
|
||||
available on the current context proxy.
|
||||
|
||||
Returns:
|
||||
The information requested or the default value specified if the
|
||||
information isn't found.
|
||||
"""
|
||||
return default
|
||||
|
||||
@property
|
||||
def _requires_mech_list_mic(self) -> bool:
|
||||
"""Determine if the SPNEGO mechListMIC is required for the sec context.
|
||||
|
||||
When Microsoft hosts deal with NTLM through SPNEGO it always wants the mechListMIC to be present when the NTLM
|
||||
authentication message contains a MIC. This goes against RFC 4178 as a mechListMIC shouldn't be required if
|
||||
NTLM was the preferred mech from the initiator but we can't do anything about that now. Because we exclusively
|
||||
use SSPI on Windows hosts, which does all the work for us, this function only matter for Linux hosts when this
|
||||
library manually creates the SPNEGO token.
|
||||
|
||||
The function performs 2 operations. When called before the NTLM authentication message has been created it
|
||||
tells the gss-ntlmssp mech that it's ok to generate the MIC. When the authentication message has been created
|
||||
it returns a bool stating whether the MIC was present in the auth message and subsequently whether we need to
|
||||
include the mechListMIC in the SPNEGO token.
|
||||
|
||||
See `mech_required_mechlistMIC in MIT KRB5`_ for more information about how MIT KRB5 deals with this.
|
||||
|
||||
Returns:
|
||||
bool: Whether the SPNEGO mechListMIC needs to be generated or not.
|
||||
|
||||
.. _mech_requires_mechlistMIC:
|
||||
https://github.com/krb5/krb5/blob/b2fe66fed560ae28917a4acae6f6c0f020156353/src/lib/gssapi/spnego/spnego_mech.c#L493
|
||||
"""
|
||||
return False # pragma: no cover
|
||||
|
||||
def _build_iov_list(
|
||||
self, iov: typing.Iterable[IOV], native_convert: typing.Callable[[IOVBuffer], NativeIOV]
|
||||
) -> typing.List[NativeIOV]:
|
||||
"""Creates a list of IOV buffers for the native provider needed."""
|
||||
provider_iov: typing.List[NativeIOV] = []
|
||||
|
||||
for entry in iov:
|
||||
data: typing.Optional[typing.Union[bytes, int, bool]]
|
||||
if isinstance(entry, tuple):
|
||||
if len(entry) != 2:
|
||||
raise ValueError("IOV entry tuple must contain 2 values, the type and data, see IOVBuffer.")
|
||||
|
||||
if not isinstance(entry[0], int):
|
||||
raise ValueError("IOV entry[0] must specify the BufferType as an int")
|
||||
buffer_type = entry[0]
|
||||
|
||||
if entry[1] is not None and not isinstance(entry[1], (bytes, int, bool)):
|
||||
raise ValueError(
|
||||
"IOV entry[1] must specify the buffer bytes, length of the buffer, or whether "
|
||||
"it is auto allocated."
|
||||
)
|
||||
data = entry[1] if entry[1] is not None else b""
|
||||
|
||||
elif isinstance(entry, int):
|
||||
buffer_type = entry
|
||||
data = None
|
||||
|
||||
elif isinstance(entry, bytes):
|
||||
buffer_type = BufferType.data
|
||||
data = entry
|
||||
|
||||
else:
|
||||
raise ValueError("IOV entry must be a IOVBuffer tuple, int, or bytes")
|
||||
|
||||
iov_buffer = IOVBuffer(type=BufferType(buffer_type), data=data)
|
||||
provider_iov.append(native_convert(iov_buffer))
|
||||
|
||||
return provider_iov
|
||||
|
||||
def _reset_ntlm_crypto_state(self, outgoing: bool = True) -> None:
|
||||
"""Reset the NTLM crypto handles after signing/verifying the SPNEGO mechListMIC.
|
||||
|
||||
`MS-SPNG`_ documents that after signing or verifying the mechListMIC, the RC4 key state needs to be the same
|
||||
for the mechListMIC and for the first message signed/sealed by the application. Because we use SSPI on Windows
|
||||
hosts which does all the work for us this function only matters for Linux hosts.
|
||||
|
||||
Args:
|
||||
outgoing: Whether to reset the outgoing or incoming RC4 key state.
|
||||
|
||||
.. _MS-SPNG:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/b87587b3-9d72-4027-8131-b76b5368115f
|
||||
"""
|
||||
pass # pragma: no cover
|
||||
287
env/lib/python3.12/site-packages/spnego/_credential.py
vendored
Normal file
287
env/lib/python3.12/site-packages/spnego/_credential.py
vendored
Normal file
@@ -0,0 +1,287 @@
|
||||
# Copyright: (c) 2021, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
"""Credentials that can be used by a client.
|
||||
|
||||
These are the various credentials that can be used as a client to authenticate
|
||||
with a service. See the docstring for each credential type to identify what
|
||||
credentials are usable for each authenticaton protocol.
|
||||
"""
|
||||
|
||||
import dataclasses
|
||||
import typing
|
||||
|
||||
from spnego._ntlm_raw.crypto import is_ntlm_hash
|
||||
from spnego.exceptions import InvalidCredentialError, NoCredentialError
|
||||
|
||||
# FUTURE: Add Anonymous credential class
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class Password:
|
||||
"""Plaintext username and password credential.
|
||||
|
||||
This is the simple username and password credential that is supported by
|
||||
all authentication protocols.
|
||||
|
||||
Attributes:
|
||||
username: The username.
|
||||
password: The password for the user.
|
||||
"""
|
||||
|
||||
username: str
|
||||
password: str = dataclasses.field(repr=False)
|
||||
|
||||
@property
|
||||
def supported_protocols(self) -> typing.List[str]:
|
||||
"""List of protocols the credential can be used for."""
|
||||
return ["credssp", "kerberos", "ntlm"]
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class CredentialCache:
|
||||
"""Cached credential.
|
||||
|
||||
Uses the provider specific cached credential. Can also specify a username
|
||||
to select a specific cached credential.
|
||||
|
||||
Attributes:
|
||||
username: Optional username used to select a specific credential in the
|
||||
cache.
|
||||
"""
|
||||
|
||||
username: typing.Optional[str] = None
|
||||
|
||||
@property
|
||||
def supported_protocols(self) -> typing.List[str]:
|
||||
return ["kerberos", "ntlm"]
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class NTLMHash:
|
||||
"""NTLM LM/NT Hash credential.
|
||||
|
||||
Used with :class:`NTLMProxy` for NTLM authentication backed by an NT and/or
|
||||
LM hash value. In modern iterations of NTLM only the NT hash needs to be
|
||||
specified and LM is ignored but both can be specified and the NTLM code
|
||||
will use them as necessary.
|
||||
|
||||
Attributes:
|
||||
username: The username the hashes are for.
|
||||
lm_hash: The LM hash as a hex string, can be `None` in most cases.
|
||||
nt_hash: The NT hash as a hex string.
|
||||
"""
|
||||
|
||||
username: str
|
||||
lm_hash: typing.Optional[str] = dataclasses.field(default=None, repr=False)
|
||||
nt_hash: typing.Optional[str] = dataclasses.field(default=None, repr=False)
|
||||
|
||||
@property
|
||||
def supported_protocols(self) -> typing.List[str]:
|
||||
"""List of protocols the credential can be used for."""
|
||||
return ["ntlm"]
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class KerberosKeytab:
|
||||
"""Kerberos Keytab Credential.
|
||||
|
||||
Used with :class:`GSSAPIProxy` or :class:`SSPIProxy` for Kerberos
|
||||
authentication. It is used to retrieve a Kerberos ticket using a keytab for
|
||||
authentication rather than a password.
|
||||
|
||||
Attributes:
|
||||
keytab: The keytab to use for authentication. The path will not be
|
||||
expanded of have variables substituted so should be the absolute
|
||||
path to the keytab.
|
||||
principal: The Kerberos principal to get the credential for. Should be
|
||||
in the UPN form `username@REALM.COM`. Set to `None` to use the
|
||||
first keytab entry.
|
||||
"""
|
||||
|
||||
keytab: str
|
||||
principal: typing.Optional[str] = None
|
||||
|
||||
@property
|
||||
def supported_protocols(self) -> typing.List[str]:
|
||||
"""List of protocols the credential can be used for."""
|
||||
return ["kerberos"]
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class KerberosCCache:
|
||||
"""Kerberos CCache Credential.
|
||||
|
||||
Used with :class:`GSSAPIProxy` for Kerberos authentication. It is used to
|
||||
specify the credential cache that has the stored Kerberos credential for
|
||||
authentication. The ccache value is specified in the form ``TYPE:RESIDUAL``
|
||||
where the ``TYPE`` supported is down to the installed Kerberos/GSSAPI
|
||||
implementation and ``RESIDUAL`` is a value specific to the type. Common
|
||||
types are:
|
||||
|
||||
DIR: The value is the path to a directory containing a collection of
|
||||
`FILE` caches.
|
||||
FILE: The value is the path to an individual cache.
|
||||
MEMORY: The value is a unique identifier to a cache stored in memory of
|
||||
the current process. It must be resolvable by the linked GSSAPI
|
||||
provider that this library uses.
|
||||
|
||||
There are other ccache types but they are mostly platform or GSSAPI
|
||||
implementation specific.
|
||||
|
||||
.. Note:
|
||||
This only works on Linux, Windows does not have the concept of
|
||||
separate CCaches.
|
||||
|
||||
Attributes:
|
||||
ccache: The ccache in the form ``TYPE:RESIDUAL`` to use for a Kerberos
|
||||
credential. The path will not be expanded of have variables
|
||||
substituted so should be the absolute path to the ccache.
|
||||
principal: Optional principal to get in the credential cache specified.
|
||||
"""
|
||||
|
||||
ccache: str
|
||||
principal: typing.Optional[str] = None
|
||||
|
||||
@property
|
||||
def supported_protocols(self) -> typing.List[str]:
|
||||
"""List of protocols the credential can be used for."""
|
||||
return ["kerberos"]
|
||||
|
||||
|
||||
# FUTURE: Expose this as an official credential
|
||||
# @dataclasses.dataclass
|
||||
# class CredSSPSmartCard:
|
||||
# """CredSSP Smart Card Credential.
|
||||
|
||||
# Used with :class:`CredSSPProxy` for CredSSP authentication. It is used to
|
||||
# delegate a smart card credential to the peer rather than a
|
||||
# username/password. It must be supplied with another NTLM/Kerberos supported
|
||||
# credential as this is only used for the delegation part of the CredSSP
|
||||
# authentication process.
|
||||
|
||||
# The values are modeled after `MS-CSSP TSSmartCardCreds`_.
|
||||
|
||||
# Attributes:
|
||||
# pin: The user's smart card PIN.
|
||||
# key_spec: The specification of the user's smart card.
|
||||
# card_name: The name of the smart card.
|
||||
# reader_name: The name of the smart card reader.
|
||||
# container_name: Name of the certificate container.
|
||||
# csp_name: Name of the CSP.
|
||||
# user_hint: The user's account hint.
|
||||
# domain_hint: The user's domain name hint.
|
||||
|
||||
# .. _MS-CSSP TSSmartCardCreds:
|
||||
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cssp/4251d165-cf01-4513-a5d8-39ee4a98b7a4
|
||||
# """
|
||||
# pin: bytes
|
||||
# key_spec: int
|
||||
# card_name: typing.Optional[bytes] = None
|
||||
# reader_name: typing.Optional[bytes] = None
|
||||
# container_name: typing.Optional[bytes] = None
|
||||
# csp_name: typing.Optional[bytes] = None
|
||||
# user_hint: typing.Optional[bytes] = None
|
||||
# domain_hint: typing.Optional[bytes] = None
|
||||
|
||||
# @property
|
||||
# def supported_protocols(self) -> typing.List[str]:
|
||||
# return ["credssp"]
|
||||
|
||||
|
||||
# @dataclasses.dataclass
|
||||
# class CredSSPRemoteGuardPackage:
|
||||
# """CredSSP Remote Guard Credential.
|
||||
|
||||
# Used with :class:`CredSSPProxy` for CredSSP authentication. It is used to
|
||||
# delegate credential protected by `Remote Credential Guard`_. It must be
|
||||
# supplied with another NTLM/Kerberos supported credential as this is only
|
||||
# used for the delegation part of the CredSSP authentication process.
|
||||
# Multiple instance of this can be passed in with the first entry being the
|
||||
# logon credential and the remaining instances being the supplemental
|
||||
# credentials.
|
||||
|
||||
# The values are modeled after `MS-CSSP TSRemoteGuardPackageCred`_.
|
||||
|
||||
# .. _Remote Credential Guard:
|
||||
# https://docs.microsoft.com/en-us/windows/security/identity-protection/remote-credential-guard
|
||||
|
||||
# .. _MS-CSSP TSRemoteGuardPackageCred:
|
||||
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cssp/173eee44-1a2c-463f-b909-c15db01e68d7
|
||||
# """
|
||||
# package_name: str
|
||||
# cred_buffer: bytes
|
||||
|
||||
# @property
|
||||
# def supported_protocols(self) -> typing.List[str]:
|
||||
# return ["credssp"]
|
||||
|
||||
|
||||
Credential = typing.Union[CredentialCache, KerberosCCache, KerberosKeytab, NTLMHash, Password]
|
||||
|
||||
|
||||
def unify_credentials(
|
||||
username: typing.Optional[typing.Union[str, Credential, typing.List[Credential]]] = None,
|
||||
password: typing.Optional[str] = None,
|
||||
required_protocol: typing.Optional[str] = None,
|
||||
) -> typing.List[Credential]:
|
||||
"""Process user input credentials.
|
||||
|
||||
Converts the user facing credential input into a list of credentials that
|
||||
is known by spnego. Also filters out any duplicate credentials/ones that
|
||||
are rendered obsolete by any ones preceding it. For example NTLMHash won't
|
||||
be used if it's specified after Password in the credential list.
|
||||
|
||||
Args:
|
||||
username: The username or list of credentials to process.
|
||||
password: The password for username when it's a string.
|
||||
required_protocol: Optionally checks that at least 1 credential must
|
||||
support the protocol specified.
|
||||
|
||||
Returns:
|
||||
typing.List[Credential]: A list of credentials based on the free-form
|
||||
input.
|
||||
"""
|
||||
if username:
|
||||
if isinstance(username, str):
|
||||
if password is None:
|
||||
username = [CredentialCache(username=username)]
|
||||
elif is_ntlm_hash(password):
|
||||
lm, nt = password.split(":", 1)
|
||||
username = [NTLMHash(username=username, lm_hash=lm, nt_hash=nt)]
|
||||
else:
|
||||
username = [Password(username=username, password=password)]
|
||||
|
||||
elif not isinstance(username, list):
|
||||
username = [username]
|
||||
|
||||
else:
|
||||
username = [CredentialCache()]
|
||||
|
||||
credentials: typing.List[Credential] = []
|
||||
used_protocols: typing.Set[str] = set()
|
||||
for cred in username:
|
||||
if not isinstance(cred, (CredentialCache, KerberosCCache, KerberosKeytab, NTLMHash, Password)):
|
||||
raise InvalidCredentialError(
|
||||
context_msg="Invalid username/credential specified, must be a string or Credential object."
|
||||
)
|
||||
|
||||
# Remove any credential that only implements protocols that are already covered by one before it.
|
||||
# FUTURE: This might be problematic with the CredSSP ones
|
||||
cred_useful = False
|
||||
for cred_protocol in cred.supported_protocols:
|
||||
if cred_protocol not in used_protocols:
|
||||
used_protocols.add(cred_protocol)
|
||||
cred_useful = True
|
||||
|
||||
if cred_useful:
|
||||
credentials.append(cred)
|
||||
|
||||
if required_protocol and required_protocol not in used_protocols:
|
||||
found_protocols = ", ".join(sorted(used_protocols))
|
||||
raise NoCredentialError(
|
||||
context_msg=f"A credential for {required_protocol} is needed but only found "
|
||||
f"credentials for {found_protocols}"
|
||||
)
|
||||
|
||||
return credentials
|
||||
662
env/lib/python3.12/site-packages/spnego/_credssp.py
vendored
Normal file
662
env/lib/python3.12/site-packages/spnego/_credssp.py
vendored
Normal file
@@ -0,0 +1,662 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import ssl
|
||||
import struct
|
||||
import tempfile
|
||||
import typing
|
||||
|
||||
import spnego
|
||||
from spnego._context import (
|
||||
IOV,
|
||||
ContextProxy,
|
||||
ContextReq,
|
||||
IOVUnwrapResult,
|
||||
IOVWrapResult,
|
||||
SecPkgContextSizes,
|
||||
UnwrapResult,
|
||||
WinRMWrapResult,
|
||||
WrapResult,
|
||||
split_username,
|
||||
)
|
||||
from spnego._credential import Credential, Password, unify_credentials
|
||||
from spnego._credssp_structures import (
|
||||
NegoData,
|
||||
TSCredentials,
|
||||
TSPasswordCreds,
|
||||
TSRequest,
|
||||
)
|
||||
from spnego._text import to_text
|
||||
from spnego.channel_bindings import GssChannelBindings
|
||||
from spnego.exceptions import (
|
||||
BadBindingsError,
|
||||
ErrorCode,
|
||||
FeatureMissingError,
|
||||
InvalidTokenError,
|
||||
NativeError,
|
||||
NegotiateOptions,
|
||||
NoContextError,
|
||||
OperationNotAvailableError,
|
||||
SpnegoError,
|
||||
)
|
||||
from spnego.tls import (
|
||||
CredSSPTLSContext,
|
||||
default_tls_context,
|
||||
generate_tls_certificate,
|
||||
get_certificate_public_key,
|
||||
)
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# The protocol version understood by the client and server.
|
||||
_CREDSSP_VERSION = 6
|
||||
_X509_CERTIFICATE: typing.Optional[typing.Tuple[bytes, bytes, bytes]] = None
|
||||
|
||||
F = typing.TypeVar("F", bound=typing.Callable[..., typing.Any])
|
||||
|
||||
|
||||
def _create_tls_context(
|
||||
usage: str,
|
||||
) -> CredSSPTLSContext:
|
||||
log.debug("Creating TLS context")
|
||||
ctx = default_tls_context(usage=usage)
|
||||
|
||||
if usage == "accept":
|
||||
# Cache the result for future operations
|
||||
global _X509_CERTIFICATE
|
||||
if not _X509_CERTIFICATE:
|
||||
_X509_CERTIFICATE = generate_tls_certificate()
|
||||
|
||||
cert_pem, key_pem, public_key = _X509_CERTIFICATE
|
||||
|
||||
# Can't use tempfile.NamedTemporaryFile() as load_cert_chain() opens the file on another handle which fails
|
||||
# on Windows as the tempfile requires DELETE share access for that to work.
|
||||
temp_dir = tempfile.mkdtemp()
|
||||
try:
|
||||
cert_path = os.path.join(temp_dir, "ca.pem")
|
||||
with open(cert_path, mode="wb") as fd:
|
||||
fd.write(cert_pem)
|
||||
fd.write(key_pem)
|
||||
|
||||
ctx.context.load_cert_chain(cert_path)
|
||||
ctx.public_key = public_key
|
||||
|
||||
finally:
|
||||
shutil.rmtree(temp_dir)
|
||||
|
||||
return ctx
|
||||
|
||||
|
||||
def _get_pub_key_auth(
|
||||
pub_key: bytes,
|
||||
usage: str,
|
||||
nonce: typing.Optional[bytes] = None,
|
||||
) -> bytes:
|
||||
"""Computes the public key authentication value.
|
||||
|
||||
Params:
|
||||
pub_key: The public key to transform.
|
||||
usage: Either `initiate` or `accept` to denote if the key is for the
|
||||
client to server or vice versa.
|
||||
nonce: A 32 byte nonce used for CredSSP version 5 or newer.
|
||||
|
||||
Returns:
|
||||
bytes: The public key authentication value.
|
||||
"""
|
||||
if nonce:
|
||||
direction = b"Client-To-Server" if usage == "initiate" else b"Server-To-Client"
|
||||
hash_input = (b"CredSSP %s Binding Hash\x00" % direction) + nonce + pub_key
|
||||
key_auth = hashlib.sha256(hash_input).digest()
|
||||
|
||||
elif usage == "accept":
|
||||
first_byte = struct.unpack("B", pub_key[0:1])[0]
|
||||
key_auth = struct.pack("B", first_byte + 1) + pub_key[1:]
|
||||
|
||||
else:
|
||||
key_auth = pub_key
|
||||
|
||||
return key_auth
|
||||
|
||||
|
||||
def _tls_trailer_length(
|
||||
data_length: int,
|
||||
protocol: str,
|
||||
cipher_suite: str,
|
||||
) -> int:
|
||||
"""Gets the length of the TLS trailer.
|
||||
|
||||
WinRM wrapping needs to split the trailer/header with the data but the
|
||||
length of the trailer is dependent on the cipher suite that was negotiated.
|
||||
On Windows you can get this length by calling `QueryContextAttributes`_
|
||||
with the `SecPkgContext_StreamSizes`_ structure. Unfortunately we need to
|
||||
work on other platforms so we calculate it manually.
|
||||
|
||||
Params:
|
||||
data_length: The length of the TLS data used to calculate the padding
|
||||
size.
|
||||
protocol: The TLS protocol negotiated between the client and server.
|
||||
cipher_suite: The TLS cipher suite negotiated between the client and
|
||||
server.
|
||||
|
||||
Returns:
|
||||
int: The length of the trailer.
|
||||
|
||||
.. _QueryContextAttributes:
|
||||
https://docs.microsoft.com/en-us/windows/win32/api/sspi/nf-sspi-querycontextattributesw
|
||||
|
||||
.. _SecPkgContext_StreamSizes:
|
||||
https://docs.microsoft.com/en-us/windows/win32/api/sspi/ns-sspi-secpkgcontext_streamsizes
|
||||
"""
|
||||
if protocol == "TLSv1.3":
|
||||
# The 2 cipher suites that MS supports for TLS 1.3 (TLS_AES_*_GCM_SHA*) have a fixed length of 17. This may
|
||||
# change in the future but it works for now.
|
||||
trailer_length = 17
|
||||
|
||||
elif re.match(r"^.*[-_]GCM[-_][\w\d]*$", cipher_suite):
|
||||
# GCM has a fixed length of 16 bytes
|
||||
trailer_length = 16
|
||||
|
||||
else:
|
||||
# For other cipher suites, trailer size == len(hmac) + len(padding) the padding is the length required by the
|
||||
# chosen block cipher.
|
||||
hash_algorithm = cipher_suite.split("-")[-1]
|
||||
|
||||
# While there are other algorithms, SChannel doesn't support them as of yet so we just keep to this list.
|
||||
hash_length = {"MD5": 16, "SHA": 20, "SHA256": 32, "SHA384": 48}.get(hash_algorithm, 0)
|
||||
|
||||
pre_pad_length = data_length + hash_length
|
||||
if "RC4" in cipher_suite:
|
||||
# RC4 is a stream cipher so no padding would be added.
|
||||
padding_length = 0
|
||||
|
||||
elif "DES" in cipher_suite or "3DES" in cipher_suite:
|
||||
# 3DES is a 64 bit block cipher.
|
||||
padding_length = 8 - (pre_pad_length % 8)
|
||||
|
||||
else:
|
||||
# AES is a 128 bit block cipher.
|
||||
padding_length = 16 - (pre_pad_length % 16)
|
||||
|
||||
trailer_length = (pre_pad_length + padding_length) - data_length
|
||||
|
||||
return trailer_length
|
||||
|
||||
|
||||
def _wrap_ssl_error(context: str) -> typing.Callable[[F], F]:
|
||||
def decorator(func: F) -> F:
|
||||
def wrapped(*args: typing.Any, **kwargs: typing.Any) -> F:
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
|
||||
except ssl.SSLError as e:
|
||||
raise SpnegoError(error_code=ErrorCode.failure, context_msg="%s: %s" % (context, e)) from e
|
||||
|
||||
return typing.cast(F, wrapped)
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
class CredSSPProxy(ContextProxy):
|
||||
"""CredSSP proxy class CredSSP authentication.
|
||||
|
||||
This proxy class for CredSSP can be used to exchange CredSSP tokens.
|
||||
It uses the NegotiateProxy provider for the underlying authentication but
|
||||
exchanges the tokens in the exchange required by CredSSP. The main
|
||||
advantage of CredSSP is that it allows you to delegate the user's
|
||||
credentials to the server.
|
||||
|
||||
The acceptor logic is mostly done as a proof of concept and for use with
|
||||
testing. Use at your own risk.
|
||||
|
||||
Currently this context proxy supports the following CredSSP protocols:
|
||||
|
||||
2:
|
||||
Earliest protocol that ships with Windows XP, Vista, 7, 8, Server
|
||||
2008, 2008 R2, and 2012. This version is susceptible to
|
||||
CVE-2018-0886
|
||||
3:
|
||||
Introduced with Windows 8.1 and Server 2012 R2. Adds the errorCode
|
||||
field for better error details on a failure. This version is
|
||||
susceptible to CVE-2018-0886.
|
||||
4:
|
||||
Largely the same as 3, introduced in an older Win 10 build.
|
||||
5:
|
||||
Same as version 2 but with the mitigations for CVE-2018-0886
|
||||
applied.
|
||||
6:
|
||||
Same as version 3 and 4 but with the mitigations for CVE-2018-0886
|
||||
applied.
|
||||
|
||||
If the context proxy is talking to a peer with a higher protocol number it
|
||||
is treated the same as what the client supports.
|
||||
|
||||
Optional kwargs supports by CredSSPProxy:
|
||||
|
||||
credssp_negotiate_context: Use this contest for the underlying
|
||||
authentication negotiation. This allows the caller to restrict the
|
||||
auth to Kerberos or set any other setting specific to their
|
||||
environment:
|
||||
|
||||
credssp_tls_context: Custom :class:`CredSSPTLSContext` to use for the
|
||||
CredSSP exchange. See `spnego.tls` for helper methods to generate
|
||||
a custom TLS context.
|
||||
|
||||
credssp_min_protocol: The minimum CredSSP authentication protocol the
|
||||
context will allow. This can control whether the server rejects
|
||||
peers running on a lower protocol version than what is set to
|
||||
enforce a better security baseline. The default is 2 which works
|
||||
against all CredSSP peers. To ensure the mitigations for
|
||||
CVE-2018-0886 is in place set this value to 5 or higher.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
username: typing.Optional[typing.Union[str, Credential, typing.List[Credential]]] = None,
|
||||
password: typing.Optional[str] = None,
|
||||
hostname: typing.Optional[str] = None,
|
||||
service: typing.Optional[str] = None,
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
context_req: ContextReq = ContextReq.default,
|
||||
usage: str = "initiate",
|
||||
protocol: str = "credssp",
|
||||
options: NegotiateOptions = NegotiateOptions.none,
|
||||
**kwargs: typing.Any,
|
||||
) -> None:
|
||||
credentials = unify_credentials(
|
||||
username, password, required_protocol="credssp" if usage == "initiate" else None
|
||||
)
|
||||
super(CredSSPProxy, self).__init__(
|
||||
credentials, hostname, service, channel_bindings, context_req, usage, protocol, options
|
||||
)
|
||||
|
||||
if options & NegotiateOptions.session_key:
|
||||
raise FeatureMissingError(NegotiateOptions.session_key)
|
||||
|
||||
self._credentials = credentials
|
||||
self._options = options & ~NegotiateOptions.wrapping_winrm # WinRM wrapping won't apply for auth context.
|
||||
|
||||
self._auth_context: typing.Optional[ContextProxy] = kwargs.get("credssp_negotiate_context", None)
|
||||
self._ts_credential: typing.Optional[TSCredentials] = None
|
||||
self._complete = False
|
||||
self._step_gen: typing.Optional[typing.Generator[bytes, typing.Optional[bytes], None]] = None
|
||||
self._auth_stage = "TLS Handshake"
|
||||
self._min_version: int = kwargs.get("credssp_min_protocol", 2)
|
||||
self._selected_version: typing.Optional[int] = None
|
||||
|
||||
self._tls_context: CredSSPTLSContext
|
||||
if "credssp_tls_context" in kwargs:
|
||||
self._tls_context = kwargs["credssp_tls_context"]
|
||||
|
||||
if usage == "accept" and not self._tls_context.public_key:
|
||||
raise OperationNotAvailableError(context_msg="Provided tls context does not have a public key set")
|
||||
else:
|
||||
self._tls_context = _create_tls_context(usage)
|
||||
|
||||
self._in_buff = ssl.MemoryBIO()
|
||||
self._out_buff = ssl.MemoryBIO()
|
||||
self._tls_object = self._tls_context.context.wrap_bio(
|
||||
self._in_buff, self._out_buff, server_side=(usage == "accept")
|
||||
)
|
||||
|
||||
if usage == "initiate":
|
||||
for cred in credentials:
|
||||
# There will always be a Password cred as per the check in unify_credentials
|
||||
if isinstance(cred, Password):
|
||||
domain, username = split_username(cred.username)
|
||||
password_cred = TSPasswordCreds(domain or "", username or "", cred.password)
|
||||
self._ts_credential = TSCredentials(credentials=password_cred)
|
||||
break
|
||||
|
||||
@classmethod
|
||||
def available_protocols(cls, options: typing.Optional[NegotiateOptions] = None) -> typing.List[str]:
|
||||
return ["credssp"]
|
||||
|
||||
@classmethod
|
||||
def iov_available(cls) -> bool:
|
||||
return False
|
||||
|
||||
@property
|
||||
def client_principal(self) -> typing.Optional[str]:
|
||||
return self._auth_context.client_principal if self._auth_context else None
|
||||
|
||||
@property
|
||||
def complete(self) -> bool:
|
||||
return self._complete
|
||||
|
||||
@property
|
||||
def negotiated_protocol(self) -> typing.Optional[str]:
|
||||
return self._auth_context.negotiated_protocol if self._auth_context else None
|
||||
|
||||
@property
|
||||
def session_key(self) -> bytes:
|
||||
raise OperationNotAvailableError(context_msg="CredSSP does not have a session key to share")
|
||||
|
||||
def new_context(self) -> "CredSSPProxy":
|
||||
return CredSSPProxy(
|
||||
username=self._credentials,
|
||||
hostname=self._hostname,
|
||||
service=self._service,
|
||||
channel_bindings=self.channel_bindings,
|
||||
context_req=self.context_req,
|
||||
usage=self.usage,
|
||||
protocol=self.protocol,
|
||||
options=self.options,
|
||||
credssp_negotiate_context=self._auth_context.new_context() if self._auth_context else None,
|
||||
)
|
||||
|
||||
def step(
|
||||
self,
|
||||
in_token: typing.Optional[bytes] = None,
|
||||
*,
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
) -> typing.Optional[bytes]:
|
||||
log.debug("CredSSP step input: %s", to_text(base64.b64encode(in_token or b"")))
|
||||
|
||||
if self._step_gen is None:
|
||||
self._step_gen = getattr(self, "_step_%s" % self.usage)(in_token)
|
||||
in_token = None
|
||||
|
||||
out_token = None
|
||||
try:
|
||||
out_token = self._step_gen.send(in_token)
|
||||
except StopIteration:
|
||||
pass
|
||||
|
||||
log.debug("CredSSP step output: %s", to_text(base64.b64encode(out_token or b"")))
|
||||
return out_token
|
||||
|
||||
def _step_initiate(
|
||||
self,
|
||||
in_token: typing.Optional[bytes],
|
||||
) -> typing.Generator[bytes, bytes, None]:
|
||||
"""The initiator authentication steps of CredSSP."""
|
||||
yield from self._step_tls(in_token)
|
||||
|
||||
server_certificate = typing.cast(bytes, self._tls_object.getpeercert(True))
|
||||
public_key = get_certificate_public_key(server_certificate)
|
||||
|
||||
log.debug("Starting CredSSP authentication phase")
|
||||
if not self._auth_context:
|
||||
auth_kwargs: typing.Dict[str, typing.Any] = {}
|
||||
if self._hostname:
|
||||
auth_kwargs["hostname"] = self._hostname
|
||||
if self._service:
|
||||
auth_kwargs["service"] = self._service
|
||||
self._auth_context = spnego.client(
|
||||
self._credentials, protocol="negotiate", options=self._options, **auth_kwargs
|
||||
)
|
||||
|
||||
round = 0
|
||||
out_token = self._auth_context.step()
|
||||
while True:
|
||||
round += 1
|
||||
auth_request = TSRequest(_CREDSSP_VERSION, nego_tokens=NegoData(out_token or b""))
|
||||
|
||||
auth_response = yield from self._yield_ts_request(auth_request, "Authentication %d" % round)
|
||||
out_token = self._auth_context.step(auth_response.nego_tokens[0].nego_token) # type: ignore[index]
|
||||
|
||||
# Special edge case, we need to include the final NTLM token in the pubKeyAuth step but the context won't
|
||||
# be seen as complete when it's wrapped in SPNEGO. We just check if the known header signature is present.
|
||||
if self._auth_context.complete or (out_token and b"NTLMSSP\x00\x03\x00\x00\x00" in out_token):
|
||||
break
|
||||
|
||||
self._selected_version = min(auth_response.version, _CREDSSP_VERSION)
|
||||
log.debug("Negotiated CredSSP version: %d" % self._selected_version)
|
||||
if self._selected_version < self._min_version:
|
||||
msg = (
|
||||
f"The peer protocol version was {auth_response.version} and did not meet the minimum "
|
||||
f"requirements of {self._min_version}"
|
||||
)
|
||||
raise InvalidTokenError(context_msg=msg)
|
||||
|
||||
pub_key_nego_token = NegoData(out_token) if out_token else None
|
||||
nonce = os.urandom(32) if self._selected_version > 4 else None
|
||||
pub_value = _get_pub_key_auth(public_key, "initiate", nonce=nonce)
|
||||
pub_key_request = TSRequest(
|
||||
version=_CREDSSP_VERSION,
|
||||
nego_tokens=pub_key_nego_token,
|
||||
client_nonce=nonce,
|
||||
pub_key_auth=self._auth_context.wrap(pub_value).data,
|
||||
)
|
||||
|
||||
pub_key_response = yield from self._yield_ts_request(pub_key_request, "Public key exchange")
|
||||
if not pub_key_response.pub_key_auth:
|
||||
raise InvalidTokenError(context_msg="Acceptor did not response with pubKeyAuth info.")
|
||||
|
||||
if pub_key_response.nego_tokens:
|
||||
# NTLM over SPNEGO auth returned the mechListMIC for us to verify.
|
||||
self._auth_context.step(pub_key_response.nego_tokens[0].nego_token)
|
||||
|
||||
response_key = self._auth_context.unwrap(pub_key_response.pub_key_auth).data
|
||||
expected_key = _get_pub_key_auth(public_key, "accept", nonce=nonce)
|
||||
if expected_key != response_key:
|
||||
raise BadBindingsError(context_msg="Public key verification failed, potential man in the middle attack")
|
||||
|
||||
enc_credentials = self._auth_context.wrap(
|
||||
self._ts_credential.pack() # type: ignore[union-attr] # initiate always has one
|
||||
).data
|
||||
credential_request = TSRequest(_CREDSSP_VERSION, auth_info=enc_credentials)
|
||||
self._complete = True
|
||||
|
||||
yield from self._yield_ts_request(credential_request, "Credential exchange")
|
||||
|
||||
def _step_accept(
|
||||
self,
|
||||
in_token: typing.Optional[bytes],
|
||||
) -> typing.Generator[bytes, bytes, None]:
|
||||
"""The acceptor authentication steps of CredSSP."""
|
||||
in_token = yield from self._step_tls(in_token)
|
||||
|
||||
auth_request = TSRequest.unpack(in_token or b"")
|
||||
|
||||
# The version to use as the acceptor should be the smaller of the client and _CREDSSP_VERSION.
|
||||
self._selected_version = min(auth_request.version, _CREDSSP_VERSION)
|
||||
log.debug("Negotiated CredSSP version: %d" % self._selected_version)
|
||||
if self._selected_version < self._min_version:
|
||||
msg = (
|
||||
f"The peer protocol version was {auth_request.version} and did not meet the minimum "
|
||||
f"requirements of {self._min_version}"
|
||||
)
|
||||
raise InvalidTokenError(context_msg=msg)
|
||||
|
||||
try:
|
||||
log.debug("Starting CredSSP authentication phase")
|
||||
if not self._auth_context:
|
||||
auth_kwargs: typing.Dict[str, typing.Any] = {}
|
||||
if self._hostname:
|
||||
auth_kwargs["hostname"] = self._hostname
|
||||
if self._service:
|
||||
auth_kwargs["service"] = self._service
|
||||
self._auth_context = spnego.server(protocol="negotiate", options=self._options, **auth_kwargs)
|
||||
|
||||
round = 0
|
||||
while True:
|
||||
round += 1
|
||||
nego_out_token = None
|
||||
|
||||
if auth_request.nego_tokens:
|
||||
nego_out_token = self._auth_context.step(auth_request.nego_tokens[0].nego_token)
|
||||
|
||||
if auth_request.pub_key_auth:
|
||||
break
|
||||
|
||||
auth_response = TSRequest(_CREDSSP_VERSION, nego_tokens=NegoData(nego_out_token or b""))
|
||||
auth_request = yield from self._yield_ts_request(auth_response, "Authentication %d" % round)
|
||||
|
||||
except SpnegoError as e:
|
||||
# Version 2 and 5 don't support the errorCode field and the initiator won't expect a token back.
|
||||
log.warning("Received CredSSP error when accepting credentials: %s", e)
|
||||
if self._selected_version in [3, 4] or self._selected_version >= 6:
|
||||
error_token = TSRequest(_CREDSSP_VERSION, error_code=e.nt_status)
|
||||
yield from self._yield_ts_request(error_token, "Authentication failure")
|
||||
|
||||
return
|
||||
|
||||
actual_key = self._auth_context.unwrap(auth_request.pub_key_auth).data
|
||||
public_key = self._tls_context.public_key or b""
|
||||
expected_key = _get_pub_key_auth(public_key, "initiate", nonce=auth_request.client_nonce)
|
||||
if actual_key != expected_key:
|
||||
raise BadBindingsError(context_msg="Public key verification failed, potential man in the middle attack")
|
||||
|
||||
nego_token = NegoData(nego_out_token) if nego_out_token else None
|
||||
server_key = self._auth_context.wrap(
|
||||
_get_pub_key_auth(public_key, "accept", nonce=auth_request.client_nonce)
|
||||
).data
|
||||
pub_key_response = TSRequest(_CREDSSP_VERSION, nego_tokens=nego_token, pub_key_auth=server_key)
|
||||
auth_request = yield from self._yield_ts_request(pub_key_response, "Public key exchange")
|
||||
|
||||
self._auth_stage = "Credential exchange"
|
||||
if not auth_request.auth_info:
|
||||
raise InvalidTokenError(context_msg="No credential received on CredSSP TSRequest from initiator")
|
||||
|
||||
self._ts_credential = TSCredentials.unpack(self._auth_context.unwrap(auth_request.auth_info).data)
|
||||
self._complete = True
|
||||
|
||||
def _step_tls(self, in_token: typing.Optional[bytes]) -> typing.Generator[bytes, bytes, bytes]:
|
||||
"""The TLS handshake phase of CredSSP."""
|
||||
try:
|
||||
while True:
|
||||
# For an acceptor we start with a token (Client Hello), write this to the memory BIO before processing.
|
||||
if in_token:
|
||||
self._in_buff.write(in_token)
|
||||
|
||||
want_read = False
|
||||
try:
|
||||
self._tls_object.do_handshake()
|
||||
except ssl.SSLWantReadError:
|
||||
# The handshake process requires more data to be exchanged.
|
||||
want_read = True
|
||||
|
||||
# We need to keep on sending the TLS packets until there is nothing left to send.
|
||||
# If we are an acceptor we still need to send an empty token to the initiator.
|
||||
# https://github.com/jborean93/pyspnego/issues/90
|
||||
out_token = self._out_buff.read()
|
||||
if not out_token and self.usage != "accept":
|
||||
break
|
||||
in_token = yield out_token
|
||||
|
||||
# TLSv1.3 acceptor has no more work to be done after SSLWantReadError was not raised and it received
|
||||
# the last token from the user (first authentication token).
|
||||
if not want_read and self.usage == "accept":
|
||||
out_token = self.unwrap(in_token).data
|
||||
break
|
||||
|
||||
except ssl.SSLError as e:
|
||||
raise InvalidTokenError(context_msg="TLS handshake for CredSSP: %s" % e) from e
|
||||
|
||||
cipher, protocol, _ = self._tls_object.cipher() # type: ignore[misc] # This should always be present
|
||||
log.debug("TLS handshake complete, negotiation details: %s %s", protocol, cipher)
|
||||
return out_token
|
||||
|
||||
def _yield_ts_request(
|
||||
self,
|
||||
ts_request: TSRequest,
|
||||
context_msg: str,
|
||||
) -> typing.Generator[bytes, bytes, TSRequest]:
|
||||
"""Exchanges a TSRequest between the initiator and acceptor."""
|
||||
self._auth_stage = context_msg
|
||||
|
||||
out_request = ts_request.pack()
|
||||
log.debug("CredSSP TSRequest output: %s" % to_text(base64.b64encode(out_request)))
|
||||
wrapped_response = yield self.wrap(out_request).data
|
||||
|
||||
in_request = self.unwrap(wrapped_response).data
|
||||
log.debug("CredSSP TSRequest input: %s" % to_text(base64.b64encode(in_request)))
|
||||
response = TSRequest.unpack(in_request)
|
||||
|
||||
if response.error_code:
|
||||
# The error code is an NtStatus value, try to see if it maps to a known error in our exception map.
|
||||
base_error = NativeError("Received NTStatus in TSRequest from acceptor", winerror=response.error_code)
|
||||
raise SpnegoError(base_error=base_error, context_msg=context_msg)
|
||||
|
||||
return response
|
||||
|
||||
def get_extra_info(
|
||||
self,
|
||||
name: str,
|
||||
default: typing.Any = None,
|
||||
) -> typing.Any:
|
||||
if name == "client_credential" and self.usage == "accept" and self._ts_credential:
|
||||
return self._ts_credential.credentials
|
||||
|
||||
elif name == "sslcontext":
|
||||
return self._tls_context.context
|
||||
|
||||
elif name == "ssl_object":
|
||||
return self._tls_object
|
||||
|
||||
elif name == "auth_stage":
|
||||
return self._auth_stage
|
||||
|
||||
elif name == "protocol_version" and self._selected_version is not None:
|
||||
return self._selected_version
|
||||
|
||||
else:
|
||||
return default
|
||||
|
||||
def query_message_sizes(self) -> SecPkgContextSizes:
|
||||
if not self._tls_object or not self.complete:
|
||||
raise NoContextError(context_msg="Cannot get message sizes until context has been established")
|
||||
|
||||
cipher_negotiated, tls_protocol, _ = self._tls_object.cipher() # type: ignore[misc]
|
||||
trailer_length = _tls_trailer_length(0, tls_protocol, cipher_negotiated)
|
||||
|
||||
return SecPkgContextSizes(header=trailer_length)
|
||||
|
||||
@_wrap_ssl_error("Invalid TLS state when wrapping data")
|
||||
def wrap(self, data: bytes, encrypt: bool = True, qop: typing.Optional[int] = None) -> WrapResult:
|
||||
self._tls_object.write(data)
|
||||
return WrapResult(data=self._out_buff.read(), encrypted=True)
|
||||
|
||||
def wrap_iov(
|
||||
self,
|
||||
iov: typing.Iterable[IOV],
|
||||
encrypt: bool = True,
|
||||
qop: typing.Optional[int] = None,
|
||||
) -> IOVWrapResult:
|
||||
raise OperationNotAvailableError(context_msg="CredSSP does not offer IOV wrapping")
|
||||
|
||||
def wrap_winrm(self, data: bytes) -> WinRMWrapResult:
|
||||
enc_data = self.wrap(data).data
|
||||
cipher_negotiated, tls_protocol, _ = self._tls_object.cipher() # type: ignore[misc]
|
||||
trailer_length = _tls_trailer_length(len(data), tls_protocol, cipher_negotiated)
|
||||
|
||||
return WinRMWrapResult(header=enc_data[:trailer_length], data=enc_data[trailer_length:], padding_length=0)
|
||||
|
||||
@_wrap_ssl_error("Invalid TLS state when unwrapping data")
|
||||
def unwrap(self, data: bytes) -> UnwrapResult:
|
||||
self._in_buff.write(data)
|
||||
|
||||
chunks = []
|
||||
while True:
|
||||
try:
|
||||
chunks.append(self._tls_object.read())
|
||||
except ssl.SSLWantReadError:
|
||||
break
|
||||
|
||||
return UnwrapResult(data=b"".join(chunks), encrypted=True, qop=0)
|
||||
|
||||
def unwrap_iov(
|
||||
self,
|
||||
iov: typing.Iterable[IOV],
|
||||
) -> IOVUnwrapResult:
|
||||
raise OperationNotAvailableError(context_msg="CredSSP does not offer IOV wrapping")
|
||||
|
||||
def unwrap_winrm(self, header: bytes, data: bytes) -> bytes:
|
||||
return self.unwrap(header + data).data
|
||||
|
||||
def sign(self, data: bytes, qop: typing.Optional[int] = None) -> bytes:
|
||||
raise OperationNotAvailableError(context_msg="CredSSP does not offer signing")
|
||||
|
||||
def verify(self, data: bytes, mic: bytes) -> int:
|
||||
raise OperationNotAvailableError(context_msg="CredSSP does not offer verification")
|
||||
|
||||
@property
|
||||
def _context_attr_map(self) -> typing.List[typing.Tuple[ContextReq, int]]:
|
||||
return [] # Not applicable to CredSSP.
|
||||
586
env/lib/python3.12/site-packages/spnego/_credssp_structures.py
vendored
Normal file
586
env/lib/python3.12/site-packages/spnego/_credssp_structures.py
vendored
Normal file
@@ -0,0 +1,586 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import typing
|
||||
|
||||
from spnego._asn1 import (
|
||||
ASN1Value,
|
||||
TagClass,
|
||||
get_sequence_value,
|
||||
pack_asn1,
|
||||
pack_asn1_integer,
|
||||
pack_asn1_octet_string,
|
||||
pack_asn1_sequence,
|
||||
unpack_asn1,
|
||||
unpack_asn1_integer,
|
||||
unpack_asn1_octet_string,
|
||||
unpack_asn1_tagged_sequence,
|
||||
)
|
||||
|
||||
|
||||
def unpack_text_field(
|
||||
sequence: typing.Dict[int, ASN1Value],
|
||||
idx: int,
|
||||
structure: str,
|
||||
name: str,
|
||||
**kwargs: typing.Optional[str],
|
||||
) -> typing.Optional[str]:
|
||||
"""Extracts a text field from a tagged ASN.1 sequence."""
|
||||
raw_value = get_sequence_value(sequence, idx, structure, name, unpack_asn1_octet_string)
|
||||
if raw_value is None:
|
||||
if "default" not in kwargs:
|
||||
raise ValueError("Missing mandatory text field '%s' in '%s'" % (name, structure))
|
||||
|
||||
return kwargs["default"]
|
||||
|
||||
return raw_value.decode("utf-16-le")
|
||||
|
||||
|
||||
def unpack_sequence(data: typing.Union[ASN1Value, bytes]) -> typing.Dict[int, ASN1Value]:
|
||||
"""Helper function that can unpack a sequence as either it's raw bytes or the already unpacked ASN.1 tuple."""
|
||||
if not isinstance(data, ASN1Value):
|
||||
data = unpack_asn1(data)[0]
|
||||
|
||||
return unpack_asn1_tagged_sequence(data)
|
||||
|
||||
|
||||
class NegoData:
|
||||
"""CredSSP NegoData structure.
|
||||
|
||||
The NegoData structure contains the SPNEGO tokens, the Kerberos messages, or the NTLM messages. While the
|
||||
structure is a SEQUENCE OF SEQUENCE this class just represents an individual SEQUENCE entry.
|
||||
|
||||
The ASN.1 definition for the NegoData structure is defined in `MS-CSSP 2.2.1.1 NegoData`_::
|
||||
|
||||
NegoData ::= SEQUENCE OF SEQUENCE {
|
||||
negoToken [0] OCTET STRING
|
||||
}
|
||||
|
||||
Args:
|
||||
nego_token: One or more SPNEGO tokens and all Kerberos or NTLM messages, as negotiated by SPNEGO.
|
||||
|
||||
Attributes:
|
||||
nego_token (bytes): See args.
|
||||
|
||||
.. _MS-CSSP 2.2.1.1 NegoData:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cssp/9664994d-0784-4659-b85b-83b8d54c2336
|
||||
"""
|
||||
|
||||
def __init__(self, nego_token: bytes) -> None:
|
||||
self.nego_token = nego_token
|
||||
|
||||
def pack(self) -> bytes:
|
||||
"""Packs the NegoData as a byte string."""
|
||||
return pack_asn1_sequence(
|
||||
[
|
||||
pack_asn1(TagClass.context_specific, True, 0, pack_asn1_octet_string(self.nego_token)),
|
||||
]
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def unpack(b_data: typing.Union[ASN1Value, bytes]) -> "NegoData":
|
||||
"""Unpacks the NegoData TLV value."""
|
||||
nego_data = unpack_sequence(b_data)
|
||||
nego_token = get_sequence_value(nego_data, 0, "NegoData", "negoToken", unpack_asn1_octet_string)
|
||||
|
||||
return NegoData(nego_token)
|
||||
|
||||
|
||||
class TSRequest:
|
||||
"""CredSSP TSRequest structure.
|
||||
|
||||
The TSRequest structure is the top-most structure used by the CredSSP client and CredSSP server. The TSRequest
|
||||
message is always sent over the TLS-encrypted channel between the client and server in a CredSSP protocol exchange.
|
||||
|
||||
The ASN.1 definition for the TSRequest structure is defined in `MS-CSSP 2.2.1 TSRequest`_::
|
||||
|
||||
TSRequest ::= SEQUENCE {
|
||||
version [0] INTEGER,
|
||||
negoTokens [1] NegoData OPTIONAL,
|
||||
authInfo [2] OCTET STRING OPTIONAL,
|
||||
pubKeyAuth [3] OCTET STRING OPTIONAL,
|
||||
errorCode [4] INTEGER OPTIONAL,
|
||||
clientNonce [5] OCTET STRING OPTIONAL
|
||||
}
|
||||
|
||||
Args:
|
||||
version: THe supported version of the CredSSP protocol.
|
||||
nego_tokens: A list of NegoData structures that contains te SPNEGO tokens.
|
||||
auth_info: The encrypted TSCredentials structure that contains the user's credentials to be delegated to the
|
||||
server.
|
||||
pub_key_auth: The encrypted public key used in the TLS handshake between the client and the server.
|
||||
error_code: The error code that represents the NTSTATUS failure code from the server.
|
||||
client_nonce: A 32-byte array of cryptograpically random bytes for the pub_key_auth hash computation (version
|
||||
or above).
|
||||
|
||||
Attributes:
|
||||
version (int): See args.
|
||||
nego_tokens (Optional[List[int]]): See args.
|
||||
auth_info (bytes): See args.
|
||||
pub_key_auth (bytes): See args.
|
||||
error_code (int): See args.
|
||||
client_nonce (bytes): See args.
|
||||
|
||||
.. _MS-CSSP 2.2.1 TSRequest:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cssp/9664994d-0784-4659-b85b-83b8d54c2336
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
version: int,
|
||||
nego_tokens: typing.Optional[typing.Union[NegoData, typing.List[NegoData]]] = None,
|
||||
auth_info: typing.Optional[bytes] = None,
|
||||
pub_key_auth: typing.Optional[bytes] = None,
|
||||
error_code: typing.Optional[int] = None,
|
||||
client_nonce: typing.Optional[bytes] = None,
|
||||
) -> None:
|
||||
self.version = version
|
||||
|
||||
if nego_tokens is not None and not isinstance(nego_tokens, list):
|
||||
nego_tokens = [nego_tokens]
|
||||
self.nego_tokens = nego_tokens
|
||||
|
||||
self.auth_info = auth_info
|
||||
self.pub_key_auth = pub_key_auth
|
||||
self.error_code = error_code
|
||||
self.client_nonce = client_nonce
|
||||
|
||||
def pack(self) -> bytes:
|
||||
"""Packs the TSRequest as a byte string."""
|
||||
elements = [pack_asn1(TagClass.context_specific, True, 0, pack_asn1_integer(self.version))]
|
||||
if self.nego_tokens:
|
||||
nego_tokens = [token.pack() for token in self.nego_tokens]
|
||||
elements.append(pack_asn1(TagClass.context_specific, True, 1, pack_asn1_sequence(nego_tokens)))
|
||||
|
||||
value_map: typing.List[typing.Tuple[int, typing.Any, typing.Callable]] = [
|
||||
(2, self.auth_info, pack_asn1_octet_string),
|
||||
(3, self.pub_key_auth, pack_asn1_octet_string),
|
||||
(4, self.error_code, pack_asn1_integer),
|
||||
(5, self.client_nonce, pack_asn1_octet_string),
|
||||
]
|
||||
for tag, value, pack_func in value_map:
|
||||
if value is not None:
|
||||
elements.append(pack_asn1(TagClass.context_specific, True, tag, pack_func(value)))
|
||||
|
||||
return pack_asn1_sequence(elements)
|
||||
|
||||
@staticmethod
|
||||
def unpack(b_data: typing.Union[ASN1Value, bytes]) -> "TSRequest":
|
||||
"""Unpacks the TSRequest TLV value."""
|
||||
request = unpack_sequence(b_data)
|
||||
|
||||
version = get_sequence_value(request, 0, "TSRequest", "version", unpack_asn1_integer)
|
||||
|
||||
nego_tokens = get_sequence_value(request, 1, "TSRequest", "negoTokens")
|
||||
if nego_tokens is not None:
|
||||
remaining_bytes = nego_tokens.b_data
|
||||
nego_tokens = []
|
||||
while remaining_bytes:
|
||||
nego_tokens.append(NegoData.unpack(remaining_bytes))
|
||||
remaining_bytes = unpack_asn1(remaining_bytes)[1]
|
||||
|
||||
auth_info = get_sequence_value(request, 2, "TSRequest", "authInfo", unpack_asn1_octet_string)
|
||||
pub_key_auth = get_sequence_value(request, 3, "TSRequest", "pubKeyAuth", unpack_asn1_octet_string)
|
||||
error_code = get_sequence_value(request, 4, "TSRequest", "errorCode", unpack_asn1_integer)
|
||||
client_nonce = get_sequence_value(request, 5, "TSRequest", "clientNonce", unpack_asn1_octet_string)
|
||||
|
||||
return TSRequest(
|
||||
version,
|
||||
nego_tokens=nego_tokens,
|
||||
auth_info=auth_info,
|
||||
pub_key_auth=pub_key_auth,
|
||||
error_code=error_code,
|
||||
client_nonce=client_nonce,
|
||||
)
|
||||
|
||||
|
||||
class TSCredentials:
|
||||
"""CredSSP TSCredentials structure.
|
||||
|
||||
The TSCredentials structure contains both the user's credentials that are delegated to the server and their type.
|
||||
|
||||
The ASN.1 definition for the TSCredentials structure is defined in `MS-CSSP 2.2.1.2 TSCredentials`_::
|
||||
|
||||
TSCredentials ::= SEQUENCE {
|
||||
credType [0] INTEGER,
|
||||
credentials [1] OCTET STRING
|
||||
}
|
||||
|
||||
Args:
|
||||
credentials: The credential structure; TSPasswordCreds, TSSmartCardCreds, TSRemoteGuardCreds.
|
||||
|
||||
Attributes:
|
||||
credentials (Union[TSPasswordCreds, TSSmartCardCreds, TSRemoteGuardCreds]): See args.
|
||||
|
||||
.. _MS-CSSP 2.2.1.2 TSCredentials:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cssp/94a1ab00-5500-42fd-8d3d-7a84e6c2cf03
|
||||
"""
|
||||
|
||||
def __init__(self, credentials: typing.Union["TSPasswordCreds", "TSSmartCardCreds", "TSRemoteGuardCreds"]) -> None:
|
||||
self.credentials = credentials
|
||||
|
||||
@property
|
||||
def cred_type(self) -> int:
|
||||
"""The credential type of credentials as an integer."""
|
||||
if isinstance(self.credentials, TSPasswordCreds):
|
||||
return 1
|
||||
|
||||
elif isinstance(self.credentials, TSSmartCardCreds):
|
||||
return 2
|
||||
|
||||
elif isinstance(self.credentials, TSRemoteGuardCreds):
|
||||
return 6
|
||||
|
||||
else:
|
||||
raise ValueError("Invalid credential type set")
|
||||
|
||||
def pack(self) -> bytes:
|
||||
"""Packs the TSCredentials as a byte string."""
|
||||
cred_type = self.cred_type
|
||||
credentials = self.credentials.pack()
|
||||
|
||||
return pack_asn1_sequence(
|
||||
[
|
||||
pack_asn1(TagClass.context_specific, True, 0, pack_asn1_integer(cred_type)),
|
||||
pack_asn1(TagClass.context_specific, True, 1, pack_asn1_octet_string(credentials)),
|
||||
]
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def unpack(b_data: typing.Union[ASN1Value, bytes]) -> "TSCredentials":
|
||||
"""Unpacks the TSCredentials TLV value."""
|
||||
credential = unpack_sequence(b_data)
|
||||
cred_type = get_sequence_value(credential, 0, "TSCredentials", "credType", unpack_asn1_integer)
|
||||
credentials_raw = get_sequence_value(credential, 1, "TSCredentials", "credentials", unpack_asn1_octet_string)
|
||||
|
||||
cred_class: typing.Optional[
|
||||
typing.Union[typing.Type[TSPasswordCreds], typing.Type[TSSmartCardCreds], typing.Type[TSRemoteGuardCreds]]
|
||||
] = {
|
||||
1: TSPasswordCreds,
|
||||
2: TSSmartCardCreds,
|
||||
6: TSRemoteGuardCreds,
|
||||
}.get(cred_type)
|
||||
if not cred_class:
|
||||
raise ValueError("Unknown credType %s in TSCredentials, cannot unpack" % cred_type)
|
||||
|
||||
credentials = cred_class.unpack(credentials_raw)
|
||||
return TSCredentials(credentials)
|
||||
|
||||
|
||||
class TSPasswordCreds:
|
||||
"""CredSSP TSPasswordCreds structure.
|
||||
|
||||
The TSPasswordCreds structure contains the user's password credentials that are delegated to the server.
|
||||
|
||||
The ASN.1 definition for the TSPasswordCreds structure is defined in `MS-CSSP 2.2.1.2.1 TSPasswordCreds`_::
|
||||
|
||||
TSPasswordCreds ::= SEQUENCE {
|
||||
domainName [0] OCTET STRING,
|
||||
userName [1] OCTET STRING,
|
||||
password [2] OCTET STRING
|
||||
}
|
||||
|
||||
Args:
|
||||
domain_name: The name of the user's account domain.
|
||||
username: The user's account name.
|
||||
password: The user's account password.
|
||||
|
||||
Attributes:
|
||||
domain_name (str): See args.
|
||||
username (str): See args.
|
||||
password (str): See args.
|
||||
|
||||
.. _MS-CSSP 2.2.1.2.1 TSPasswordCreds:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cssp/9664994d-0784-4659-b85b-83b8d54c2336
|
||||
"""
|
||||
|
||||
def __init__(self, domain_name: str, username: str, password: str) -> None:
|
||||
self.domain_name = domain_name
|
||||
self.username = username
|
||||
self.password = password
|
||||
|
||||
def pack(self) -> bytes:
|
||||
"""Packs the TSPasswordCreds as a byte string."""
|
||||
elements = []
|
||||
for idx, value in enumerate([self.domain_name, self.username, self.password]):
|
||||
b_value = value.encode("utf-16-le")
|
||||
elements.append(pack_asn1(TagClass.context_specific, True, idx, pack_asn1_octet_string(b_value)))
|
||||
|
||||
return pack_asn1_sequence(elements)
|
||||
|
||||
@staticmethod
|
||||
def unpack(b_data: typing.Union[ASN1Value, bytes]) -> "TSPasswordCreds":
|
||||
"""Unpacks the TSPasswordCreds TLV value."""
|
||||
creds = unpack_sequence(b_data)
|
||||
|
||||
domain_name = unpack_text_field(creds, 0, "TSPasswordCreds", "domainName") or ""
|
||||
username = unpack_text_field(creds, 1, "TSPasswordCreds", "userName") or ""
|
||||
password = unpack_text_field(creds, 2, "TSPasswordCreds", "password") or ""
|
||||
|
||||
return TSPasswordCreds(domain_name, username, password)
|
||||
|
||||
|
||||
class TSSmartCardCreds:
|
||||
"""CredSSP TSSmartCardCreds structure.
|
||||
|
||||
The TSSmartCardCreds structure contains the user's smart card credentials that are delegated to the server.
|
||||
|
||||
The ASN.1 definition for the TSSmartCardCreds structure is defined in `MS-CSSP 2.2.1.2.2 TSSmartCardCreds`_::
|
||||
|
||||
TSSmartCardCreds ::= SEQUENCE {
|
||||
pin [0] OCTET STRING,
|
||||
cspData [1] TSCspDataDetail,
|
||||
userHint [2] OCTET STRING OPTIONAL,
|
||||
domainHint [3] OCTET STRING OPTIONAL
|
||||
}
|
||||
|
||||
Args:
|
||||
pin: THe user's smart card PIN.
|
||||
csp_data: Info about the cryptographic service provider (CSP).
|
||||
user_hint: The user's account hint.
|
||||
domain_hint: The user's domain name to which the user's account belongs.
|
||||
|
||||
Attributes:
|
||||
pin (str): See args.
|
||||
csp_data (TSCspDataDetail): See args.
|
||||
user_hint (Optional[str]): See args.
|
||||
domain_hint (Optional[str]): See args.
|
||||
|
||||
.. _MS-CSSP 2.2.1.2.2 TSSmartCardCreds:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cssp/4251d165-cf01-4513-a5d8-39ee4a98b7a4
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
pin: str,
|
||||
csp_data: "TSCspDataDetail",
|
||||
user_hint: typing.Optional[str] = None,
|
||||
domain_hint: typing.Optional[str] = None,
|
||||
) -> None:
|
||||
self.pin = pin
|
||||
self.csp_data = csp_data
|
||||
self.user_hint = user_hint
|
||||
self.domain_hint = domain_hint
|
||||
|
||||
def pack(self) -> bytes:
|
||||
"""Packs the TSSmartCardCreds as a byte string."""
|
||||
elements = [
|
||||
pack_asn1(TagClass.context_specific, True, 0, pack_asn1_octet_string(self.pin.encode("utf-16-le"))),
|
||||
pack_asn1(TagClass.context_specific, True, 1, self.csp_data.pack()),
|
||||
]
|
||||
for idx, value in [(2, self.user_hint), (3, self.domain_hint)]:
|
||||
if value:
|
||||
b_value = value.encode("utf-16-le")
|
||||
elements.append(pack_asn1(TagClass.context_specific, True, idx, pack_asn1_octet_string(b_value)))
|
||||
|
||||
return pack_asn1_sequence(elements)
|
||||
|
||||
@staticmethod
|
||||
def unpack(b_data: typing.Union[ASN1Value, bytes]) -> "TSSmartCardCreds":
|
||||
"""Unpacks the TSSmartCardCreds TLV value."""
|
||||
creds = unpack_sequence(b_data)
|
||||
|
||||
pin = unpack_text_field(creds, 0, "TSSmartCardCreds", "pin") or ""
|
||||
csp_data = get_sequence_value(creds, 1, "TSSmartCardCreds", "cspData", TSCspDataDetail.unpack)
|
||||
user_hint = unpack_text_field(creds, 2, "TSSmartCardCreds", "userHint", default=None)
|
||||
domain_hint = unpack_text_field(creds, 3, "TSSmartCardCreds", "domainHint", default=None)
|
||||
|
||||
return TSSmartCardCreds(pin, csp_data, user_hint, domain_hint)
|
||||
|
||||
|
||||
class TSCspDataDetail:
|
||||
"""CredSSP TSCspDataDetail structure.
|
||||
|
||||
The TSCspDataDetail structure contains CSP information used during smart card logon.
|
||||
|
||||
The ASN.1 definition for the TSCspDataDetail structure is defined in `MS-CSSP 2.2.1.2.2.1 TSCspDataDetail`_::
|
||||
|
||||
TSCspDataDetail ::= SEQUENCE {
|
||||
keySpec [0] INTEGER,
|
||||
cardName [1] OCTET STRING OPTIONAL,
|
||||
readerName [2] OCTET STRING OPTIONAL,
|
||||
containerName [3] OCTET STRING OPTIONAL,
|
||||
cspName [4] OCTET STRING OPTIONAL
|
||||
}
|
||||
|
||||
Args:
|
||||
key_spec: The specification of the user's smart card.
|
||||
card_name: The name of the smart card.
|
||||
reader_name: The name of the smart card reader.
|
||||
container_name: The name of the certificate container.
|
||||
csp_name: The name of the CSP.
|
||||
|
||||
Attributes:
|
||||
key_spec (int): See args.
|
||||
card_name (Optional[str]): See args.
|
||||
reader_name (Optional[str]): See args.
|
||||
container_name (Optional[str]): See args.
|
||||
csp_name (Optional[str]): See args.
|
||||
|
||||
.. _MS-CSSP 2.2.1.2.2.1 TSCspDataDetail:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cssp/34ee27b3-5791-43bb-9201-076054b58123
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
key_spec: int,
|
||||
card_name: typing.Optional[str] = None,
|
||||
reader_name: typing.Optional[str] = None,
|
||||
container_name: typing.Optional[str] = None,
|
||||
csp_name: typing.Optional[str] = None,
|
||||
) -> None:
|
||||
self.key_spec = key_spec
|
||||
self.card_name = card_name
|
||||
self.reader_name = reader_name
|
||||
self.container_name = container_name
|
||||
self.csp_name = csp_name
|
||||
|
||||
def pack(self) -> bytes:
|
||||
"""Packs the TSCspDataDetail as a byte string."""
|
||||
elements = [
|
||||
pack_asn1(TagClass.context_specific, True, 0, pack_asn1_integer(self.key_spec)),
|
||||
]
|
||||
|
||||
value_map = [
|
||||
(1, self.card_name),
|
||||
(2, self.reader_name),
|
||||
(3, self.container_name),
|
||||
(4, self.csp_name),
|
||||
]
|
||||
for idx, value in value_map:
|
||||
if value:
|
||||
b_value = value.encode("utf-16-le")
|
||||
elements.append(pack_asn1(TagClass.context_specific, True, idx, pack_asn1_octet_string(b_value)))
|
||||
|
||||
return pack_asn1_sequence(elements)
|
||||
|
||||
@staticmethod
|
||||
def unpack(b_data: typing.Union[ASN1Value, bytes]) -> "TSCspDataDetail":
|
||||
"""Unpacks the TSCspDataDetail TLV value."""
|
||||
csp_data = unpack_sequence(b_data)
|
||||
|
||||
key_spec = get_sequence_value(csp_data, 0, "TSCspDataDetail", "keySpec", unpack_asn1_integer)
|
||||
card_name = unpack_text_field(csp_data, 1, "TSCspDataDetail", "cardName", default=None)
|
||||
reader_name = unpack_text_field(csp_data, 2, "TSCspDataDetail", "readerName", default=None)
|
||||
container_name = unpack_text_field(csp_data, 3, "TSCspDataDetail", "containerName", default=None)
|
||||
csp_name = unpack_text_field(csp_data, 4, "TSCspDataDetail", "cspName", default=None)
|
||||
|
||||
return TSCspDataDetail(key_spec, card_name, reader_name, container_name, csp_name)
|
||||
|
||||
|
||||
class TSRemoteGuardCreds:
|
||||
"""CredSSP TSRemoteGuardCreds structure.
|
||||
|
||||
The TSRemoteGuardCreds structure contains a logon credential and supplemental credentials provided by security
|
||||
packages. The format of the individual credentials depends on the packages that provided them.
|
||||
|
||||
The ASN.1 definition for the TSRemoteGuardCreds structure is defined in `MS-CSSP 2.2.1.2.3 TSRemoteGuardCreds`_::
|
||||
|
||||
TSRemoteGuardCreds ::= SEQUENCE{
|
||||
logonCred [0] TSRemoteGuardPackageCred,
|
||||
supplementalCreds [1] SEQUENCE OF TSRemoteGuardPackageCred OPTIONAL,
|
||||
}
|
||||
|
||||
Args:
|
||||
logon_cred: The logon credential for the user.
|
||||
supplemental_creds: Optional supplemental credentials for other security packages.
|
||||
|
||||
Attributes:
|
||||
logon_cred (TSRemoteGuardPackageCred): See args.
|
||||
supplemental_creds (List[TSRemoteGuardPackageCred]): See args.
|
||||
|
||||
.. _MS-CSSP 2.2.1.2.3 TSRemoteGuardCreds:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cssp/7ef8229c-44ea-4c1b-867f-00369b882b38
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
logon_cred: "TSRemoteGuardPackageCred",
|
||||
supplemental_creds: typing.Optional[
|
||||
typing.Union["TSRemoteGuardPackageCred", typing.List["TSRemoteGuardPackageCred"]]
|
||||
] = None,
|
||||
) -> None:
|
||||
self.logon_cred = logon_cred
|
||||
|
||||
if supplemental_creds is not None and not isinstance(supplemental_creds, list):
|
||||
supplemental_creds = [supplemental_creds]
|
||||
self.supplemental_creds = supplemental_creds
|
||||
|
||||
def pack(self) -> bytes:
|
||||
"""Packs the TSRemoteGuardCreds as a byte string."""
|
||||
elements = [pack_asn1(TagClass.context_specific, True, 0, self.logon_cred.pack())]
|
||||
if self.supplemental_creds is not None:
|
||||
supplemental_creds = [cred.pack() for cred in self.supplemental_creds]
|
||||
elements.append(pack_asn1(TagClass.context_specific, True, 1, pack_asn1_sequence(supplemental_creds)))
|
||||
|
||||
return pack_asn1_sequence(elements)
|
||||
|
||||
@staticmethod
|
||||
def unpack(b_data: typing.Union[ASN1Value, bytes]) -> "TSRemoteGuardCreds":
|
||||
"""Unpacks the TSRemoteGuardCreds TLV value."""
|
||||
cred = unpack_sequence(b_data)
|
||||
logon_cred = get_sequence_value(cred, 0, "TSRemoteGuardCreds", "logonCred", TSRemoteGuardPackageCred.unpack)
|
||||
|
||||
raw_supplemental_creds = get_sequence_value(cred, 1, "TSRemoteGuardCreds", "supplementalCreds")
|
||||
if raw_supplemental_creds:
|
||||
supplemental_creds = []
|
||||
remaining_bytes = raw_supplemental_creds.b_data
|
||||
while remaining_bytes:
|
||||
supplemental_creds.append(TSRemoteGuardPackageCred.unpack(remaining_bytes))
|
||||
remaining_bytes = unpack_asn1(remaining_bytes)[1]
|
||||
|
||||
else:
|
||||
supplemental_creds = None
|
||||
|
||||
return TSRemoteGuardCreds(logon_cred, supplemental_creds)
|
||||
|
||||
|
||||
class TSRemoteGuardPackageCred:
|
||||
"""CredSSP TSRemoteGuardPackageCred structure.
|
||||
|
||||
The TSRemoteGuardPackageCred structure contains credentials for a specific security package.
|
||||
|
||||
The ASN.1 definition for the TSRemoteGuardPackageCred structure is defined in
|
||||
`MS-CSSP 2.2.1.2.3.1 TSRemoteGuardPackageCred`_::
|
||||
|
||||
TSRemoteGuardPackageCred ::= SEQUENCE{
|
||||
packageName [0] OCTET STRING,
|
||||
credBuffer [1] OCTET STRING,
|
||||
}
|
||||
|
||||
Args:
|
||||
package_name: The name of the packages for which these credentials are intended.
|
||||
cred_buffer: The credentials in a format specified by the CredSSP server.
|
||||
|
||||
Attributes:
|
||||
package_name (str): See args.
|
||||
cred_buffer (bytes): See args.
|
||||
|
||||
.. _MS-CSSP 2.2.1.2.3.1 TSRemoteGuardPackageCred:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cssp/173eee44-1a2c-463f-b909-c15db01e68d7
|
||||
"""
|
||||
|
||||
def __init__(self, package_name: str, cred_buffer: bytes) -> None:
|
||||
self.package_name = package_name
|
||||
self.cred_buffer = cred_buffer
|
||||
|
||||
def pack(self) -> bytes:
|
||||
"""Packs the TSRemoteGuardPackageCred as a byte string."""
|
||||
b_package_name = self.package_name.encode("utf-16-le")
|
||||
return pack_asn1_sequence(
|
||||
[
|
||||
pack_asn1(TagClass.context_specific, True, 0, pack_asn1_octet_string(b_package_name)),
|
||||
pack_asn1(TagClass.context_specific, True, 1, pack_asn1_octet_string(self.cred_buffer)),
|
||||
]
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def unpack(b_data: typing.Union[ASN1Value, bytes]) -> "TSRemoteGuardPackageCred":
|
||||
"""Unpacks the TSRemoteGuardPackageCred TLV value."""
|
||||
package_cred = unpack_sequence(b_data)
|
||||
package_name = unpack_text_field(package_cred, 0, "TSRemoteGuardPackageCred", "packageName") or ""
|
||||
cred_buffer = get_sequence_value(
|
||||
package_cred, 1, "TSRemoteGuardPackageCred", "credBuffer", unpack_asn1_octet_string
|
||||
)
|
||||
|
||||
return TSRemoteGuardPackageCred(package_name, cred_buffer)
|
||||
628
env/lib/python3.12/site-packages/spnego/_gss.py
vendored
Normal file
628
env/lib/python3.12/site-packages/spnego/_gss.py
vendored
Normal file
@@ -0,0 +1,628 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import base64
|
||||
import copy
|
||||
import logging
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from spnego._context import (
|
||||
IOV,
|
||||
ContextProxy,
|
||||
ContextReq,
|
||||
GSSMech,
|
||||
IOVUnwrapResult,
|
||||
IOVWrapResult,
|
||||
SecPkgContextSizes,
|
||||
UnwrapResult,
|
||||
WinRMWrapResult,
|
||||
WrapResult,
|
||||
wrap_system_error,
|
||||
)
|
||||
from spnego._credential import (
|
||||
Credential,
|
||||
CredentialCache,
|
||||
KerberosCCache,
|
||||
KerberosKeytab,
|
||||
Password,
|
||||
unify_credentials,
|
||||
)
|
||||
from spnego._text import to_bytes, to_text
|
||||
from spnego.channel_bindings import GssChannelBindings
|
||||
from spnego.exceptions import GSSError as NativeError
|
||||
from spnego.exceptions import (
|
||||
InvalidCredentialError,
|
||||
NegotiateOptions,
|
||||
NoContextError,
|
||||
SpnegoError,
|
||||
)
|
||||
from spnego.iov import BufferType, IOVBuffer, IOVResBuffer
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
HAS_GSSAPI = True
|
||||
GSSAPI_IMP_ERR = None
|
||||
try:
|
||||
import gssapi
|
||||
import krb5
|
||||
from gssapi.raw import ChannelBindings, GSSError, inquire_sec_context_by_oid, set_cred_option
|
||||
from gssapi.raw import exceptions as gss_errors
|
||||
except ImportError as e:
|
||||
GSSAPI_IMP_ERR = str(e)
|
||||
HAS_GSSAPI = False
|
||||
log.debug("Python gssapi not available, cannot use any GSSAPIProxy protocols: %s" % e)
|
||||
|
||||
|
||||
HAS_IOV = True
|
||||
GSSAPI_IOV_IMP_ERR = None
|
||||
try:
|
||||
from gssapi.raw import IOV as GSSIOV
|
||||
from gssapi.raw import IOVBuffer as GSSIOVBuffer
|
||||
from gssapi.raw import IOVBufferType, unwrap_iov, wrap_iov, wrap_iov_length
|
||||
except ImportError as e:
|
||||
GSSAPI_IOV_IMP_ERR = str(e)
|
||||
HAS_IOV = False
|
||||
log.debug("Python gssapi IOV extension not available: %s" % GSSAPI_IOV_IMP_ERR)
|
||||
|
||||
_GSS_C_INQ_SSPI_SESSION_KEY = "1.2.840.113554.1.2.2.5.5"
|
||||
|
||||
_GSS_KRB5_CRED_NO_CI_FLAGS_X = "1.2.752.43.13.29"
|
||||
|
||||
|
||||
def _create_iov_result(iov: "GSSIOV") -> typing.Tuple[IOVResBuffer, ...]:
|
||||
"""Converts GSSAPI IOV buffer to generic IOVBuffer result."""
|
||||
buffers = []
|
||||
for i in iov:
|
||||
buffer_entry = IOVResBuffer(type=BufferType(i.type), data=i.value)
|
||||
buffers.append(buffer_entry)
|
||||
|
||||
return tuple(buffers)
|
||||
|
||||
|
||||
def _get_gssapi_credential(
|
||||
mech: "gssapi.OID",
|
||||
usage: str,
|
||||
credentials: typing.List[Credential],
|
||||
context_req: typing.Optional[ContextReq] = None,
|
||||
) -> typing.Optional["gssapi.creds.Credentials"]:
|
||||
"""Gets the GSSAPI credential.
|
||||
|
||||
Will get a GSSAPI credential for the mech specified. If the username and password is specified then a new
|
||||
set of credentials are explicitly required for the mech specified. Otherwise the credentials are retrieved based on
|
||||
the credential type specified.
|
||||
|
||||
Args:
|
||||
mech: The mech OID to get the credentials for, only Kerberos is supported.
|
||||
usage: Either `initiate` for a client context or `accept` for a server context.
|
||||
credentials: List of credentials to retreive from.
|
||||
context_req: Context requirement flags that can control how the credential is retrieved.
|
||||
|
||||
Returns:
|
||||
gssapi.creds.Credentials: The credential set that was created/retrieved.
|
||||
"""
|
||||
name_type = getattr(gssapi.NameType, "user" if usage == "initiate" else "hostbased_service")
|
||||
forwardable = bool(context_req and (context_req & ContextReq.delegate or context_req & ContextReq.delegate_policy))
|
||||
|
||||
for cred in credentials:
|
||||
if isinstance(cred, CredentialCache):
|
||||
principal = None
|
||||
if cred.username:
|
||||
principal = gssapi.Name(base=cred.username, name_type=name_type)
|
||||
|
||||
elif usage == "initiate":
|
||||
# https://github.com/jborean93/pyspnego/issues/15
|
||||
# Using None as a credential when creating the sec context is better than getting the default
|
||||
# credential as the former takes into account the target SPN when selecting the principal to use.
|
||||
return None
|
||||
|
||||
gss_cred = gssapi.Credentials(name=principal, usage=usage, mechs=[mech])
|
||||
|
||||
# We don't need to check the actual lifetime, just trying to get the valid will have gssapi check the
|
||||
# lifetime and raise an ExpiredCredentialsError if it is expired.
|
||||
_ = gss_cred.lifetime
|
||||
|
||||
return gss_cred
|
||||
|
||||
elif isinstance(cred, KerberosCCache):
|
||||
if usage != "initiate":
|
||||
log.debug("Skipping %s as it can only be used for an initiate Kerberos context", cred)
|
||||
continue
|
||||
|
||||
ctx = krb5.init_context()
|
||||
ccache = krb5.cc_resolve(ctx, to_bytes(cred.ccache))
|
||||
krb5_principal: typing.Optional[krb5.Principal] = None
|
||||
if cred.principal:
|
||||
krb5_principal = krb5.parse_name_flags(ctx, to_bytes(cred.principal))
|
||||
|
||||
return gssapi.Credentials(base=_gss_acquire_cred_from_ccache(ccache, krb5_principal), usage=usage)
|
||||
|
||||
elif isinstance(cred, (KerberosKeytab, Password)):
|
||||
if usage != "initiate":
|
||||
log.debug("Skipping %s as it can only be used for an initiate Kerberos context", cred)
|
||||
continue
|
||||
|
||||
if isinstance(cred, KerberosKeytab):
|
||||
username = cred.principal or ""
|
||||
password = to_bytes(cred.keytab)
|
||||
is_keytab = True
|
||||
else:
|
||||
username = cred.username
|
||||
password = _encode_kerb_password(cred.password)
|
||||
is_keytab = False
|
||||
|
||||
raw_cred = _kinit(
|
||||
to_bytes(username),
|
||||
password,
|
||||
forwardable=forwardable,
|
||||
is_keytab=is_keytab,
|
||||
)
|
||||
|
||||
return gssapi.Credentials(base=raw_cred, usage=usage)
|
||||
|
||||
else:
|
||||
log.debug("Skipping credential %s as it does not support required mech type", cred)
|
||||
continue
|
||||
|
||||
raise InvalidCredentialError(context_msg="No applicable credentials available")
|
||||
|
||||
|
||||
def _gss_sasl_description(mech: "gssapi.OID") -> typing.Optional[bytes]:
|
||||
"""Attempts to get the SASL description of the mech specified."""
|
||||
try:
|
||||
res = _gss_sasl_description.result # type: ignore
|
||||
return res[mech.dotted_form]
|
||||
|
||||
except (AttributeError, KeyError):
|
||||
res = getattr(_gss_sasl_description, "result", {})
|
||||
|
||||
try:
|
||||
sasl_desc = gssapi.raw.inquire_saslname_for_mech(mech).mech_description
|
||||
except Exception as e:
|
||||
log.debug("gss_inquire_saslname_for_mech(%s) failed: %s" % (mech.dotted_form, str(e)))
|
||||
sasl_desc = None
|
||||
|
||||
res[mech.dotted_form] = sasl_desc
|
||||
_gss_sasl_description.result = res # type: ignore
|
||||
return _gss_sasl_description(mech)
|
||||
|
||||
|
||||
def _kinit(
|
||||
username: bytes,
|
||||
password: bytes,
|
||||
forwardable: typing.Optional[bool] = None,
|
||||
is_keytab: bool = False,
|
||||
) -> "gssapi.raw.Creds":
|
||||
"""Gets a Kerberos credential.
|
||||
|
||||
This will get the GSSAPI credential that contains the Kerberos TGT inside
|
||||
it. This is used instead of gss_acquire_cred_with_password as the latter
|
||||
does not expose a way to request a forwardable ticket or to retrieve a TGT
|
||||
from a keytab. This way makes it possible to request whatever is needed
|
||||
before making it usable in GSSAPI.
|
||||
|
||||
Args:
|
||||
username: The username to get the credential for.
|
||||
password: The password to use to retrieve the credential.
|
||||
forwardable: Whether to request a forwardable credential.
|
||||
is_keytab: Whether password is a keytab or just a password.
|
||||
|
||||
Returns:
|
||||
gssapi.raw.Creds: The GSSAPI credential for the Kerberos mech.
|
||||
"""
|
||||
ctx = krb5.init_context()
|
||||
|
||||
kt: typing.Optional[krb5.KeyTab] = None
|
||||
princ: typing.Optional[krb5.Principal] = None
|
||||
if is_keytab:
|
||||
kt = krb5.kt_resolve(ctx, password)
|
||||
|
||||
# If the username was not specified get the principal of the first entry.
|
||||
if not username:
|
||||
# The principal handle is deleted once the entry is deallocated. Make sure it is stored in a var before
|
||||
# being copied.
|
||||
first_entry = list(kt)[0]
|
||||
princ = copy.copy(first_entry.principal)
|
||||
|
||||
if not princ:
|
||||
princ = krb5.parse_name_flags(ctx, username)
|
||||
|
||||
init_opt = krb5.get_init_creds_opt_alloc(ctx)
|
||||
|
||||
if hasattr(krb5, "get_init_creds_opt_set_default_flags"):
|
||||
# Heimdal requires this to be set in order to load the default options from krb5.conf. This follows the same
|
||||
# code that it's own gss_acquire_cred_with_password does.
|
||||
realm = krb5.principal_get_realm(ctx, princ)
|
||||
krb5.get_init_creds_opt_set_default_flags(ctx, init_opt, b"gss_krb5", realm)
|
||||
|
||||
krb5.get_init_creds_opt_set_canonicalize(init_opt, True)
|
||||
if forwardable is not None:
|
||||
krb5.get_init_creds_opt_set_forwardable(init_opt, forwardable)
|
||||
|
||||
if kt:
|
||||
cred = krb5.get_init_creds_keytab(ctx, princ, init_opt, keytab=kt)
|
||||
else:
|
||||
cred = krb5.get_init_creds_password(ctx, princ, init_opt, password=password)
|
||||
|
||||
mem_ccache = krb5.cc_new_unique(ctx, b"MEMORY")
|
||||
krb5.cc_initialize(ctx, mem_ccache, cred.client)
|
||||
krb5.cc_store_cred(ctx, mem_ccache, cred)
|
||||
|
||||
return _gss_acquire_cred_from_ccache(mem_ccache, None)
|
||||
|
||||
|
||||
def _gss_acquire_cred_from_ccache(
|
||||
ccache: "krb5.CCache",
|
||||
principal: typing.Optional["krb5.Principal"],
|
||||
) -> "gssapi.raw.Creds":
|
||||
"""Acquire GSSAPI credential from CCache.
|
||||
|
||||
Args:
|
||||
ccache: The CCache to acquire the credential from.
|
||||
principal: The optional principal to acquire the cred for.
|
||||
|
||||
Returns:
|
||||
gssapi.raw.Creds: The GSSAPI credentials from the ccache.
|
||||
"""
|
||||
# acquire_cred_from is less dangerous than krb5_import_cred which uses a raw pointer to access the ccache. Heimdal
|
||||
# has only recently added this API (not in a release as of 2021) so there's a fallback to the latter API.
|
||||
if hasattr(gssapi.raw, "acquire_cred_from"):
|
||||
kerberos = gssapi.OID.from_int_seq(GSSMech.kerberos.value)
|
||||
name = None
|
||||
if principal:
|
||||
name = gssapi.Name(base=to_text(principal.name), name_type=gssapi.NameType.user)
|
||||
|
||||
ccache_name = ccache.name or b""
|
||||
if ccache.cache_type:
|
||||
ccache_name = ccache.cache_type + b":" + ccache_name
|
||||
|
||||
return gssapi.raw.acquire_cred_from(
|
||||
{b"ccache": ccache_name},
|
||||
name=name,
|
||||
mechs=[kerberos],
|
||||
usage="initiate",
|
||||
).creds
|
||||
|
||||
else:
|
||||
gssapi_creds = gssapi.raw.Creds()
|
||||
gssapi.raw.krb5_import_cred(
|
||||
gssapi_creds, cache=ccache.addr, keytab_principal=principal.addr if principal else None
|
||||
)
|
||||
|
||||
return gssapi_creds
|
||||
|
||||
|
||||
def _encode_kerb_password(
|
||||
value: str,
|
||||
) -> bytes:
|
||||
"""Encode string to use for Kerberos passwords.
|
||||
|
||||
Encodes the input string to use with Kerberos functions as a password. This
|
||||
is a special encoding method to ensure that any invalid surrogate chars are
|
||||
encoded as the replacement char U+FFFD. This is needed when dealing with
|
||||
randomly generated passwords like gMSA or machine accounts. The raw UTF-16
|
||||
bytes can be encoded in a string with the following:
|
||||
|
||||
b"...".decode("utf-16-le", errors="surrogatepass")
|
||||
|
||||
The invalid surrogate pairs in the UTF-16 byte sequence will be preserved
|
||||
in the str value allowing this function to replace it as needed. This
|
||||
means the value can be used with both NTLM and Kerberos authentication with
|
||||
the same value.
|
||||
|
||||
Args:
|
||||
value: The string to encode to bytes.
|
||||
|
||||
Returns:
|
||||
bytes: The encoded string value.
|
||||
"""
|
||||
b_data = []
|
||||
for c in value:
|
||||
try:
|
||||
b_data.append(c.encode("utf-8", errors="strict"))
|
||||
except UnicodeEncodeError:
|
||||
b_data.append(b"\xef\xbf\xbd")
|
||||
|
||||
return b"".join(b_data)
|
||||
|
||||
|
||||
class GSSAPIProxy(ContextProxy):
|
||||
"""GSSAPI proxy class for GSSAPI on Linux.
|
||||
|
||||
This proxy class for GSSAPI exposes GSSAPI calls into a common interface for Kerberos authentication. This context
|
||||
uses the Python gssapi library to interface with the gss_* calls to provider Kerberos.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
username: typing.Optional[typing.Union[str, Credential, typing.List[Credential]]] = None,
|
||||
password: typing.Optional[str] = None,
|
||||
hostname: typing.Optional[str] = None,
|
||||
service: typing.Optional[str] = None,
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
context_req: ContextReq = ContextReq.default,
|
||||
usage: str = "initiate",
|
||||
protocol: str = "kerberos",
|
||||
options: NegotiateOptions = NegotiateOptions.none,
|
||||
**kwargs: typing.Any,
|
||||
) -> None:
|
||||
if not HAS_GSSAPI:
|
||||
raise ImportError("GSSAPIProxy requires the Python gssapi library: %s" % GSSAPI_IMP_ERR)
|
||||
|
||||
credentials = unify_credentials(username, password)
|
||||
super(GSSAPIProxy, self).__init__(
|
||||
credentials, hostname, service, channel_bindings, context_req, usage, protocol, options
|
||||
)
|
||||
|
||||
self._mech = gssapi.OID.from_int_seq(GSSMech.kerberos.value)
|
||||
|
||||
gssapi_credential = kwargs.get("_gssapi_credential", None)
|
||||
if not gssapi_credential:
|
||||
try:
|
||||
gssapi_credential = _get_gssapi_credential(
|
||||
self._mech,
|
||||
self.usage,
|
||||
credentials=credentials,
|
||||
context_req=context_req,
|
||||
)
|
||||
except GSSError as gss_err:
|
||||
raise SpnegoError(base_error=gss_err, context_msg="Getting GSSAPI credential") from gss_err
|
||||
|
||||
if context_req & ContextReq.no_integrity and self.usage == "initiate":
|
||||
if gssapi_credential is None:
|
||||
gssapi_credential = gssapi.Credentials(usage=self.usage, mechs=[self._mech])
|
||||
|
||||
set_cred_option(
|
||||
gssapi.OID.from_int_seq(_GSS_KRB5_CRED_NO_CI_FLAGS_X),
|
||||
gssapi_credential,
|
||||
)
|
||||
|
||||
self._credential = gssapi_credential
|
||||
self._context: typing.Optional[gssapi.SecurityContext] = None
|
||||
|
||||
@classmethod
|
||||
def available_protocols(cls, options: typing.Optional[NegotiateOptions] = None) -> typing.List[str]:
|
||||
# We can't offer Kerberos if the caller requires WinRM wrapping and IOV isn't available.
|
||||
avail = []
|
||||
if not (options and options & NegotiateOptions.wrapping_winrm and not HAS_IOV):
|
||||
avail.append("kerberos")
|
||||
|
||||
return avail
|
||||
|
||||
@classmethod
|
||||
def iov_available(cls) -> bool:
|
||||
return HAS_IOV
|
||||
|
||||
@property
|
||||
def client_principal(self) -> typing.Optional[str]:
|
||||
# Looks like a bug in python-gssapi where the value still has the terminating null char.
|
||||
if self._context and self.usage == "accept":
|
||||
return to_text(self._context.initiator_name).rstrip("\x00")
|
||||
else:
|
||||
return None
|
||||
|
||||
@property
|
||||
def complete(self) -> bool:
|
||||
return self._context is not None and self._context.complete
|
||||
|
||||
@property
|
||||
def negotiated_protocol(self) -> typing.Optional[str]:
|
||||
return "kerberos"
|
||||
|
||||
@property
|
||||
@wrap_system_error(NativeError, "Retrieving session key")
|
||||
def session_key(self) -> bytes:
|
||||
if self._context:
|
||||
return inquire_sec_context_by_oid(self._context, gssapi.OID.from_int_seq(_GSS_C_INQ_SSPI_SESSION_KEY))[0]
|
||||
else:
|
||||
raise NoContextError(context_msg="Retrieving session key failed as no context was initialized")
|
||||
|
||||
def new_context(self) -> "GSSAPIProxy":
|
||||
return GSSAPIProxy(
|
||||
hostname=self._hostname,
|
||||
service=self._service,
|
||||
channel_bindings=self.channel_bindings,
|
||||
context_req=self.context_req,
|
||||
usage=self.usage,
|
||||
protocol=self.protocol,
|
||||
options=self.options,
|
||||
_gssapi_credential=self._credential,
|
||||
)
|
||||
|
||||
@wrap_system_error(NativeError, "Processing security token")
|
||||
def step(
|
||||
self,
|
||||
in_token: typing.Optional[bytes] = None,
|
||||
*,
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
) -> typing.Optional[bytes]:
|
||||
if not self._is_wrapped:
|
||||
log.debug("GSSAPI step input: %s", base64.b64encode(in_token or b"").decode())
|
||||
|
||||
if not self._context:
|
||||
context_kwargs: typing.Dict[str, typing.Any] = {}
|
||||
|
||||
channel_bindings = channel_bindings or self.channel_bindings
|
||||
if channel_bindings:
|
||||
context_kwargs["channel_bindings"] = ChannelBindings(
|
||||
initiator_address_type=channel_bindings.initiator_addrtype,
|
||||
initiator_address=channel_bindings.initiator_address,
|
||||
acceptor_address_type=channel_bindings.acceptor_addrtype,
|
||||
acceptor_address=channel_bindings.acceptor_address,
|
||||
application_data=channel_bindings.application_data,
|
||||
)
|
||||
|
||||
if self.usage == "initiate":
|
||||
spn = "%s@%s" % (self._service or "host", self._hostname or "unspecified")
|
||||
context_kwargs["name"] = gssapi.Name(spn, name_type=gssapi.NameType.hostbased_service)
|
||||
context_kwargs["mech"] = self._mech
|
||||
context_kwargs["flags"] = self._context_req
|
||||
|
||||
self._context = gssapi.SecurityContext(creds=self._credential, usage=self.usage, **context_kwargs)
|
||||
|
||||
out_token = self._context.step(in_token)
|
||||
|
||||
try:
|
||||
self._context_attr = int(self._context.actual_flags)
|
||||
except gss_errors.MissingContextError: # pragma: no cover
|
||||
# MIT krb5 before 1.14.x will raise this error if the context isn't
|
||||
# complete. We should only treat it as an error if it happens when
|
||||
# the context is complete (last step).
|
||||
# https://github.com/jborean93/pyspnego/issues/55
|
||||
if self._context.complete:
|
||||
raise
|
||||
|
||||
if not self._is_wrapped:
|
||||
log.debug("GSSAPI step output: %s", base64.b64encode(out_token or b"").decode())
|
||||
|
||||
return out_token
|
||||
|
||||
@wrap_system_error(NativeError, "Getting context sizes")
|
||||
def query_message_sizes(self) -> SecPkgContextSizes:
|
||||
if not self._context:
|
||||
raise NoContextError(context_msg="Cannot get message sizes until context has been established")
|
||||
|
||||
iov = GSSIOV(
|
||||
IOVBufferType.header,
|
||||
b"",
|
||||
std_layout=False,
|
||||
)
|
||||
wrap_iov_length(self._context, iov)
|
||||
return SecPkgContextSizes(header=len(iov[0].value or b""))
|
||||
|
||||
@wrap_system_error(NativeError, "Wrapping data")
|
||||
def wrap(self, data: bytes, encrypt: bool = True, qop: typing.Optional[int] = None) -> WrapResult:
|
||||
if not self._context:
|
||||
raise NoContextError(context_msg="Cannot wrap until context has been established")
|
||||
res = gssapi.raw.wrap(self._context, data, confidential=encrypt, qop=qop)
|
||||
|
||||
return WrapResult(data=res.message, encrypted=res.encrypted)
|
||||
|
||||
@wrap_system_error(NativeError, "Wrapping IOV buffer")
|
||||
def wrap_iov(
|
||||
self,
|
||||
iov: typing.Iterable[IOV],
|
||||
encrypt: bool = True,
|
||||
qop: typing.Optional[int] = None,
|
||||
) -> IOVWrapResult:
|
||||
if not self._context:
|
||||
raise NoContextError(context_msg="Cannot wrap until context has been established")
|
||||
|
||||
buffers = self._build_iov_list(iov, self._convert_iov_buffer)
|
||||
iov_buffer = GSSIOV(*buffers, std_layout=False)
|
||||
encrypted = wrap_iov(self._context, iov_buffer, confidential=encrypt, qop=qop)
|
||||
|
||||
return IOVWrapResult(buffers=_create_iov_result(iov_buffer), encrypted=encrypted)
|
||||
|
||||
def wrap_winrm(self, data: bytes) -> WinRMWrapResult:
|
||||
iov = self.wrap_iov([BufferType.header, data, BufferType.padding]).buffers
|
||||
header = iov[0].data or b""
|
||||
enc_data = iov[1].data or b""
|
||||
padding = iov[2].data or b""
|
||||
|
||||
return WinRMWrapResult(header=header, data=enc_data + padding, padding_length=len(padding))
|
||||
|
||||
@wrap_system_error(NativeError, "Unwrapping data")
|
||||
def unwrap(self, data: bytes) -> UnwrapResult:
|
||||
if not self._context:
|
||||
raise NoContextError(context_msg="Cannot unwrap until context has been established")
|
||||
|
||||
res = gssapi.raw.unwrap(self._context, data)
|
||||
|
||||
return UnwrapResult(data=res.message, encrypted=res.encrypted, qop=res.qop)
|
||||
|
||||
@wrap_system_error(NativeError, "Unwrapping IOV buffer")
|
||||
def unwrap_iov(
|
||||
self,
|
||||
iov: typing.Iterable[IOV],
|
||||
) -> IOVUnwrapResult:
|
||||
if not self._context:
|
||||
raise NoContextError(context_msg="Cannot unwrap until context has been established")
|
||||
|
||||
buffers = self._build_iov_list(iov, self._convert_iov_buffer)
|
||||
iov_buffer = GSSIOV(*buffers, std_layout=False)
|
||||
res = unwrap_iov(self._context, iov_buffer)
|
||||
|
||||
return IOVUnwrapResult(buffers=_create_iov_result(iov_buffer), encrypted=res.encrypted, qop=res.qop)
|
||||
|
||||
def unwrap_winrm(self, header: bytes, data: bytes) -> bytes:
|
||||
# This is an extremely weird setup, Kerberos depends on the underlying provider that is used. Right now the
|
||||
# proper IOV buffers required to work on both AES and RC4 encrypted only works for MIT KRB5 whereas Heimdal
|
||||
# fails. It currently mandates a padding buffer of a variable size which we cannot achieve in the way that
|
||||
# WinRM encrypts the data. This is fixed in the source code but until it is widely distributed we just need to
|
||||
# use a way that is known to just work with AES. To ensure that MIT works on both RC4 and AES we check the
|
||||
# description which differs between the 2 implemtations. It's not perfect but I don't know of another way to
|
||||
# achieve this until more time has passed.
|
||||
# https://github.com/heimdal/heimdal/issues/739
|
||||
if not self._context:
|
||||
raise NoContextError(context_msg="Cannot unwrap until context has been established")
|
||||
|
||||
sasl_desc = _gss_sasl_description(self._context.mech)
|
||||
|
||||
# https://github.com/krb5/krb5/blob/f2e28f13156785851819fc74cae52100e0521690/src/lib/gssapi/krb5/gssapi_krb5.c#L686
|
||||
if sasl_desc and sasl_desc == b"Kerberos 5 GSS-API Mechanism":
|
||||
iov = self.unwrap_iov([(IOVBufferType.header, header), data, IOVBufferType.data]).buffers
|
||||
return iov[1].data or b""
|
||||
|
||||
else:
|
||||
return self.unwrap(header + data).data
|
||||
|
||||
@wrap_system_error(NativeError, "Signing message")
|
||||
def sign(self, data: bytes, qop: typing.Optional[int] = None) -> bytes:
|
||||
if not self._context:
|
||||
raise NoContextError(context_msg="Cannot sign until context has been established")
|
||||
|
||||
return gssapi.raw.get_mic(self._context, data, qop=qop)
|
||||
|
||||
@wrap_system_error(NativeError, "Verifying message")
|
||||
def verify(self, data: bytes, mic: bytes) -> int:
|
||||
if not self._context:
|
||||
raise NoContextError(context_msg="Cannot verify until context has been established")
|
||||
|
||||
return gssapi.raw.verify_mic(self._context, data, mic)
|
||||
|
||||
@property
|
||||
def _context_attr_map(self) -> typing.List[typing.Tuple[ContextReq, int]]:
|
||||
attr_map = [
|
||||
(ContextReq.delegate, "delegate_to_peer"),
|
||||
(ContextReq.mutual_auth, "mutual_authentication"),
|
||||
(ContextReq.replay_detect, "replay_detection"),
|
||||
(ContextReq.sequence_detect, "out_of_sequence_detection"),
|
||||
(ContextReq.confidentiality, "confidentiality"),
|
||||
(ContextReq.integrity, "integrity"),
|
||||
(ContextReq.dce_style, "dce_style"),
|
||||
# Only present when the DCE extensions are installed.
|
||||
(ContextReq.identify, "identify"),
|
||||
# Only present with newer versions of python-gssapi https://github.com/pythongssapi/python-gssapi/pull/218.
|
||||
(ContextReq.delegate_policy, "ok_as_delegate"),
|
||||
]
|
||||
attrs = []
|
||||
for spnego_flag, gssapi_name in attr_map:
|
||||
if hasattr(gssapi.RequirementFlag, gssapi_name):
|
||||
attrs.append((spnego_flag, getattr(gssapi.RequirementFlag, gssapi_name)))
|
||||
|
||||
return attrs
|
||||
|
||||
def _convert_iov_buffer(self, buffer: IOVBuffer) -> "GSSIOVBuffer":
|
||||
buffer_data = None
|
||||
buffer_alloc = False
|
||||
|
||||
if isinstance(buffer.data, bytes):
|
||||
buffer_data = buffer.data
|
||||
elif isinstance(buffer.data, bool):
|
||||
buffer_alloc = buffer.data
|
||||
elif isinstance(buffer.data, int):
|
||||
# This shouldn't really occur on GSSAPI but is here to mirror what SSPI does.
|
||||
buffer_data = b"\x00" * buffer.data
|
||||
else:
|
||||
auto_alloc = [BufferType.header, BufferType.padding, BufferType.trailer]
|
||||
buffer_alloc = buffer.type in auto_alloc
|
||||
|
||||
buffer_type = buffer.type
|
||||
if buffer.type == BufferType.data_readonly:
|
||||
# GSSAPI doesn't have the SSPI equivalent of SECBUFFER_READONLY.
|
||||
# the GSS_IOV_BUFFER_TYPE_EMPTY seems to produce the same behaviour
|
||||
# so that's going to be used instead.
|
||||
buffer_type = BufferType.empty
|
||||
|
||||
return GSSIOVBuffer(IOVBufferType(buffer_type), buffer_alloc, buffer_data)
|
||||
1433
env/lib/python3.12/site-packages/spnego/_kerberos.py
vendored
Normal file
1433
env/lib/python3.12/site-packages/spnego/_kerberos.py
vendored
Normal file
File diff suppressed because it is too large
Load Diff
480
env/lib/python3.12/site-packages/spnego/_negotiate.py
vendored
Normal file
480
env/lib/python3.12/site-packages/spnego/_negotiate.py
vendored
Normal file
@@ -0,0 +1,480 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import struct
|
||||
import typing
|
||||
|
||||
import spnego
|
||||
from spnego._context import (
|
||||
IOV,
|
||||
ContextProxy,
|
||||
ContextReq,
|
||||
GSSMech,
|
||||
IOVUnwrapResult,
|
||||
IOVWrapResult,
|
||||
SecPkgContextSizes,
|
||||
UnwrapResult,
|
||||
WinRMWrapResult,
|
||||
WrapResult,
|
||||
)
|
||||
from spnego._credential import Credential, unify_credentials
|
||||
from spnego._gss import GSSAPIProxy
|
||||
from spnego._spnego import (
|
||||
NegState,
|
||||
NegTokenInit,
|
||||
NegTokenResp,
|
||||
pack_mech_type_list,
|
||||
unpack_token,
|
||||
)
|
||||
from spnego._sspi import SSPIProxy
|
||||
from spnego.channel_bindings import GssChannelBindings
|
||||
from spnego.exceptions import (
|
||||
BadMechanismError,
|
||||
InvalidTokenError,
|
||||
NegotiateOptions,
|
||||
NoContextError,
|
||||
)
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class NegotiateProxy(ContextProxy):
|
||||
"""A context wrapper for a Python managed SPNEGO context.
|
||||
|
||||
This is a context that can be used on Linux to generate SPNEGO tokens based on the raw Kerberos or NTLM tokens
|
||||
generated by gssapi or our Python NTLM provider This is used as a fallback if gssapi is not available or cannot
|
||||
generate SPNEGO tokens.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
username: typing.Optional[typing.Union[str, Credential, typing.List[Credential]]] = None,
|
||||
password: typing.Optional[str] = None,
|
||||
hostname: typing.Optional[str] = None,
|
||||
service: typing.Optional[str] = None,
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
context_req: ContextReq = ContextReq.default,
|
||||
usage: str = "initiate",
|
||||
protocol: str = "negotiate",
|
||||
options: NegotiateOptions = NegotiateOptions.none,
|
||||
**kwargs: typing.Any,
|
||||
) -> None:
|
||||
credentials = unify_credentials(username, password)
|
||||
super(NegotiateProxy, self).__init__(
|
||||
credentials, hostname, service, channel_bindings, context_req, usage, protocol, options
|
||||
)
|
||||
|
||||
self._credentials = credentials
|
||||
self._complete = False
|
||||
self._available_contexts: typing.Optional[typing.Dict[GSSMech, ContextProxy]] = kwargs.get(
|
||||
"_negotiate_contexts", None
|
||||
)
|
||||
self._context_list: typing.Dict[GSSMech, typing.Tuple[ContextProxy, typing.Optional[bytes]]] = {}
|
||||
self.__chosen_mech: typing.Optional[GSSMech] = None
|
||||
self._mech_list: typing.List[str] = []
|
||||
|
||||
self._init_sent = False
|
||||
self._mech_sent = False
|
||||
self._mic_sent = False
|
||||
self._mic_recv = False
|
||||
# DCE will always send a MIC token, even for Kerberos.
|
||||
self._mic_required = bool(self.context_req & ContextReq.dce_style)
|
||||
|
||||
@classmethod
|
||||
def available_protocols(cls, options: typing.Optional[NegotiateOptions] = None) -> typing.List[str]:
|
||||
# We always support Negotiate and NTLM as we have our builtin NTLM backend and only support kerberos if gssapi
|
||||
# is present.
|
||||
protocols = ["ntlm", "negotiate"]
|
||||
|
||||
# Make sure we add Kerberos first as the order is important.
|
||||
if "kerberos" in GSSAPIProxy.available_protocols(
|
||||
options=options
|
||||
) or "kerberos" in SSPIProxy.available_protocols(options=options):
|
||||
protocols.insert(0, "kerberos")
|
||||
|
||||
return protocols
|
||||
|
||||
@classmethod
|
||||
def iov_available(cls) -> bool:
|
||||
# If SSPI is available then IOV is available, otherwise it's dependent on whether GSSAPI exposes the functions.
|
||||
if SSPIProxy.available_protocols() == []:
|
||||
return GSSAPIProxy.iov_available()
|
||||
else:
|
||||
return True
|
||||
|
||||
@property
|
||||
def client_principal(self) -> typing.Optional[str]:
|
||||
return self._context.client_principal if self._context_list else None
|
||||
|
||||
@property
|
||||
def complete(self) -> bool:
|
||||
return self._complete
|
||||
|
||||
@property
|
||||
def context_attr(self) -> ContextReq:
|
||||
return self._context.context_attr if self._context_list else ContextReq.none
|
||||
|
||||
@property
|
||||
def negotiated_protocol(self) -> typing.Optional[str]:
|
||||
return self._context.negotiated_protocol if self._context_list else None
|
||||
|
||||
@property
|
||||
def session_key(self) -> bytes:
|
||||
return self._context.session_key if self._context_list else b""
|
||||
|
||||
def new_context(self) -> "NegotiateProxy":
|
||||
return NegotiateProxy(
|
||||
hostname=self._hostname,
|
||||
service=self._service,
|
||||
channel_bindings=self.channel_bindings,
|
||||
context_req=self.context_req,
|
||||
usage=self.usage,
|
||||
protocol=self.protocol,
|
||||
options=self.options,
|
||||
_negotiate_contexts={m: c[0].new_context() for m, c in self._context_list.items()},
|
||||
)
|
||||
|
||||
def step(
|
||||
self,
|
||||
in_token: typing.Optional[bytes] = None,
|
||||
*,
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
) -> typing.Optional[bytes]:
|
||||
log.debug("SPNEGO step input: %s", base64.b64encode(in_token or b"").decode())
|
||||
|
||||
# Step 1. Process SPNEGO mechs.
|
||||
mech_token_in, mech_list_mic, is_spnego = self._step_spnego_input(
|
||||
in_token=in_token,
|
||||
channel_bindings=channel_bindings,
|
||||
)
|
||||
|
||||
mech_token_out = None
|
||||
if mech_token_in or self.usage == "initiate":
|
||||
# Step 2. Process the inner context tokens.
|
||||
mech_token_out = self._step_spnego_token(in_token=mech_token_in, channel_bindings=channel_bindings)
|
||||
|
||||
out_token: typing.Optional[bytes] = None
|
||||
if is_spnego:
|
||||
# Step 3. Process / generate the mechListMIC.
|
||||
out_mic = self._step_spnego_mic(in_mic=mech_list_mic)
|
||||
|
||||
# Step 4. Generate the output SPNEGO token.
|
||||
out_token = self._step_spnego_output(out_token=mech_token_out, out_mic=out_mic)
|
||||
|
||||
else:
|
||||
out_token = mech_token_out
|
||||
self._complete = self._context.complete
|
||||
|
||||
if self.complete:
|
||||
# Remove the leftover contexts if there are still others remaining.
|
||||
self._context_list = {self._chosen_mech: (self._context, None)}
|
||||
|
||||
log.debug("SPNEGO step output: %s" % base64.b64encode(out_token or b"").decode())
|
||||
|
||||
return out_token
|
||||
|
||||
def _step_spnego_input(
|
||||
self,
|
||||
in_token: typing.Optional[bytes] = None,
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
) -> typing.Tuple[typing.Optional[bytes], typing.Optional[bytes], bool]:
|
||||
mech_list_mic = None
|
||||
token = None
|
||||
is_spnego = True
|
||||
|
||||
if in_token:
|
||||
try:
|
||||
in_token = unpack_token(in_token)
|
||||
except struct.error as e:
|
||||
raise InvalidTokenError(base_error=e, context_msg=f"Failed to unpack input token {e!s}")
|
||||
|
||||
if isinstance(in_token, NegTokenInit):
|
||||
mech_list_mic = in_token.mech_list_mic
|
||||
token = in_token.mech_token
|
||||
|
||||
# This is the first token of the exchange, we should build our context list based on the mechs the
|
||||
# opposite end supports.
|
||||
mech_list = self._rebuild_context_list(
|
||||
mech_types=in_token.mech_types,
|
||||
channel_bindings=channel_bindings,
|
||||
)
|
||||
|
||||
if self.usage == "initiate":
|
||||
# If initiate processes a NegTokenInit2 token that's just used as a hint, use the actually
|
||||
# supported mechs as the true mech list.
|
||||
self._mech_list = mech_list
|
||||
|
||||
else:
|
||||
# If accept processes a NegTokenInit token we treat that as an actual init is sent so it does not
|
||||
# send it's own and uses the initiate mech list as the true mech list.
|
||||
self._init_sent = True
|
||||
self._mech_list = in_token.mech_types
|
||||
|
||||
# If the preferred initiator token does not match the preferred acceptor token then the acceptor
|
||||
# must send the request-mic negState.
|
||||
preferred_mech = self._preferred_mech_list()[0]
|
||||
if preferred_mech.value != in_token.mech_types[0]:
|
||||
self._mic_required = True
|
||||
|
||||
elif isinstance(in_token, NegTokenResp):
|
||||
mech_list_mic = in_token.mech_list_mic
|
||||
token = in_token.response_token
|
||||
|
||||
# https://github.com/jborean93/smbprotocol/issues/137
|
||||
# Some really old SPNEGO implementations have mechListMIC with the same value as responseToken. This is
|
||||
# a bug but needs to be handled by blanking out the mechListMIC.
|
||||
if token and mech_list_mic == token:
|
||||
mech_list_mic = None
|
||||
|
||||
# If we have received the supported_mech then we don't need to send our own.
|
||||
if in_token.supported_mech:
|
||||
self.__chosen_mech = GSSMech.from_oid(in_token.supported_mech)
|
||||
self._mech_sent = True
|
||||
|
||||
# Raise exception if we are rejected and have no error info (mechToken) that will give us more info.
|
||||
if in_token.neg_state == NegState.reject and not token:
|
||||
raise InvalidTokenError(context_msg="Received SPNEGO rejection with no token error message")
|
||||
|
||||
if in_token.neg_state == NegState.request_mic:
|
||||
self._mic_required = True
|
||||
elif in_token.neg_state == NegState.accept_complete:
|
||||
self._complete = True
|
||||
|
||||
else:
|
||||
# This usually indicates the token is a raw NTLM or Kerberos token, return as is.
|
||||
is_spnego = False
|
||||
token = in_token
|
||||
|
||||
self.__chosen_mech = GSSMech.ntlm if token and token.startswith(b"NTLMSSP\x00") else GSSMech.kerberos
|
||||
|
||||
if not self._context_list:
|
||||
self._rebuild_context_list(
|
||||
mech_types=[self.__chosen_mech.value],
|
||||
channel_bindings=channel_bindings,
|
||||
)
|
||||
|
||||
else:
|
||||
self._mech_list = self._rebuild_context_list(
|
||||
channel_bindings=channel_bindings,
|
||||
)
|
||||
|
||||
return token, mech_list_mic, is_spnego
|
||||
|
||||
def _step_spnego_token(
|
||||
self,
|
||||
in_token: typing.Optional[bytes] = None,
|
||||
*,
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
) -> typing.Optional[bytes]:
|
||||
chosen_mech = self._chosen_mech
|
||||
context, generated_token = self._context_list[chosen_mech]
|
||||
|
||||
out_token: typing.Optional[bytes] = None
|
||||
if not context.complete:
|
||||
# When usage == 'initiate', the context_list may contain a pre-cached token which we use instead.
|
||||
|
||||
if generated_token:
|
||||
out_token = generated_token
|
||||
self._context_list[chosen_mech] = (context, None) # Clear the value as it's no longer required.
|
||||
|
||||
else:
|
||||
out_token = context.step(in_token=in_token, channel_bindings=channel_bindings)
|
||||
|
||||
# NTLM has a special case where we need to tell it it's ok to generate the MIC and also determine if
|
||||
# it actually did set the MIC as that controls the mechListMIC for the SPNEGO token.
|
||||
if self._requires_mech_list_mic:
|
||||
self._mic_required = True
|
||||
|
||||
return out_token
|
||||
|
||||
def _step_spnego_mic(self, in_mic: typing.Optional[bytes] = None) -> typing.Optional[bytes]:
|
||||
if in_mic:
|
||||
self.verify(pack_mech_type_list(self._mech_list), in_mic)
|
||||
self._reset_ntlm_crypto_state(outgoing=False)
|
||||
|
||||
self._mic_required = True # If we received a mechListMIC we need to send one back.
|
||||
self._mic_recv = True
|
||||
|
||||
if self._mic_sent:
|
||||
self._complete = True
|
||||
|
||||
if self._context.complete and self._mic_required and not self._mic_sent:
|
||||
out_mic = self.sign(pack_mech_type_list(self._mech_list))
|
||||
self._reset_ntlm_crypto_state()
|
||||
|
||||
self._mic_sent = True
|
||||
|
||||
return out_mic
|
||||
|
||||
return None
|
||||
|
||||
def _step_spnego_output(
|
||||
self,
|
||||
out_token: typing.Optional[bytes] = None,
|
||||
out_mic: typing.Optional[bytes] = None,
|
||||
) -> typing.Optional[bytes]:
|
||||
final_token: typing.Optional[bytes] = None
|
||||
|
||||
if not self._init_sent:
|
||||
self._init_sent = True
|
||||
|
||||
init_kwargs: typing.Dict[str, typing.Any] = {
|
||||
"mech_token": out_token,
|
||||
"mech_list_mic": out_mic,
|
||||
}
|
||||
if self.usage == "accept":
|
||||
init_kwargs["hint_name"] = b"not_defined_in_RFC4178@please_ignore"
|
||||
|
||||
final_token = NegTokenInit(self._mech_list, **init_kwargs).pack()
|
||||
|
||||
elif not self.complete:
|
||||
state = NegState.accept_incomplete
|
||||
|
||||
# As per RFC 4178 - 4.2.2: supportedMech should only be present in the first reply from the target.
|
||||
# Also 'negState: request-mic' MUST only be in the first reply from the target if it is needed.
|
||||
# https://tools.ietf.org/html/rfc4178#section-4.2.2
|
||||
supported_mech = None
|
||||
if not self._mech_sent:
|
||||
supported_mech = self._chosen_mech.value
|
||||
if self._mic_required:
|
||||
state = NegState.request_mic
|
||||
|
||||
self._mech_sent = True
|
||||
|
||||
if self._context.complete and (not self._mic_required or (self._mic_sent and self._mic_recv)):
|
||||
state = NegState.accept_complete
|
||||
self._complete = True
|
||||
|
||||
final_token = NegTokenResp(
|
||||
neg_state=state, supported_mech=supported_mech, response_token=out_token, mech_list_mic=out_mic
|
||||
).pack()
|
||||
|
||||
return final_token
|
||||
|
||||
def query_message_sizes(self) -> SecPkgContextSizes:
|
||||
if not self.complete:
|
||||
raise NoContextError(context_msg="Cannot get message sizes until context has been established")
|
||||
|
||||
return self._context.query_message_sizes()
|
||||
|
||||
def wrap(self, data: bytes, encrypt: bool = True, qop: typing.Optional[int] = None) -> WrapResult:
|
||||
return self._context.wrap(data, encrypt=encrypt, qop=qop)
|
||||
|
||||
def wrap_iov(
|
||||
self,
|
||||
iov: typing.Iterable[IOV],
|
||||
encrypt: bool = True,
|
||||
qop: typing.Optional[int] = None,
|
||||
) -> IOVWrapResult:
|
||||
return self._context.wrap_iov(iov, encrypt=encrypt, qop=qop)
|
||||
|
||||
def wrap_winrm(self, data: bytes) -> WinRMWrapResult:
|
||||
return self._context.wrap_winrm(data)
|
||||
|
||||
def unwrap(self, data: bytes) -> UnwrapResult:
|
||||
return self._context.unwrap(data)
|
||||
|
||||
def unwrap_iov(
|
||||
self,
|
||||
iov: typing.Iterable[IOV],
|
||||
) -> IOVUnwrapResult:
|
||||
return self._context.unwrap_iov(iov)
|
||||
|
||||
def unwrap_winrm(self, header: bytes, data: bytes) -> bytes:
|
||||
return self._context.unwrap_winrm(header, data)
|
||||
|
||||
def sign(self, data: bytes, qop: typing.Optional[int] = None) -> bytes:
|
||||
return self._context.sign(data, qop=qop)
|
||||
|
||||
def verify(self, data: bytes, mic: bytes) -> int:
|
||||
return self._context.verify(data, mic)
|
||||
|
||||
@property
|
||||
def _context(self) -> ContextProxy:
|
||||
return self._context_list[self._chosen_mech][0]
|
||||
|
||||
@property
|
||||
def _chosen_mech(self) -> GSSMech:
|
||||
if self.__chosen_mech:
|
||||
return self.__chosen_mech
|
||||
|
||||
return next(iter(self._context_list))
|
||||
|
||||
@property
|
||||
def _context_attr_map(self) -> typing.List[typing.Tuple[ContextReq, int]]:
|
||||
return [] # SPNEGO layer uses the generic commands, the underlying context has it's own specific map.
|
||||
|
||||
@property
|
||||
def _requires_mech_list_mic(self) -> bool:
|
||||
return self._context._requires_mech_list_mic
|
||||
|
||||
def _preferred_mech_list(self) -> typing.List[GSSMech]:
|
||||
"""Get a list of mechs that can be used in priority order (highest to lowest)."""
|
||||
available_protocols = [p for p in self.available_protocols(self.options) if p != "negotiate"]
|
||||
return [getattr(GSSMech, p) for p in available_protocols]
|
||||
|
||||
def _rebuild_context_list(
|
||||
self,
|
||||
mech_types: typing.Optional[typing.List[str]] = None,
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
) -> typing.List[str]:
|
||||
"""Builds a new context list that are available to the client."""
|
||||
available_contexts = self._available_contexts or {}
|
||||
last_err = None
|
||||
|
||||
if not available_contexts:
|
||||
context_kwargs: typing.Dict[str, typing.Any] = {
|
||||
"hostname": self._hostname,
|
||||
"service": self._service,
|
||||
"channel_bindings": self.channel_bindings,
|
||||
"context_req": self.context_req,
|
||||
}
|
||||
all_protocols = self._preferred_mech_list()
|
||||
|
||||
for mech in all_protocols:
|
||||
if mech_types and mech.value not in mech_types:
|
||||
continue
|
||||
|
||||
protocol = mech.name
|
||||
try:
|
||||
log.debug(f"Attempting to create {protocol} context when building SPNEGO mech list")
|
||||
|
||||
# Cannot use SSPI's NTLM as we need to reset the crypto state which SSPI does not expose.
|
||||
options = self.options & ~NegotiateOptions.use_negotiate
|
||||
if protocol == "ntlm" and "ntlm" in SSPIProxy.available_protocols(options=options):
|
||||
options |= NegotiateOptions.use_ntlm
|
||||
|
||||
if self.usage == "accept":
|
||||
context = spnego.server(protocol=protocol, options=options, **context_kwargs)
|
||||
else:
|
||||
context = spnego.client(self._credentials, protocol=protocol, options=options, **context_kwargs)
|
||||
|
||||
context._is_wrapped = True
|
||||
available_contexts[mech] = context
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
log.debug("Failed to create context for SPNEGO protocol %s: %s", protocol, str(e))
|
||||
continue
|
||||
|
||||
self._context_list = {}
|
||||
mech_list = []
|
||||
for mech, context in available_contexts.items():
|
||||
try:
|
||||
first_token = context.step(channel_bindings=channel_bindings) if self.usage == "initiate" else None
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
log.debug("Failed to create first token for SPNEGO protocol %s: %s", mech.name, str(e))
|
||||
continue
|
||||
|
||||
self._context_list[mech] = (context, first_token)
|
||||
mech_list.append(mech.value)
|
||||
|
||||
if not mech_list:
|
||||
raise BadMechanismError(context_msg="Unable to negotiate common mechanism", base_error=last_err)
|
||||
|
||||
return mech_list
|
||||
|
||||
def _reset_ntlm_crypto_state(self, outgoing: bool = True) -> None:
|
||||
self._context._reset_ntlm_crypto_state(outgoing=outgoing)
|
||||
966
env/lib/python3.12/site-packages/spnego/_ntlm.py
vendored
Normal file
966
env/lib/python3.12/site-packages/spnego/_ntlm.py
vendored
Normal file
@@ -0,0 +1,966 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import typing
|
||||
|
||||
from spnego._context import (
|
||||
IOV,
|
||||
ContextProxy,
|
||||
ContextReq,
|
||||
IOVUnwrapResult,
|
||||
IOVWrapResult,
|
||||
SecPkgContextSizes,
|
||||
UnwrapResult,
|
||||
WinRMWrapResult,
|
||||
WrapResult,
|
||||
split_username,
|
||||
)
|
||||
from spnego._credential import (
|
||||
Credential,
|
||||
CredentialCache,
|
||||
NTLMHash,
|
||||
Password,
|
||||
unify_credentials,
|
||||
)
|
||||
from spnego._ntlm_raw.crypto import (
|
||||
RC4Handle,
|
||||
compute_response_v1,
|
||||
compute_response_v2,
|
||||
hmac_md5,
|
||||
lmowfv1,
|
||||
md5,
|
||||
ntowfv1,
|
||||
ntowfv2,
|
||||
rc4init,
|
||||
rc4k,
|
||||
sealkey,
|
||||
signkey,
|
||||
)
|
||||
from spnego._ntlm_raw.messages import (
|
||||
Authenticate,
|
||||
AvFlags,
|
||||
AvId,
|
||||
Challenge,
|
||||
FileTime,
|
||||
Negotiate,
|
||||
NegotiateFlags,
|
||||
NTClientChallengeV2,
|
||||
TargetInfo,
|
||||
Version,
|
||||
)
|
||||
from spnego._ntlm_raw.security import seal, sign
|
||||
from spnego._text import to_text
|
||||
from spnego.channel_bindings import GssChannelBindings
|
||||
from spnego.exceptions import (
|
||||
BadBindingsError,
|
||||
BadMICError,
|
||||
ErrorCode,
|
||||
InvalidTokenError,
|
||||
NegotiateOptions,
|
||||
NoContextError,
|
||||
OperationNotAvailableError,
|
||||
SpnegoError,
|
||||
UnsupportedQop,
|
||||
)
|
||||
from spnego.iov import BufferType, IOVResBuffer
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _get_credential_file() -> typing.Optional[str]:
|
||||
"""Get the path to the NTLM credential store.
|
||||
|
||||
Returns the path to the NTLM credential store specified by the environment variable `NTLM_USER_FILE`.
|
||||
|
||||
Returns:
|
||||
Optional[bytes]: The path to the NTLM credential file or None if not set or found.
|
||||
"""
|
||||
user_file_path = os.environ.get("NTLM_USER_FILE", None)
|
||||
if not user_file_path:
|
||||
return None
|
||||
|
||||
file_path = to_text(user_file_path, encoding="utf-8")
|
||||
if os.path.isfile(file_path):
|
||||
return file_path
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _get_credential(
|
||||
store: typing.Optional[str],
|
||||
domain: typing.Optional[str] = None,
|
||||
username: typing.Optional[str] = None,
|
||||
) -> typing.Tuple[typing.Optional[str], typing.Optional[str], bytes, bytes]:
|
||||
"""Look up NTLM credentials from the common flat file.
|
||||
|
||||
Retrieves the LM and NT hash for use with authentication or validating a credential from an initiator.
|
||||
|
||||
Each line in the store can be in the Heimdal format `DOMAIN:USER:PASSWORD` like::
|
||||
|
||||
testdom:testuser:Password01
|
||||
:testuser@TESTDOM.COM:Password01
|
||||
|
||||
Or it can use the `smbpasswd`_ file format `USERNAME:UID:LM_HASH:NT_HASH:ACCT_FLAGS:TIMESTAMP` like::
|
||||
|
||||
testuser:1000:278623D830DABE161104594F8C2EF12B:C3C6F4FD8A02A6C1268F1A8074B6E7E0:[U]:LCT-1589398321
|
||||
TESTDOM\testuser:1000:4588C64B89437893AAD3B435B51404EE:65202355FA01AEF26B89B19E00F52679:[U]:LCT-1589398321
|
||||
testuser@TESTDOM.COM:1000:00000000000000000000000000000000:8ADB9B997580D69E69CAA2BBB68F4697:[U]:LCT-1589398321
|
||||
|
||||
While only the `USERNAME`, `LM_HASH`, and `NT_HASH` fields are used, the colons are still required to differentiate
|
||||
between the 2 formats. See `ntlm hash generator`_ for ways to generate the `LM_HASH` and `NT_HASH`.
|
||||
|
||||
The username is case insensitive but the format of the domain and user part must match up with the value used as
|
||||
the username specified by the caller.
|
||||
|
||||
While each line can use a different format, it is recommended to stick to 1 throughout the file.
|
||||
|
||||
The same env var and format can also be read with gss-ntlmssp.
|
||||
|
||||
Args:
|
||||
store: The credential store to lookup the credential from.
|
||||
domain: The domain for the user to get the credentials for. Should be `None` for a user in the UPN form.
|
||||
username: The username to get the credentials for. If omitted then the first entry in the store is used.
|
||||
|
||||
Returns:
|
||||
Tuple[str, str, bytes, bytes]: The domain, username, LM, and NT hash of the user specified.
|
||||
|
||||
.. _smbpasswd:
|
||||
https://www.samba.org/samba/docs/current/man-html/smbpasswd.5.html
|
||||
|
||||
.. _ntlm hash generator:
|
||||
https://asecuritysite.com/encryption/lmhash
|
||||
"""
|
||||
if not store:
|
||||
raise OperationNotAvailableError(
|
||||
context_msg="No username or password was specified and the credential cache did not exist or contained no credentials"
|
||||
)
|
||||
|
||||
domain = domain or ""
|
||||
|
||||
def store_lines(
|
||||
text: str,
|
||||
) -> typing.Iterator[typing.Tuple[str, str, typing.Optional[str], typing.Optional[bytes], typing.Optional[bytes]]]:
|
||||
for line in text.splitlines():
|
||||
line_split = line.split(":")
|
||||
|
||||
if len(line_split) == 3:
|
||||
yield line_split[0], line_split[1], line_split[2], None, None
|
||||
|
||||
elif len(line_split) == 6:
|
||||
domain_entry, user_entry = split_username(line_split[0])
|
||||
lm_entry = base64.b16decode(line_split[2].upper())
|
||||
nt_entry = base64.b16decode(line_split[3].upper())
|
||||
|
||||
yield domain_entry or "", user_entry or "", None, lm_entry, nt_entry
|
||||
|
||||
with open(store, mode="rb") as fd:
|
||||
cred_text = fd.read().decode()
|
||||
|
||||
for line_domain, line_user, line_password, lm_hash, nt_hash in store_lines(cred_text):
|
||||
if not username or (username.upper() == line_user.upper() and domain.upper() == line_domain.upper()):
|
||||
# The Heimdal format uses the password so if the LM or NT hash isn't set generate it ourselves.
|
||||
if not lm_hash:
|
||||
lm_hash = lmowfv1(line_password or "")
|
||||
if not nt_hash:
|
||||
nt_hash = ntowfv1(line_password or "")
|
||||
|
||||
# Favour the explicit username/password value, otherwise use what was in the credential file.
|
||||
if not username:
|
||||
username = line_user
|
||||
|
||||
if not domain:
|
||||
domain = line_domain or None
|
||||
|
||||
return domain, username, lm_hash, nt_hash
|
||||
|
||||
else:
|
||||
raise SpnegoError(
|
||||
ErrorCode.failure,
|
||||
context_msg="Failed to find any matching credential in NTLM_USER_FILE credential store.",
|
||||
)
|
||||
|
||||
|
||||
def _get_workstation() -> typing.Optional[str]:
|
||||
"""Get the current workstation name.
|
||||
|
||||
This gets the current workstation name that respects `NETBIOS_COMPUTER_NAME`. The env var is used by the library
|
||||
that gss-ntlmssp calls and makes sure that this Python implementation is a closer in its behaviour.
|
||||
|
||||
Returns:
|
||||
Optional[str]: The workstation to supply in the NTLM authentication message or None.
|
||||
"""
|
||||
if "NETBIOS_COMPUTER_NAME" in os.environ:
|
||||
workstation = os.environ["NETBIOS_COMPUTER_NAME"]
|
||||
|
||||
else:
|
||||
workstation = socket.gethostname().upper()
|
||||
|
||||
# An empty workstation should be None so we don't set it in the message.
|
||||
return to_text(workstation) if workstation else None
|
||||
|
||||
|
||||
class _NTLMCredential:
|
||||
def __init__(
|
||||
self,
|
||||
credential: typing.Optional[Credential] = None,
|
||||
) -> None:
|
||||
self._raw_username: typing.Optional[str] = None
|
||||
self._store: typing.Optional[str]
|
||||
if isinstance(credential, Password):
|
||||
self._store = "explicit"
|
||||
self._raw_username = credential.username
|
||||
self.domain, self.username = split_username(credential.username)
|
||||
self.lm_hash = lmowfv1(credential.password)
|
||||
self.nt_hash = ntowfv1(credential.password)
|
||||
|
||||
elif isinstance(credential, NTLMHash):
|
||||
self._store = "explicit"
|
||||
self._raw_username = credential.username
|
||||
self.domain, self.username = split_username(credential.username)
|
||||
self.lm_hash = base64.b16decode(credential.lm_hash.upper()) if credential.lm_hash else b"\x00" * 16
|
||||
self.nt_hash = base64.b16decode(credential.nt_hash.upper()) if credential.nt_hash else b"\x00" * 16
|
||||
|
||||
else:
|
||||
domain = username = None
|
||||
if isinstance(credential, CredentialCache):
|
||||
self._raw_username = credential.username
|
||||
domain, username = split_username(credential.username)
|
||||
|
||||
self._store = _get_credential_file()
|
||||
self.domain, self.username, self.lm_hash, self.nt_hash = _get_credential(self._store, domain, username)
|
||||
|
||||
|
||||
class NTLMProxy(ContextProxy):
|
||||
"""A context wrapper for a Python managed NTLM context.
|
||||
|
||||
This is a context that can be used on Linux to generate NTLM without any system dependencies.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
username: typing.Optional[typing.Union[str, Credential, typing.List[Credential]]] = None,
|
||||
password: typing.Optional[str] = None,
|
||||
hostname: typing.Optional[str] = None,
|
||||
service: typing.Optional[str] = None,
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
context_req: ContextReq = ContextReq.default,
|
||||
usage: str = "initiate",
|
||||
protocol: str = "ntlm",
|
||||
options: NegotiateOptions = NegotiateOptions.none,
|
||||
**kwargs: typing.Any,
|
||||
) -> None:
|
||||
credentials = unify_credentials(username, password, required_protocol="ntlm")
|
||||
super(NTLMProxy, self).__init__(
|
||||
credentials, hostname, service, channel_bindings, context_req, usage, protocol, options
|
||||
)
|
||||
|
||||
self._complete = False
|
||||
self._credential: typing.Optional[_NTLMCredential] = None
|
||||
|
||||
# Set the default flags, these might change depending on the LM_COMPAT_LEVEL set.
|
||||
self._context_req = (
|
||||
self._context_req
|
||||
| NegotiateFlags.key_128
|
||||
| NegotiateFlags.key_56
|
||||
| NegotiateFlags.key_exch
|
||||
| NegotiateFlags.extended_session_security
|
||||
| NegotiateFlags.always_sign
|
||||
| NegotiateFlags.ntlm
|
||||
| NegotiateFlags.lm_key
|
||||
| NegotiateFlags.request_target
|
||||
| NegotiateFlags.oem
|
||||
| NegotiateFlags.unicode
|
||||
)
|
||||
|
||||
# gss-ntlmssp uses the env var 'LM_COMPAT_LEVEL' to control the NTLM compatibility level. To try and make our
|
||||
# NTLM implementation similar in functionality we will also use that behaviour.
|
||||
# https://github.com/gssapi/gss-ntlmssp/blob/e498737a96e8832a2cb9141ab1fe51e129185a48/src/gss_ntlmssp.c#L159-L170
|
||||
# See the below policy link for more details on what these mean, for now 3 is the sane behaviour.
|
||||
# https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/network-security-lan-manager-authentication-level
|
||||
lm_compat_level = int(os.environ.get("LM_COMPAT_LEVEL", 3))
|
||||
if lm_compat_level < 0 or lm_compat_level > 5:
|
||||
raise SpnegoError(
|
||||
ErrorCode.failure, context_msg="Invalid LM_COMPAT_LEVEL %d, must be between 0 and 5" % lm_compat_level
|
||||
)
|
||||
|
||||
if lm_compat_level == 0:
|
||||
self._context_req &= ~NegotiateFlags.extended_session_security
|
||||
|
||||
if self.usage == "initiate":
|
||||
self._credential = _NTLMCredential(next(c for c in credentials if "ntlm" in c.supported_protocols))
|
||||
|
||||
self._lm = lm_compat_level < 2
|
||||
self._nt_v1 = lm_compat_level < 3
|
||||
self._nt_v2 = lm_compat_level > 2
|
||||
|
||||
if lm_compat_level > 1:
|
||||
self._context_req &= ~NegotiateFlags.lm_key
|
||||
|
||||
else:
|
||||
self._lm = lm_compat_level < 4
|
||||
self._nt_v1 = lm_compat_level < 5
|
||||
self._nt_v2 = True
|
||||
|
||||
# Make sure that the credential file is set and exists
|
||||
if not _get_credential_file():
|
||||
raise OperationNotAvailableError(
|
||||
context_msg="NTLM acceptor requires NTLM credential cache to be provided through the env var NTLM_USER_FILE set to a filepath"
|
||||
)
|
||||
|
||||
self._temp_negotiate: typing.Optional[Negotiate] = None
|
||||
self._temp_challenge: typing.Optional[Challenge] = None
|
||||
self._mic_required = False
|
||||
|
||||
# Crypto state for signing and sealing.
|
||||
self._session_key: typing.Optional[bytes] = None
|
||||
self._sign_key_out: typing.Optional[bytes] = None
|
||||
self._sign_key_in: typing.Optional[bytes] = None
|
||||
self._handle_out: typing.Optional[RC4Handle] = None
|
||||
self._handle_in: typing.Optional[RC4Handle] = None
|
||||
self.__seq_num_in = 0
|
||||
self.__seq_num_out = 0
|
||||
|
||||
@classmethod
|
||||
def available_protocols(cls, options: typing.Optional[NegotiateOptions] = None) -> typing.List[str]:
|
||||
return ["ntlm"]
|
||||
|
||||
@classmethod
|
||||
def iov_available(cls) -> bool:
|
||||
return True
|
||||
|
||||
@property
|
||||
def client_principal(self) -> typing.Optional[str]:
|
||||
if self.usage == "accept" and self.complete and self._credential:
|
||||
domain_part = self._credential.domain + "\\" if self._credential.domain else ""
|
||||
return "%s%s" % (domain_part, self._credential.username)
|
||||
|
||||
return None
|
||||
|
||||
@property
|
||||
def complete(self) -> bool:
|
||||
return self._complete
|
||||
|
||||
@property
|
||||
def negotiated_protocol(self) -> typing.Optional[str]:
|
||||
return "ntlm"
|
||||
|
||||
@property
|
||||
def session_key(self) -> bytes:
|
||||
return self._session_key or b""
|
||||
|
||||
def new_context(self) -> "NTLMProxy":
|
||||
cred: typing.Optional[NTLMHash] = None
|
||||
if self._credential and self.usage == "initiate":
|
||||
cred = NTLMHash(
|
||||
username=self._credential._raw_username or "",
|
||||
lm_hash=base64.b16encode(self._credential.lm_hash).decode(),
|
||||
nt_hash=base64.b16encode(self._credential.nt_hash).decode(),
|
||||
)
|
||||
|
||||
return NTLMProxy(
|
||||
username=cred,
|
||||
hostname=self._hostname,
|
||||
service=self._service,
|
||||
channel_bindings=self.channel_bindings,
|
||||
context_req=self.context_req,
|
||||
usage=self.usage,
|
||||
protocol=self.protocol,
|
||||
options=self.options,
|
||||
)
|
||||
|
||||
def step(
|
||||
self,
|
||||
in_token: typing.Optional[bytes] = None,
|
||||
*,
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
) -> typing.Optional[bytes]:
|
||||
if not self._is_wrapped:
|
||||
log.debug("NTLM step input: %s", base64.b64encode(in_token or b"").decode())
|
||||
|
||||
out_token = getattr(self, "_step_%s" % self.usage)(
|
||||
in_token=in_token,
|
||||
channel_bindings=channel_bindings,
|
||||
)
|
||||
|
||||
if not self._is_wrapped:
|
||||
log.debug("NTLM step output: %s", base64.b64encode(out_token or b"").decode())
|
||||
|
||||
if self._complete:
|
||||
# Clear out any temp data we still have stored.
|
||||
self._temp_negotiate = None
|
||||
self._temp_challenge = None
|
||||
|
||||
in_usage = "accept" if self.usage == "initiate" else "initiate"
|
||||
session_key = self._session_key or b""
|
||||
# if tmp_key := os.environ.get("TESTING", None):
|
||||
# session_key = self._session_key = base64.b16decode(tmp_key)
|
||||
|
||||
self._sign_key_out = signkey(self._context_attr, session_key, self.usage)
|
||||
self._sign_key_in = signkey(self._context_attr, session_key, in_usage)
|
||||
|
||||
# Found a vague reference in MS-NLMP that states if NTLMv2 authentication was not used then only 1 key is
|
||||
# used for sealing. This seems to reference when NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY is not set and
|
||||
# not NTLMv2 messages itself.
|
||||
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/d1c86e81-eb66-47fd-8a6f-970050121347
|
||||
if self._context_attr & NegotiateFlags.extended_session_security:
|
||||
self._handle_out = rc4init(sealkey(self._context_attr, session_key, self.usage))
|
||||
self._handle_in = rc4init(sealkey(self._context_attr, session_key, in_usage))
|
||||
else:
|
||||
self._handle_out = self._handle_in = rc4init(sealkey(self._context_attr, session_key, self.usage))
|
||||
|
||||
return out_token
|
||||
|
||||
def _step_initiate(
|
||||
self,
|
||||
in_token: typing.Optional[bytes] = None,
|
||||
*,
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
) -> bytes:
|
||||
if not self._temp_negotiate:
|
||||
# SSPI always sends the version even if it's optional. There have
|
||||
# been reports that some NTLM servers expect this to produce a
|
||||
# valid challenge/authentication token later in the exchange.
|
||||
# https://github.com/jborean93/smbprotocol/issues/216
|
||||
self._temp_negotiate = Negotiate(self._context_req, version=Version.get_current())
|
||||
return self._temp_negotiate.pack()
|
||||
|
||||
in_token = in_token or b""
|
||||
challenge = Challenge.unpack(in_token)
|
||||
|
||||
# Lots of mypy failures with self._credential, cast it to non Optional as it will always be set here.
|
||||
credential = typing.cast(_NTLMCredential, self._credential)
|
||||
auth_kwargs: typing.Dict[str, typing.Any] = {
|
||||
"domain_name": credential.domain,
|
||||
"username": credential.username,
|
||||
}
|
||||
|
||||
if challenge.flags & NegotiateFlags.version:
|
||||
auth_kwargs["version"] = Version.get_current()
|
||||
auth_kwargs["workstation"] = _get_workstation()
|
||||
|
||||
nt_challenge, lm_challenge, key_exchange_key = self._compute_response(
|
||||
challenge,
|
||||
credential,
|
||||
channel_bindings=channel_bindings or self.channel_bindings,
|
||||
)
|
||||
|
||||
if challenge.flags & NegotiateFlags.key_exch:
|
||||
# This is only documented on the server side for MS-NLMP but is also valid for the client. The actual
|
||||
# session key is the KeyExchangeKey like normal unless sign or seal is negotiated.
|
||||
|
||||
if challenge.flags & NegotiateFlags.sign or challenge.flags & NegotiateFlags.seal:
|
||||
self._session_key = os.urandom(16)
|
||||
auth_kwargs["encrypted_session_key"] = rc4k(key_exchange_key, self._session_key)
|
||||
|
||||
else:
|
||||
self._session_key = key_exchange_key
|
||||
auth_kwargs["encrypted_session_key"] = b"\x00" # Must be set to some value but this can be anything.
|
||||
|
||||
else:
|
||||
self._session_key = key_exchange_key
|
||||
|
||||
authenticate = Authenticate(challenge.flags, lm_challenge, nt_challenge, **auth_kwargs)
|
||||
|
||||
if self._mic_required:
|
||||
authenticate.mic = self._calculate_mic(
|
||||
self._session_key, self._temp_negotiate.pack(), in_token, authenticate.pack()
|
||||
)
|
||||
|
||||
self._context_attr = authenticate.flags
|
||||
self._complete = True
|
||||
|
||||
return authenticate.pack()
|
||||
|
||||
def _step_accept(
|
||||
self,
|
||||
in_token: bytes,
|
||||
*,
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
) -> typing.Optional[bytes]:
|
||||
if not self._temp_negotiate:
|
||||
return self._step_accept_negotiate(in_token)
|
||||
|
||||
else:
|
||||
self._step_accept_authenticate(
|
||||
in_token,
|
||||
channel_bindings=channel_bindings or self.channel_bindings,
|
||||
)
|
||||
return None
|
||||
|
||||
def _step_accept_negotiate(self, token: bytes) -> bytes:
|
||||
"""Process the Negotiate message from the initiator."""
|
||||
negotiate = Negotiate.unpack(token)
|
||||
|
||||
flags = (
|
||||
negotiate.flags
|
||||
| NegotiateFlags.request_target
|
||||
| NegotiateFlags.ntlm
|
||||
| NegotiateFlags.always_sign
|
||||
| NegotiateFlags.target_info
|
||||
| NegotiateFlags.target_type_server
|
||||
)
|
||||
|
||||
# Make sure either UNICODE or OEM is set, not both.
|
||||
if flags & NegotiateFlags.unicode:
|
||||
flags &= ~NegotiateFlags.oem
|
||||
elif flags & NegotiateFlags.oem == 0:
|
||||
raise SpnegoError(
|
||||
ErrorCode.failure,
|
||||
context_msg="Neither NEGOTIATE_OEM or NEGOTIATE_UNICODE flags were "
|
||||
"set, cannot derive encoding for text fields",
|
||||
)
|
||||
|
||||
if flags & NegotiateFlags.extended_session_security:
|
||||
flags &= ~NegotiateFlags.lm_key
|
||||
|
||||
server_challenge = os.urandom(8)
|
||||
target_name = to_text(socket.gethostname()).upper()
|
||||
|
||||
target_info = TargetInfo()
|
||||
target_info[AvId.nb_computer_name] = target_name
|
||||
target_info[AvId.nb_domain_name] = "WORKSTATION"
|
||||
target_info[AvId.dns_computer_name] = to_text(socket.getfqdn())
|
||||
target_info[AvId.timestamp] = FileTime.now()
|
||||
|
||||
challenge = Challenge(flags, server_challenge, target_name=target_name, target_info=target_info)
|
||||
|
||||
self._temp_negotiate = negotiate
|
||||
self._temp_challenge = challenge
|
||||
|
||||
return challenge.pack()
|
||||
|
||||
def _step_accept_authenticate(self, token: bytes, channel_bindings: typing.Optional[GssChannelBindings]) -> None:
|
||||
"""Process the Authenticate message from the initiator."""
|
||||
negotiate = typing.cast(Negotiate, self._temp_negotiate)
|
||||
challenge = typing.cast(Challenge, self._temp_challenge)
|
||||
server_challenge = challenge.server_challenge
|
||||
auth = Authenticate.unpack(token)
|
||||
|
||||
# TODO: Add anonymous user support.
|
||||
if not auth.user_name or (
|
||||
not auth.nt_challenge_response and (not auth.lm_challenge_response or auth.lm_challenge_response == b"\x00")
|
||||
):
|
||||
raise OperationNotAvailableError(context_msg="Anonymous user authentication not implemented")
|
||||
|
||||
username = auth.user_name
|
||||
if auth.domain_name:
|
||||
username = f"{auth.domain_name}\\{username}"
|
||||
self._credential = _NTLMCredential(CredentialCache(username=username))
|
||||
expected_mic = None
|
||||
|
||||
if auth.nt_challenge_response and len(auth.nt_challenge_response) > 24:
|
||||
nt_hash = ntowfv2(auth.user_name, self._credential.nt_hash, auth.domain_name)
|
||||
|
||||
nt_challenge = NTClientChallengeV2.unpack(auth.nt_challenge_response[16:])
|
||||
time = nt_challenge.time_stamp
|
||||
client_challenge = nt_challenge.challenge_from_client
|
||||
target_info = nt_challenge.av_pairs
|
||||
|
||||
expected_nt, expected_lm, key_exchange_key = compute_response_v2(
|
||||
nt_hash, server_challenge, client_challenge, time, target_info
|
||||
)
|
||||
|
||||
if channel_bindings:
|
||||
if AvId.channel_bindings not in target_info:
|
||||
raise BadBindingsError(
|
||||
context_msg="Acceptor bindings specified but not present in initiator response"
|
||||
)
|
||||
|
||||
expected_bindings = target_info[AvId.channel_bindings]
|
||||
actual_bindings = md5(channel_bindings.pack())
|
||||
if expected_bindings not in [actual_bindings, b"\x00" * 16]:
|
||||
raise BadBindingsError(context_msg="Acceptor bindings do not match initiator bindings")
|
||||
|
||||
if target_info.get(AvId.flags, 0) & AvFlags.mic:
|
||||
expected_mic = auth.mic
|
||||
|
||||
else:
|
||||
if not self._nt_v1:
|
||||
raise InvalidTokenError(context_msg="Acceptor settings are set to reject NTv1 responses")
|
||||
|
||||
elif not auth.nt_challenge_response and not self._lm:
|
||||
raise InvalidTokenError(context_msg="Acceptor settings are set to reject LM responses")
|
||||
|
||||
client_challenge = b"\x00" * 8
|
||||
if auth.flags & NegotiateFlags.extended_session_security:
|
||||
client_challenge = (auth.lm_challenge_response or b"\x00" * 8)[:8]
|
||||
|
||||
expected_nt, expected_lm, key_exchange_key = compute_response_v1(
|
||||
auth.flags,
|
||||
self._credential.nt_hash,
|
||||
self._credential.lm_hash,
|
||||
server_challenge,
|
||||
client_challenge,
|
||||
no_lm_response=not self._lm,
|
||||
)
|
||||
|
||||
auth_success = False
|
||||
|
||||
if auth.nt_challenge_response:
|
||||
auth_success = auth.nt_challenge_response == expected_nt
|
||||
|
||||
elif auth.lm_challenge_response:
|
||||
auth_success = auth.lm_challenge_response == expected_lm
|
||||
|
||||
if not auth_success:
|
||||
raise InvalidTokenError(context_msg="Invalid NTLM response from initiator")
|
||||
|
||||
if auth.flags & NegotiateFlags.key_exch and (
|
||||
auth.flags & NegotiateFlags.sign or auth.flags & NegotiateFlags.seal
|
||||
):
|
||||
self._session_key = rc4k(key_exchange_key, auth.encrypted_random_session_key or b"")
|
||||
|
||||
else:
|
||||
self._session_key = key_exchange_key
|
||||
|
||||
if expected_mic:
|
||||
auth.mic = b"\x00" * 16
|
||||
actual_mic = self._calculate_mic(self.session_key, negotiate.pack(), challenge.pack(), auth.pack())
|
||||
|
||||
if actual_mic != expected_mic:
|
||||
raise InvalidTokenError(context_msg="Invalid MIC in NTLM authentication message")
|
||||
|
||||
self._context_attr = auth.flags
|
||||
self._complete = True
|
||||
|
||||
def query_message_sizes(self) -> SecPkgContextSizes:
|
||||
if not self.complete:
|
||||
raise NoContextError(context_msg="Cannot get message sizes until context has been established")
|
||||
|
||||
return SecPkgContextSizes(header=16)
|
||||
|
||||
def wrap(self, data: bytes, encrypt: bool = True, qop: typing.Optional[int] = None) -> WrapResult:
|
||||
if qop:
|
||||
raise UnsupportedQop(context_msg="Unsupported QoP value %s specified for NTLM" % qop)
|
||||
|
||||
if self.context_attr & ContextReq.integrity == 0 and self.context_attr & ContextReq.confidentiality == 0:
|
||||
raise OperationNotAvailableError(context_msg="NTLM wrap without integrity or confidentiality")
|
||||
|
||||
if not self._handle_out or self._sign_key_out is None:
|
||||
raise NoContextError(context_msg="Cannot wrap until context has been established")
|
||||
|
||||
msg, signature = seal(
|
||||
self._context_attr,
|
||||
self._handle_out,
|
||||
self._sign_key_out,
|
||||
self._seq_num_out,
|
||||
data,
|
||||
)
|
||||
|
||||
return WrapResult(data=signature + msg, encrypted=True)
|
||||
|
||||
def wrap_iov(
|
||||
self,
|
||||
iov: typing.Iterable[IOV],
|
||||
encrypt: bool = True,
|
||||
qop: typing.Optional[int] = None,
|
||||
) -> IOVWrapResult:
|
||||
if qop:
|
||||
raise UnsupportedQop(context_msg="Unsupported QoP value %s specified for NTLM" % qop)
|
||||
|
||||
if self.context_attr & ContextReq.integrity == 0 and self.context_attr & ContextReq.confidentiality == 0:
|
||||
raise OperationNotAvailableError(context_msg="NTLM wrap without integrity or confidentiality")
|
||||
|
||||
if not self._handle_out or self._sign_key_out is None:
|
||||
raise NoContextError(context_msg="Cannot wrap until context has been established")
|
||||
|
||||
header_idx = -1
|
||||
data_idx = -1
|
||||
signature_input = []
|
||||
buffers = self._build_iov_list(iov, lambda b: b)
|
||||
res: typing.List[IOVResBuffer] = []
|
||||
|
||||
for idx, buffer in enumerate(buffers):
|
||||
data: bytes
|
||||
if buffer.type == BufferType.header:
|
||||
if header_idx != -1:
|
||||
raise InvalidTokenError(context_msg="wrap_iov must only be used with 1 header IOV buffer.")
|
||||
header_idx = idx
|
||||
data = b""
|
||||
|
||||
elif buffer.type == BufferType.data:
|
||||
if data_idx != -1:
|
||||
raise InvalidTokenError(context_msg="wrap_iov must only be used with 1 data IOV buffer.")
|
||||
|
||||
if not isinstance(buffer.data, bytes):
|
||||
raise InvalidTokenError(context_msg=f"wrap_iov IOV data buffer at [{idx}] must be bytes")
|
||||
|
||||
data_idx = idx
|
||||
data = buffer.data
|
||||
signature_input.append(data)
|
||||
|
||||
elif buffer.type in [BufferType.sign_only, BufferType.data_readonly]:
|
||||
if not isinstance(buffer.data, bytes):
|
||||
raise InvalidTokenError(
|
||||
context_msg=f"wrap_iov IOV {buffer.type.name} buffer at [{idx}] must be bytes"
|
||||
)
|
||||
|
||||
data = buffer.data
|
||||
signature_input.append(data)
|
||||
|
||||
else:
|
||||
raise InvalidTokenError(context_msg=f"wrap_iov unsupported IOV buffer type {buffer.type.name}")
|
||||
|
||||
res.append(IOVResBuffer(buffer.type, data))
|
||||
|
||||
if header_idx == -1:
|
||||
raise InvalidTokenError(context_msg="wrap_iov no IOV header buffer present")
|
||||
|
||||
if data_idx == -1:
|
||||
raise InvalidTokenError(context_msg="wrap_iov no IOV data buffer present")
|
||||
|
||||
enc_msg, signature = seal(
|
||||
self._context_attr,
|
||||
self._handle_out,
|
||||
self._sign_key_out,
|
||||
self._seq_num_out,
|
||||
res[data_idx][1] or b"",
|
||||
to_sign=b"".join(signature_input),
|
||||
)
|
||||
|
||||
res[header_idx] = IOVResBuffer(BufferType.header, signature)
|
||||
res[data_idx] = IOVResBuffer(BufferType.data, enc_msg)
|
||||
|
||||
return IOVWrapResult(tuple(res), encrypted=True)
|
||||
|
||||
def wrap_winrm(self, data: bytes) -> WinRMWrapResult:
|
||||
enc_data = self.wrap(data).data
|
||||
return WinRMWrapResult(header=enc_data[:16], data=enc_data[16:], padding_length=0)
|
||||
|
||||
def unwrap(self, data: bytes) -> UnwrapResult:
|
||||
if not self._handle_in:
|
||||
raise NoContextError(context_msg="Cannot unwrap until context has been established")
|
||||
|
||||
signature = data[:16]
|
||||
msg = self._handle_in.update(data[16:])
|
||||
self.verify(msg, signature)
|
||||
|
||||
return UnwrapResult(data=msg, encrypted=True, qop=0)
|
||||
|
||||
def unwrap_iov(
|
||||
self,
|
||||
iov: typing.Iterable[IOV],
|
||||
) -> IOVUnwrapResult:
|
||||
if self.context_attr & ContextReq.integrity == 0 and self.context_attr & ContextReq.confidentiality == 0:
|
||||
raise OperationNotAvailableError(context_msg="NTLM unwrap without integrity or confidentiality")
|
||||
|
||||
if not self._handle_in or self._sign_key_in is None:
|
||||
raise NoContextError(context_msg="Cannot unwrap until context has been established")
|
||||
|
||||
buffers = self._build_iov_list(iov, lambda b: b)
|
||||
|
||||
# Check if it's a stream + data set of buffers and just call unwrap.
|
||||
if (
|
||||
len(buffers) == 2
|
||||
and buffers[0].type == BufferType.stream
|
||||
and buffers[1].type == BufferType.data
|
||||
and isinstance(buffers[0].data, bytes)
|
||||
):
|
||||
unwrap_res = self.unwrap(buffers[0].data)
|
||||
|
||||
return IOVUnwrapResult(
|
||||
(
|
||||
IOVResBuffer(BufferType.stream, buffers[0].data),
|
||||
IOVResBuffer(BufferType.data, unwrap_res.data),
|
||||
),
|
||||
encrypted=unwrap_res.encrypted,
|
||||
qop=unwrap_res.qop,
|
||||
)
|
||||
|
||||
header_idx = -1
|
||||
data_idx = -1
|
||||
data_sig_idx = -1
|
||||
signature_input: typing.List[bytes] = []
|
||||
|
||||
res: typing.List[IOVResBuffer] = []
|
||||
|
||||
for idx, buffer in enumerate(buffers):
|
||||
data: bytes
|
||||
|
||||
if not isinstance(buffer.data, bytes):
|
||||
raise InvalidTokenError(
|
||||
context_msg=f"unwrap_iov IOV {buffer.type.name} buffer at [{idx}] must be bytes"
|
||||
)
|
||||
|
||||
data = buffer.data
|
||||
|
||||
if buffer.type == BufferType.header:
|
||||
if header_idx != -1:
|
||||
raise InvalidTokenError(context_msg="unwrap_iov must only be used with 1 header IOV buffer.")
|
||||
|
||||
header_idx = idx
|
||||
|
||||
elif buffer.type == BufferType.data:
|
||||
if data_idx != -1:
|
||||
raise InvalidTokenError(context_msg="unwrap_iov must only be used with 1 data IOV buffer.")
|
||||
|
||||
data_idx = idx
|
||||
data_sig_idx = len(signature_input)
|
||||
signature_input.append(b"") # Replaced after decryption
|
||||
|
||||
elif buffer.type in [BufferType.sign_only, BufferType.data_readonly]:
|
||||
signature_input.append(data)
|
||||
|
||||
else:
|
||||
raise InvalidTokenError(context_msg=f"unwrap_iov unsupported IOV buffer type {buffer.type.name}")
|
||||
|
||||
res.append(IOVResBuffer(buffer.type, data))
|
||||
|
||||
if header_idx == -1:
|
||||
raise InvalidTokenError(context_msg="unwrap_iov no IOV header buffer present")
|
||||
|
||||
if data_idx == -1:
|
||||
raise InvalidTokenError(context_msg="unwrap_iov no IOV data buffer present")
|
||||
|
||||
dec = self._handle_in.update(res[data_idx].data or b"")
|
||||
res[data_idx] = IOVResBuffer(BufferType.data, dec)
|
||||
signature_input[data_sig_idx] = dec
|
||||
|
||||
self.verify(b"".join(signature_input), res[header_idx].data or b"")
|
||||
|
||||
return IOVUnwrapResult(tuple(res), encrypted=True, qop=0)
|
||||
|
||||
def unwrap_winrm(self, header: bytes, data: bytes) -> bytes:
|
||||
if not self._handle_in:
|
||||
raise NoContextError(context_msg="Cannot unwrap until context has been established")
|
||||
|
||||
msg = self._handle_in.update(data)
|
||||
self.verify(msg, header)
|
||||
|
||||
return msg
|
||||
|
||||
def sign(self, data: bytes, qop: typing.Optional[int] = None) -> bytes:
|
||||
if qop:
|
||||
raise UnsupportedQop(context_msg="Unsupported QoP value %s specified for NTLM" % qop)
|
||||
|
||||
if not self._handle_out or self._sign_key_out is None:
|
||||
raise NoContextError(context_msg="Cannot sign until context has been established")
|
||||
|
||||
return sign(
|
||||
self._context_attr,
|
||||
self._handle_out,
|
||||
self._sign_key_out,
|
||||
self._seq_num_out,
|
||||
data,
|
||||
)
|
||||
|
||||
def verify(self, data: bytes, mic: bytes) -> int:
|
||||
if not self._handle_in or self._sign_key_in is None:
|
||||
raise NoContextError(context_msg="Cannot verify until context has been established")
|
||||
|
||||
expected_sig = sign(
|
||||
self._context_attr,
|
||||
self._handle_in,
|
||||
self._sign_key_in,
|
||||
self._seq_num_in,
|
||||
data,
|
||||
)
|
||||
|
||||
if expected_sig != mic:
|
||||
raise BadMICError(context_msg="Invalid Message integrity Check (MIC) detected")
|
||||
|
||||
return 0
|
||||
|
||||
@property
|
||||
def _context_attr_map(self) -> typing.List[typing.Tuple[ContextReq, int]]:
|
||||
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/a4a41f0d-ca27-44bf-ad1d-6f8c3a3796f2
|
||||
return [
|
||||
(ContextReq.replay_detect, NegotiateFlags.sign),
|
||||
(ContextReq.sequence_detect, NegotiateFlags.sign),
|
||||
(ContextReq.confidentiality, NegotiateFlags.seal),
|
||||
(ContextReq.integrity, NegotiateFlags.sign),
|
||||
]
|
||||
|
||||
@property
|
||||
def _requires_mech_list_mic(self) -> bool:
|
||||
# If called before the Authenticate message has been created it force the MIC to be present on the message.
|
||||
# When called after the Auth message it will return whether the MIC was generated or not.
|
||||
if not self._complete:
|
||||
self._mic_required = True
|
||||
return False
|
||||
|
||||
return self._mic_required
|
||||
|
||||
@property
|
||||
def _seq_num_in(self) -> int:
|
||||
if self._context_attr & NegotiateFlags.extended_session_security:
|
||||
num = self.__seq_num_in
|
||||
self.__seq_num_in += 1
|
||||
|
||||
else:
|
||||
num = self.__seq_num_out
|
||||
self.__seq_num_out += 1
|
||||
|
||||
return num
|
||||
|
||||
@property
|
||||
def _seq_num_out(self) -> int:
|
||||
num = self.__seq_num_out
|
||||
self.__seq_num_out += 1
|
||||
return num
|
||||
|
||||
def _calculate_mic(
|
||||
self,
|
||||
session_key: bytes,
|
||||
negotiate: bytes,
|
||||
challenge: bytes,
|
||||
authenticate: bytes,
|
||||
) -> bytes:
|
||||
"""Calculates the MIC value for the negotiated context."""
|
||||
return hmac_md5(session_key, negotiate + challenge + authenticate)
|
||||
|
||||
def _compute_response(
|
||||
self,
|
||||
challenge: Challenge,
|
||||
credential: _NTLMCredential,
|
||||
channel_bindings: typing.Optional[GssChannelBindings],
|
||||
) -> typing.Tuple[bytes, bytes, bytes]:
|
||||
"""Compute the NT and LM responses and the key exchange key."""
|
||||
client_challenge = os.urandom(8)
|
||||
|
||||
if self._nt_v2:
|
||||
target_info = challenge.target_info.copy() if challenge.target_info else TargetInfo()
|
||||
|
||||
if AvId.timestamp in target_info:
|
||||
time = target_info[AvId.timestamp]
|
||||
self._mic_required = True
|
||||
|
||||
else:
|
||||
time = FileTime.now()
|
||||
|
||||
# The docs seem to indicate that a 0'd bindings hash means to ignore it but that does not seem to be the
|
||||
# case. Instead only add the bindings if they have been specified by the caller.
|
||||
if channel_bindings:
|
||||
target_info[AvId.channel_bindings] = md5(channel_bindings.pack())
|
||||
target_info[AvId.target_name] = self.spn or ""
|
||||
|
||||
if self._mic_required:
|
||||
target_info[AvId.flags] = target_info.get(AvId.flags, AvFlags(0)) | AvFlags.mic
|
||||
|
||||
ntv2_hash = ntowfv2(credential.username or "", credential.nt_hash, credential.domain)
|
||||
nt_challenge, lm_challenge, key_exchange_key = compute_response_v2(
|
||||
ntv2_hash, challenge.server_challenge, client_challenge, time, target_info
|
||||
)
|
||||
|
||||
if self._mic_required:
|
||||
lm_challenge = b"\x00" * 24
|
||||
|
||||
return nt_challenge, lm_challenge, key_exchange_key
|
||||
|
||||
else:
|
||||
return compute_response_v1(
|
||||
challenge.flags,
|
||||
credential.nt_hash,
|
||||
credential.lm_hash,
|
||||
challenge.server_challenge,
|
||||
client_challenge,
|
||||
no_lm_response=not self._lm,
|
||||
)
|
||||
|
||||
def _reset_ntlm_crypto_state(self, outgoing: bool = True) -> None:
|
||||
direction = "out" if outgoing else "in"
|
||||
getattr(self, f"_handle_{direction}").reset()
|
||||
0
env/lib/python3.12/site-packages/spnego/_ntlm_raw/__init__.py
vendored
Normal file
0
env/lib/python3.12/site-packages/spnego/_ntlm_raw/__init__.py
vendored
Normal file
558
env/lib/python3.12/site-packages/spnego/_ntlm_raw/crypto.py
vendored
Normal file
558
env/lib/python3.12/site-packages/spnego/_ntlm_raw/crypto.py
vendored
Normal file
@@ -0,0 +1,558 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
"""NTLM Cryptographic Operations
|
||||
|
||||
Implements the various cryptographic operations that are defined in `MS-NLMP Crypto Operations`_. Some crypto
|
||||
operations aren't implemented due to it being a simple operation in Python.
|
||||
|
||||
.. _MS-NLMP Crypto Operations
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/26c42637-9549-46ae-be2e-90f6f1360193
|
||||
"""
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import io
|
||||
import re
|
||||
import struct
|
||||
import typing
|
||||
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher
|
||||
|
||||
from spnego._ntlm_raw.des import DES
|
||||
from spnego._ntlm_raw.md4 import md4
|
||||
from spnego._ntlm_raw.messages import (
|
||||
FileTime,
|
||||
NegotiateFlags,
|
||||
NTClientChallengeV2,
|
||||
TargetInfo,
|
||||
)
|
||||
|
||||
try:
|
||||
# cryptography 43.0.0 and later moved ARC4 to decrepit
|
||||
from cryptography.hazmat.decrepit.ciphers import algorithms
|
||||
except ImportError:
|
||||
from cryptography.hazmat.primitives.ciphers import ( # type: ignore[no-redef]
|
||||
algorithms,
|
||||
)
|
||||
|
||||
# A user does not need to specify their actual plaintext password they can specify the LM and NT hash (from lmowfv1 and
|
||||
# ntowfv2) in the form 'lm_hash_hex:nt_hash_hex'. This is still considered a plaintext pass as we can use it to build
|
||||
# the LM and NT response but it's only usable for NTLM.
|
||||
_NTLM_HASH_PATTERN = re.compile(r"^[a-fA-F0-9]{32}:[a-fA-F0-9]{32}$")
|
||||
|
||||
|
||||
class RC4Handle:
|
||||
"""RC4 class to wrap the underlying crypto function."""
|
||||
|
||||
def __init__(self, key: bytes) -> None:
|
||||
self._key = key
|
||||
|
||||
arc4 = algorithms.ARC4(self._key)
|
||||
cipher = Cipher(arc4, mode=None, backend=default_backend())
|
||||
self._handle = cipher.encryptor()
|
||||
|
||||
def update(self, b_data: bytes) -> bytes:
|
||||
"""Update the RC4 stream and return the encrypted/decrypted bytes."""
|
||||
return self._handle.update(b_data)
|
||||
|
||||
def reset(self) -> None:
|
||||
"""Reset's the cipher stream back to the original state."""
|
||||
arc4 = algorithms.ARC4(self._key)
|
||||
cipher = Cipher(arc4, mode=None, backend=default_backend())
|
||||
self._handle = cipher.encryptor()
|
||||
|
||||
|
||||
def is_ntlm_hash(password: str) -> bool:
|
||||
return bool(_NTLM_HASH_PATTERN.match(password))
|
||||
|
||||
|
||||
def compute_response_v1(
|
||||
flags: int,
|
||||
nt_hash: bytes,
|
||||
lm_hash: bytes,
|
||||
server_challenge: bytes,
|
||||
client_challenge: bytes,
|
||||
no_lm_response: bool = True,
|
||||
) -> typing.Tuple[bytes, bytes, bytes]:
|
||||
"""Compute NT and LM Response for NTLMv1.
|
||||
|
||||
Computes the NT and LM Response for NTLMv1 messages. The response is dependent on the flags that were negotiated
|
||||
between the client and server.
|
||||
|
||||
The pseudo-code for this function as documented under `NTLM v1 Authentication`_ is::
|
||||
|
||||
Define ComputeResponse(NegFlg, ResponseKeyNT, ResponseKeyLM, CHALLENGE_MESSAGE.ServerChallenge,
|
||||
ClientChallenge, Time, ServerName) As
|
||||
|
||||
If (User is set to "" AND Passwd is set to "")
|
||||
-- Special case for anonymous authentication
|
||||
Set NtChallengeResponseLen to 0
|
||||
Set NtChallengeResponseMaxLen to 0
|
||||
Set NtChallengeResponseBufferOffset to 0
|
||||
|
||||
Set LmChallengeResponse to Z(1)
|
||||
ElseIf
|
||||
If (NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY flag is set in NegFlg)
|
||||
Set NtChallengeResponse to DESL(ResponseKeyNT,
|
||||
MD5(ConcatenationOf(CHALLENGE_MESSAGE.ServerChallenge, ClientChallenge))[0..7])
|
||||
|
||||
Set LmChallengeResponse to ConcatenationOf{ClientChallenge, Z(16)}
|
||||
Else
|
||||
Set NtChallengeResponse to DESL(ResponseKeyNT, CHALLENGE_MESSAGE.ServerChallenge)
|
||||
|
||||
If (NoLMResponseNTLMv1 is TRUE)
|
||||
Set LmChallengeResponse to NtChallengeResponse
|
||||
Else
|
||||
Set LmChallengeResponse to DESL(ResponseKeyLM, CHALLENGE_MESSAGE.ServerChallenge)
|
||||
EndIf
|
||||
EndIf
|
||||
EndIf
|
||||
|
||||
Set SessionBaseKey to MD4(NTOWF)
|
||||
|
||||
Args:
|
||||
flags: The negotiated flags between the initiator and acceptor.
|
||||
nt_hash: The response key computed by :meth:`ntowfv1`.
|
||||
lm_hash: The response key computed by :meth:`lmowfv1`.
|
||||
server_challenge: The 8 byte nonce generated by the acceptor.
|
||||
client_challenge: The 8 byte nonce generated by the initiator.
|
||||
no_lm_response: Whether to compute (True) the `LmChallengeResponse` or not (False) when extended session
|
||||
security was not negotiated.
|
||||
|
||||
Returns:
|
||||
Tuple[bytes, bytes, bytes]: Returns the NTChallengeResponse, LMChallengeResponse and KeyExchangeKey.
|
||||
|
||||
.. _NTLM v1 Authentication:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/464551a8-9fc4-428e-b3d3-bc5bfb2e73a5
|
||||
"""
|
||||
if flags & NegotiateFlags.extended_session_security:
|
||||
nt_response = desl(nt_hash, md5(server_challenge + client_challenge[:8]))
|
||||
lm_response = client_challenge + (b"\x00" * 16)
|
||||
|
||||
else:
|
||||
nt_response = lm_response = desl(nt_hash, server_challenge)
|
||||
|
||||
if not no_lm_response:
|
||||
lm_response = desl(lm_hash, server_challenge)
|
||||
|
||||
session_base_key = md4(nt_hash)
|
||||
key_exchange_key = kxkey(flags, session_base_key, lm_hash, lm_response, server_challenge)
|
||||
|
||||
return nt_response, lm_response, key_exchange_key
|
||||
|
||||
|
||||
def compute_response_v2(
|
||||
nt_hash: bytes,
|
||||
server_challenge: bytes,
|
||||
client_challenge: bytes,
|
||||
time: FileTime,
|
||||
av_pairs: TargetInfo,
|
||||
) -> typing.Tuple[bytes, bytes, bytes]:
|
||||
"""Compute NT and LM Response for NTLMv2.
|
||||
|
||||
Computes the NT and LM Response for NTLMv2 messages. The response is dependent on the flags that were negotiated
|
||||
between the client and server.
|
||||
|
||||
The pseudo-code for this function as documented under `NTLM v2 Authentication`_ is::
|
||||
|
||||
Define ComputeResponse(NegFlg, ResponseKeyNT, ResponseKeyLM, CHALLENGE_MESSAGE.ServerChallenge,
|
||||
ClientChallenge, Time, ServerName) As
|
||||
|
||||
If (User is set to "" && Passwd is set to "")
|
||||
-- Special case for anonymous authentication
|
||||
Set NtChallengeResponseLen to 0
|
||||
Set NtChallengeResponseMaxLen to 0
|
||||
Set NtChallengeResponseBufferOffset to 0
|
||||
|
||||
Set LmChallengeResponse to Z(1)
|
||||
Else
|
||||
Set temp to ConcatenationOf(Responserversion, HiResponserversion, Z(6), Time, ClientChallenge, Z(4),
|
||||
ServerName, Z(4))
|
||||
|
||||
Set NTProofStr to HMAC_MD5(ResponseKeyNT, ConcatenationOf(CHALLENGE_MESSAGE.ServerChallenge,temp))
|
||||
|
||||
Set NtChallengeResponse to ConcatenationOf(NTProofStr, temp)
|
||||
|
||||
Set LmChallengeResponse to ConcatenationOf(
|
||||
HMAC_MD5(ResponseKeyLM, ConcatenationOf(CHALLENGE_MESSAGE.ServerChallenge, ClientChallenge)),
|
||||
ClientChallenge)
|
||||
EndIf
|
||||
|
||||
Set SessionBaseKey to HMAC_MD5(ResponseKeyNT, NTProofStr)
|
||||
|
||||
Args:
|
||||
nt_hash: The response key computed by :meth:`ntwofv2`. The `ResponseKeyLM` is the same value so we only
|
||||
pass in the 1 key.
|
||||
server_challenge: The 8 byte nonce generated by the acceptor.
|
||||
client_challenge: The 8 byte nonce generated by the initiator.
|
||||
time: The FileTime to place in the NT hash.
|
||||
av_pairs: The TargetInfo AvPairs fields that are placed in the Authenticate message.
|
||||
|
||||
Returns:
|
||||
Tuple[bytes, bytes, bytes]: Returns the NTChallengeResponse, LMChallengeResponse and KeyExchangeKey.
|
||||
|
||||
.. _NTLM v2 Authentication:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/5e550938-91d4-459f-b67d-75d70009e3f3
|
||||
"""
|
||||
temp = NTClientChallengeV2(time_stamp=time, client_challenge=client_challenge, av_pairs=av_pairs)
|
||||
b_temp = temp.pack() + b"\x00\x00\x00\x00"
|
||||
nt_proof_str = hmac_md5(nt_hash, server_challenge + b_temp)
|
||||
|
||||
nt_response = nt_proof_str + b_temp
|
||||
lm_response = hmac_md5(nt_hash, server_challenge + client_challenge) + client_challenge
|
||||
session_base_key = hmac_md5(nt_hash, nt_proof_str)
|
||||
|
||||
return nt_response, lm_response, session_base_key # Is KeyExchangeKey in NTLMv2.
|
||||
|
||||
|
||||
def crc32(m: bytes) -> bytes:
|
||||
"""Simple wrapper function to generate a CRC32 checksum."""
|
||||
# We bitand to ensure the value is the same across all Python versions.
|
||||
return struct.pack("<I", binascii.crc32(m) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def des(k: bytes, d: bytes) -> bytes:
|
||||
"""DES encryption.
|
||||
|
||||
Indicates the encryption of an 8-byte data item `d` with the 7-byte key `k` using the Data Encryption Standard
|
||||
(DES) algorithm in Electronic Codebook (ECB) mode. The result is 8 bytes in length ([FIPS46-2]).
|
||||
|
||||
Args:
|
||||
k: The 7-byte key to use in the DES cipher.
|
||||
d: The 8-byte data block to encrypt.
|
||||
|
||||
Returns:
|
||||
bytes: The encrypted data block.
|
||||
"""
|
||||
return DES(DES.key56_to_key64(k)).encrypt(d)
|
||||
|
||||
|
||||
def desl(k: bytes, d: bytes) -> bytes:
|
||||
"""Encryption using the DES Long algorithm.
|
||||
|
||||
Indicates the encryption of an 8-byte data item `d` with the 16-byte key `k` using the Data Encryption
|
||||
Standard Long (DESL) algorithm. The result is 24 bytes in length.
|
||||
|
||||
`DESL(K, D)` as by MS-NLMP `DESL`_ is computed as follows::
|
||||
|
||||
ConcatenationOf(
|
||||
DES(K[0..6], D),
|
||||
DES(K[7..13], D),
|
||||
DES(ConcatenationOf(K[14..15], Z(5)), D),
|
||||
);
|
||||
|
||||
Args:
|
||||
k: The key to use for the DES cipher, will be truncated to 16 bytes and then padded to 21 bytes.
|
||||
d: The value to run through the DESL algorithm, will be truncated to 8 bytes.
|
||||
|
||||
Returns:
|
||||
bytes: The output of the DESL algorithm.
|
||||
|
||||
.. _DESL:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/26c42637-9549-46ae-be2e-90f6f1360193
|
||||
"""
|
||||
k = k[:16].ljust(21, b"\x00") # Key needs to be stripped at 16 characters and then padded to 21 chars.
|
||||
d = d[:8].ljust(8, b"\x00") # Data need to be at most 8 bytes long.
|
||||
|
||||
b_value = io.BytesIO()
|
||||
|
||||
b_value.write(des(k[:7], d))
|
||||
b_value.write(des(k[7:14], d))
|
||||
b_value.write(des(k[14:], d))
|
||||
|
||||
return b_value.getvalue()
|
||||
|
||||
|
||||
def hmac_md5(key: bytes, data: bytes) -> bytes:
|
||||
"""Simple wrapper function for a HMAC MD5 digest."""
|
||||
return hmac.new(key, data, digestmod=hashlib.md5).digest()
|
||||
|
||||
|
||||
def kxkey(
|
||||
flags: int,
|
||||
session_base_key: bytes,
|
||||
lmowf: bytes,
|
||||
lm_response: bytes,
|
||||
server_challenge: bytes,
|
||||
) -> bytes:
|
||||
"""NTLM KXKEY function.
|
||||
|
||||
The MS-NLMP `KXKEY`_ function used to derive the key exchange key for a security context. This is only for NTLMv1
|
||||
contexts as NTLMv2 just re-uses the session base key.
|
||||
|
||||
Args:
|
||||
flags: The negotiate flags in the Challenge msg.
|
||||
session_base_key: The session base key from :meth:`compute_response_v1`.
|
||||
lmowf: The LM hash from :meth:`lmowfv1`.
|
||||
lm_response: The lm response from :meth:`compute_response_v1`.
|
||||
server_challenge: The server challenge in the Challenge msg.
|
||||
|
||||
Returns:
|
||||
bytes: The derived key exchange key.
|
||||
|
||||
.. _KXKEY:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/d86303b5-b29e-4fb9-b119-77579c761370
|
||||
"""
|
||||
if flags & NegotiateFlags.extended_session_security:
|
||||
return hmac_md5(session_base_key, server_challenge + lm_response[:8])
|
||||
|
||||
elif flags & NegotiateFlags.lm_key:
|
||||
b_data = lm_response[:8]
|
||||
return des(lmowf[:7], b_data) + des(lmowf[7:8] + b"\xbd\xbd\xbd\xbd\xbd\xbd", b_data)
|
||||
|
||||
elif flags & NegotiateFlags.non_nt_session_key:
|
||||
return lmowf[:8] + b"\x00" * 8
|
||||
|
||||
else:
|
||||
return session_base_key
|
||||
|
||||
|
||||
def lmowfv1(password: str) -> bytes:
|
||||
"""NTLMv1 LMOWFv1 function
|
||||
|
||||
The Lan Manager v1 one way function as documented under `NTLM v1 Authentication`_.
|
||||
|
||||
The pseudo-code for this function is::
|
||||
|
||||
Define LMOWFv1(Passwd, User, UserDom) as
|
||||
ConcatenationOf(
|
||||
DES(UpperCase(Passwd)[0..6], "KGS!@#$%"),
|
||||
DES(UpperCase(Passwd)[7..13], "KGS!@#$%"),
|
||||
);
|
||||
|
||||
Args:
|
||||
password: The password for the user.
|
||||
|
||||
Returns:
|
||||
bytes: The LMv1 one way hash of the user's password.
|
||||
|
||||
.. _NTLM v1 Authentication:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/464551a8-9fc4-428e-b3d3-bc5bfb2e73a5
|
||||
"""
|
||||
if is_ntlm_hash(password):
|
||||
return base64.b16decode(password.split(":")[0].upper())
|
||||
|
||||
# Fix the password to upper case and pad the length to exactly 14 bytes. While it is true LM only authentication
|
||||
# will fail if the password exceeds 14 bytes typically it is used in conjunction with the NTv1 hash which has no
|
||||
# such restrictions.
|
||||
b_password = password.upper().encode("utf-8", errors="surrogatepass").ljust(14, b"\x00")[:14]
|
||||
|
||||
b_hash = io.BytesIO()
|
||||
for start, end in [(0, 7), (7, 14)]:
|
||||
b_hash.write(des(b_password[start:end], b"KGS!@#$%"))
|
||||
|
||||
return b_hash.getvalue()
|
||||
|
||||
|
||||
def md5(m: bytes) -> bytes:
|
||||
"""Simple wrapper to generate a MD5 checksum."""
|
||||
return hashlib.md5(m).digest()
|
||||
|
||||
|
||||
def ntowfv1(password: str) -> bytes:
|
||||
"""NTLMv1 NTOWFv1 function
|
||||
|
||||
The NT v1 one way function as documented under `NTLM v1 Authentication`_.
|
||||
|
||||
The pseudo-code for this function is::
|
||||
|
||||
Define NTOWFv1(Passwd, User, UserDom) as MD4(UNICODE(Passwd))
|
||||
|
||||
Args:
|
||||
password: The password for the user.
|
||||
|
||||
Returns:
|
||||
bytes: The NTv1 one way hash of the user's password.
|
||||
|
||||
.. _NTLM v1 Authentication:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/464551a8-9fc4-428e-b3d3-bc5bfb2e73a5
|
||||
"""
|
||||
if is_ntlm_hash(password):
|
||||
return base64.b16decode(password.split(":")[1].upper())
|
||||
|
||||
return md4(password.encode("utf-16-le", errors="surrogatepass"))
|
||||
|
||||
|
||||
def ntowfv2(username: str, nt_hash: bytes, domain_name: typing.Optional[str]) -> bytes:
|
||||
"""NTLMv2 NTOWFv2 function
|
||||
|
||||
The NT v2 one way function as documented under `NTLM v2 Authentication`_.
|
||||
|
||||
The pseudo-code for this function is::
|
||||
|
||||
Define NTOWFv2(Passwd, User, UserDom) as
|
||||
|
||||
HMAC_MD5(MD4(UNICODE(Passwd)), UNICODE(ConcatenationOf(Uppercase(User), UserDom)))
|
||||
|
||||
Args:
|
||||
username: The username.
|
||||
nt_hash: The NT hash from :meth:`ntowfv1`.
|
||||
domain_name: The optional domain name of the user.
|
||||
|
||||
Returns:
|
||||
bytes: The NTv2 one way has of the user's credentials.
|
||||
|
||||
.. _NTLM v2 Authentication:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/5e550938-91d4-459f-b67d-75d70009e3f3
|
||||
"""
|
||||
b_user = (username.upper() + (domain_name or "")).encode("utf-16-le")
|
||||
return hmac_md5(nt_hash, b_user)
|
||||
|
||||
|
||||
def rc4(h: RC4Handle, d: bytes) -> bytes:
|
||||
"""RC4 encryption of the data specified using the handle generated by rc4init."""
|
||||
return h.update(d)
|
||||
|
||||
|
||||
def rc4k(k: bytes, d: bytes) -> bytes:
|
||||
"""RC4 encryption with an explicit key.
|
||||
|
||||
Indicates the encryption of data item `d` with the key `k` using the `RC4`_ algorithm.
|
||||
|
||||
Args:
|
||||
k: The key to use for the RC4 cipher.
|
||||
d: The data to encrypt.
|
||||
|
||||
Returns:
|
||||
bytes: The RC4 encrypted bytes.
|
||||
|
||||
.. _RC4K:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/26c42637-9549-46ae-be2e-90f6f1360193
|
||||
"""
|
||||
return rc4init(k).update(d)
|
||||
|
||||
|
||||
def rc4init(k: bytes) -> RC4Handle:
|
||||
"""Initialization of the RC4 handle using the key specified."""
|
||||
return RC4Handle(k)
|
||||
|
||||
|
||||
def sealkey(flags: int, session_key: bytes, usage: str) -> bytes:
|
||||
"""NTLM SEALKEY function.
|
||||
|
||||
The MS-NLMP `SEALKEY`_ function used to generate the sealing keys for a security context.
|
||||
|
||||
The pseudo-code for this function as documented under `SEALKEY`_ is::
|
||||
|
||||
Define SEALKEY(NegFlg, ExportedSessionKey, Mode) as
|
||||
|
||||
If (NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY flag is set in NegFlg)
|
||||
|
||||
If ( NTLMSSP_NEGOTIATE_128 is set in NegFlg)
|
||||
Set SealKey to ExportedSessionKey
|
||||
|
||||
ElseIf ( NTLMSSP_NEGOTIATE_56 flag is set in NegFlg)
|
||||
Set SealKey to ExportedSessionKey[0..6]
|
||||
|
||||
Else
|
||||
Set SealKey to ExportedSessionKey[0..4]
|
||||
|
||||
Endif
|
||||
|
||||
If (Mode equals "Client")
|
||||
Set SealKey to MD5(ConcatenationOf(SealKey,
|
||||
"session key to client-to-server sealing key magic constant"))
|
||||
|
||||
Else
|
||||
Set SealKey to MD5(ConcatenationOf(SealKey,
|
||||
"session key to server-to-client sealing key magic constant"))
|
||||
|
||||
Endif
|
||||
ElseIf ((NTLMSSP_NEGOTIATE_LM_KEY is set in NegFlg) or ((NTLMSSP_NEGOTIATE_DATAGRAM is set in NegFlg) and
|
||||
(NTLMRevisionCurrent >= NTLMSSP_REVISION_W2K3)))
|
||||
|
||||
If (NTLMSSP_NEGOTIATE_56 flag is set in NegFlg)
|
||||
Set SealKey to ConcatenationOf(ExportedSessionKey[0..6], 0xA0)
|
||||
|
||||
Else
|
||||
Set SealKey to ConcatenationOf(ExportedSessionKey[0..4], 0xE5, 0x38, 0xB0)
|
||||
|
||||
EndIf
|
||||
|
||||
Else
|
||||
Set SealKey to ExportedSessionKey
|
||||
Endif
|
||||
EndDefine
|
||||
|
||||
Args:
|
||||
flags: The negotiated flags between the initiator and acceptor.
|
||||
session_key: The derived session key.
|
||||
usage: Whether the sealing key is for the 'initiate' or 'accept' context.
|
||||
|
||||
Returns:
|
||||
bytes: The derived sealing key.
|
||||
|
||||
.. _SEALKEY:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/bf39181d-e95d-40d7-a740-ab4ec3dc363d
|
||||
"""
|
||||
if flags & NegotiateFlags.extended_session_security:
|
||||
if flags & NegotiateFlags.key_128:
|
||||
seal_key = session_key
|
||||
|
||||
elif flags & NegotiateFlags.key_56:
|
||||
seal_key = session_key[:7]
|
||||
|
||||
else:
|
||||
seal_key = session_key[:5]
|
||||
|
||||
direction = b"client-to-server" if usage == "initiate" else b"server-to-client"
|
||||
|
||||
return md5(seal_key + b"session key to %s sealing key magic constant\x00" % direction)
|
||||
|
||||
elif flags & NegotiateFlags.lm_key or flags & NegotiateFlags.datagram:
|
||||
if flags & NegotiateFlags.key_56:
|
||||
return session_key[:7] + b"\xa0"
|
||||
|
||||
else:
|
||||
return session_key[:5] + b"\xe5\x38\xb0"
|
||||
|
||||
else:
|
||||
return session_key
|
||||
|
||||
|
||||
def signkey(flags: int, session_key: bytes, usage: str) -> bytes:
|
||||
"""NTLM SIGNKEY function.
|
||||
|
||||
The MS-NLMP `SIGNKEY`_ function used to generate the signing keys for a security context.
|
||||
|
||||
The pseudo-code for this function as documented under `SIGNKEY`_ is::
|
||||
|
||||
Define SIGNKEY(NegFlg, ExportedSessionKey, Mode) as
|
||||
|
||||
If (NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY flag is set in NegFlg)
|
||||
If (Mode equals "Client")
|
||||
Set SignKey to MD5(ConcatenationOf(ExportedSessionKey,
|
||||
"session key to client-to-server signing key magic constant"))
|
||||
|
||||
Else
|
||||
Set SignKey to MD5(ConcatenationOf(ExportedSessionKey,
|
||||
"session key to server-to-client signing key magic constant"))
|
||||
|
||||
Endif
|
||||
Else
|
||||
Set SignKey to NIL
|
||||
|
||||
Endif
|
||||
EndDefine
|
||||
|
||||
Args:
|
||||
flags: The negotiated flags between the initiator and acceptor.
|
||||
session_key: The derived session key.
|
||||
usage: Whether the signing key is for the 'initiate' or 'accept' context.
|
||||
|
||||
Returns:
|
||||
bytes: The derived singing key.
|
||||
|
||||
.. _SIGNKEY:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/524cdccb-563e-4793-92b0-7bc321fce096
|
||||
"""
|
||||
if flags & NegotiateFlags.extended_session_security == 0:
|
||||
return b""
|
||||
|
||||
direction = b"client-to-server" if usage == "initiate" else b"server-to-client"
|
||||
|
||||
return md5(session_key + b"session key to %s signing key magic constant\x00" % direction)
|
||||
1124
env/lib/python3.12/site-packages/spnego/_ntlm_raw/des.py
vendored
Normal file
1124
env/lib/python3.12/site-packages/spnego/_ntlm_raw/des.py
vendored
Normal file
File diff suppressed because it is too large
Load Diff
139
env/lib/python3.12/site-packages/spnego/_ntlm_raw/md4.py
vendored
Normal file
139
env/lib/python3.12/site-packages/spnego/_ntlm_raw/md4.py
vendored
Normal file
@@ -0,0 +1,139 @@
|
||||
# Copyright: (c) 2022, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import struct
|
||||
import typing as t
|
||||
|
||||
|
||||
def F(x: int, y: int, z: int) -> int:
|
||||
return (x & y) | (~x & z)
|
||||
|
||||
|
||||
def G(x: int, y: int, z: int) -> int:
|
||||
return (x & y) | (x & z) | (y & z)
|
||||
|
||||
|
||||
def H(x: int, y: int, z: int) -> int:
|
||||
return x ^ y ^ z
|
||||
|
||||
|
||||
def ROTL(x: int, n: int) -> int:
|
||||
return ((x << n) & 0xFFFFFFFF) | (x >> (32 - n))
|
||||
|
||||
|
||||
def FF(a: int, b: int, c: int, d: int, x: int, s: int) -> int:
|
||||
return ROTL((a + F(b, c, d) + x) & 0xFFFFFFFF, s)
|
||||
|
||||
|
||||
def GG(a: int, b: int, c: int, d: int, x: int, s: int) -> int:
|
||||
return ROTL((a + G(b, c, d) + x + 0x5A827999) & 0xFFFFFFFF, s)
|
||||
|
||||
|
||||
def HH(a: int, b: int, c: int, d: int, x: int, s: int) -> int:
|
||||
return ROTL((a + H(b, c, d) + x + 0x6ED9EBA1) & 0xFFFFFFFF, s)
|
||||
|
||||
|
||||
def md4(data: bytes) -> bytes:
|
||||
"""Python implementation of md4 hashing.
|
||||
|
||||
This is a pure Python implementation of the `MD4 Hashing Algorithm`_.
|
||||
Recent distributions of Linux ship with OpenSSL 3.x which has disabled the
|
||||
md4 engine so for backwards compatibility this must be manually implemented
|
||||
here to ensure NTLM continues to work.
|
||||
|
||||
.. _MD4 Hasing Algorithm:
|
||||
https://datatracker.ietf.org/doc/html/rfc1320
|
||||
"""
|
||||
data_block = bytearray(data)
|
||||
orig_length = len(data)
|
||||
b_orig_length = ((orig_length * 8) & 0xFFFFFFFFFFFFFFFF).to_bytes(8, "little")
|
||||
|
||||
# Need to pad the last block to 64 bytes, the first bit is set to 1 and the
|
||||
# last 8 bytes are the length of the input data.
|
||||
data_block += b"".join(
|
||||
[
|
||||
b"\x80",
|
||||
bytes((55 - orig_length % 64) % 64),
|
||||
b_orig_length,
|
||||
]
|
||||
)
|
||||
|
||||
A = 0x67452301
|
||||
B = 0xEFCDAB89
|
||||
C = 0x98BADCFE
|
||||
D = 0x10325476
|
||||
|
||||
while data_block:
|
||||
AA, BB, CC, DD = A, B, C, D
|
||||
X = struct.unpack("<16I", data_block[:64])
|
||||
data_block = data_block[64:]
|
||||
|
||||
# Round 1
|
||||
AA = FF(AA, BB, CC, DD, X[0], 3)
|
||||
DD = FF(DD, AA, BB, CC, X[1], 7)
|
||||
CC = FF(CC, DD, AA, BB, X[2], 11)
|
||||
BB = FF(BB, CC, DD, AA, X[3], 19)
|
||||
|
||||
AA = FF(AA, BB, CC, DD, X[4], 3)
|
||||
DD = FF(DD, AA, BB, CC, X[5], 7)
|
||||
CC = FF(CC, DD, AA, BB, X[6], 11)
|
||||
BB = FF(BB, CC, DD, AA, X[7], 19)
|
||||
|
||||
AA = FF(AA, BB, CC, DD, X[8], 3)
|
||||
DD = FF(DD, AA, BB, CC, X[9], 7)
|
||||
CC = FF(CC, DD, AA, BB, X[10], 11)
|
||||
BB = FF(BB, CC, DD, AA, X[11], 19)
|
||||
|
||||
AA = FF(AA, BB, CC, DD, X[12], 3)
|
||||
DD = FF(DD, AA, BB, CC, X[13], 7)
|
||||
CC = FF(CC, DD, AA, BB, X[14], 11)
|
||||
BB = FF(BB, CC, DD, AA, X[15], 19)
|
||||
|
||||
# Round 2
|
||||
AA = GG(AA, BB, CC, DD, X[0], 3)
|
||||
DD = GG(DD, AA, BB, CC, X[4], 5)
|
||||
CC = GG(CC, DD, AA, BB, X[8], 9)
|
||||
BB = GG(BB, CC, DD, AA, X[12], 13)
|
||||
|
||||
AA = GG(AA, BB, CC, DD, X[1], 3)
|
||||
DD = GG(DD, AA, BB, CC, X[5], 5)
|
||||
CC = GG(CC, DD, AA, BB, X[9], 9)
|
||||
BB = GG(BB, CC, DD, AA, X[13], 13)
|
||||
|
||||
AA = GG(AA, BB, CC, DD, X[2], 3)
|
||||
DD = GG(DD, AA, BB, CC, X[6], 5)
|
||||
CC = GG(CC, DD, AA, BB, X[10], 9)
|
||||
BB = GG(BB, CC, DD, AA, X[14], 13)
|
||||
|
||||
AA = GG(AA, BB, CC, DD, X[3], 3)
|
||||
DD = GG(DD, AA, BB, CC, X[7], 5)
|
||||
CC = GG(CC, DD, AA, BB, X[11], 9)
|
||||
BB = GG(BB, CC, DD, AA, X[15], 13)
|
||||
|
||||
# Round 3
|
||||
AA = HH(AA, BB, CC, DD, X[0], 3)
|
||||
DD = HH(DD, AA, BB, CC, X[8], 9)
|
||||
CC = HH(CC, DD, AA, BB, X[4], 11)
|
||||
BB = HH(BB, CC, DD, AA, X[12], 15)
|
||||
|
||||
AA = HH(AA, BB, CC, DD, X[2], 3)
|
||||
DD = HH(DD, AA, BB, CC, X[10], 9)
|
||||
CC = HH(CC, DD, AA, BB, X[6], 11)
|
||||
BB = HH(BB, CC, DD, AA, X[14], 15)
|
||||
|
||||
AA = HH(AA, BB, CC, DD, X[1], 3)
|
||||
DD = HH(DD, AA, BB, CC, X[9], 9)
|
||||
CC = HH(CC, DD, AA, BB, X[5], 11)
|
||||
BB = HH(BB, CC, DD, AA, X[13], 15)
|
||||
|
||||
AA = HH(AA, BB, CC, DD, X[3], 3)
|
||||
DD = HH(DD, AA, BB, CC, X[11], 9)
|
||||
CC = HH(CC, DD, AA, BB, X[7], 11)
|
||||
BB = HH(BB, CC, DD, AA, X[15], 15)
|
||||
|
||||
A = (A + AA) & 0xFFFFFFFF
|
||||
B = (B + BB) & 0xFFFFFFFF
|
||||
C = (C + CC) & 0xFFFFFFFF
|
||||
D = (D + DD) & 0xFFFFFFFF
|
||||
|
||||
return struct.pack("<IIII", A, B, C, D)
|
||||
1223
env/lib/python3.12/site-packages/spnego/_ntlm_raw/messages.py
vendored
Normal file
1223
env/lib/python3.12/site-packages/spnego/_ntlm_raw/messages.py
vendored
Normal file
File diff suppressed because it is too large
Load Diff
184
env/lib/python3.12/site-packages/spnego/_ntlm_raw/security.py
vendored
Normal file
184
env/lib/python3.12/site-packages/spnego/_ntlm_raw/security.py
vendored
Normal file
@@ -0,0 +1,184 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import struct
|
||||
import typing
|
||||
|
||||
from spnego._ntlm_raw.crypto import RC4Handle, crc32, hmac_md5, rc4
|
||||
from spnego._ntlm_raw.messages import NegotiateFlags
|
||||
from spnego.exceptions import OperationNotAvailableError
|
||||
|
||||
|
||||
def seal(
|
||||
flags: int,
|
||||
handle: RC4Handle,
|
||||
signing_key: bytes,
|
||||
seq_num: int,
|
||||
b_data: bytes,
|
||||
*,
|
||||
to_sign: typing.Optional[bytes] = None,
|
||||
) -> typing.Tuple[bytes, bytes]:
|
||||
"""Create a sealed NTLM message.
|
||||
|
||||
Creates a sealed NTLM message as documented at `NTLM Message Confidentiality`_.
|
||||
|
||||
Args:
|
||||
flags: The negotiated flags between the initiator and acceptor.
|
||||
handle: The RC4 handle for the negotiated context.
|
||||
signing_key: The key used to sign the message.
|
||||
seq_num: The sequence number for the message.
|
||||
b_data: The data/message bytes to seal.
|
||||
|
||||
Returns:
|
||||
Tuple[bytes, bytes]: The sealed message bytes and the message signature.
|
||||
|
||||
.. _NTLM Message Confidentiality:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/115f9c7d-bc30-4262-ae96-254555c14ea6
|
||||
"""
|
||||
seal_msg = rc4(handle, b_data)
|
||||
signature = sign(flags, handle, signing_key, seq_num, to_sign if to_sign else b_data)
|
||||
return seal_msg, signature
|
||||
|
||||
|
||||
def sign(
|
||||
flags: int,
|
||||
handle: RC4Handle,
|
||||
signing_key: bytes,
|
||||
seq_num: int,
|
||||
b_data: bytes,
|
||||
) -> bytes:
|
||||
"""Create a NTLM signature.
|
||||
|
||||
Creates a NTLM signature as documented at `NTLM Message Integrity`_ and appends it to the end of the message.
|
||||
|
||||
Args:
|
||||
flags: The negotiated flags between the initiator and acceptor.
|
||||
handle: The RC4 handle for the negotiated context.
|
||||
signing_key: The key used to sign the message.
|
||||
seq_num: The sequence number for the signature.
|
||||
b_data: The data/message bytes to sign.
|
||||
|
||||
Returns:
|
||||
bytes: The data with the signature appended.
|
||||
|
||||
.. _NTLM Message Integrity:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/131b0062-7958-460e-bca5-c7a9f9086652
|
||||
"""
|
||||
if flags & NegotiateFlags.sign == 0:
|
||||
if flags & NegotiateFlags.always_sign == 0:
|
||||
raise OperationNotAvailableError(context_msg="Signing without integrity.")
|
||||
|
||||
# This is the behaviour seen with SSPI when signing data with NTLMSSP_NEGOTIATE_ALWAYS_SIGN.
|
||||
return b"\x01" + b"\x00" * 15
|
||||
|
||||
elif flags & NegotiateFlags.extended_session_security:
|
||||
return _mac_with_ess(flags, handle, signing_key, seq_num, b_data)
|
||||
|
||||
else:
|
||||
return _mac_without_ess(handle, seq_num, b_data)
|
||||
|
||||
|
||||
def _mac_without_ess(
|
||||
handle: RC4Handle,
|
||||
seq_num: int,
|
||||
b_data: bytes,
|
||||
) -> bytes:
|
||||
"""NTLM MAC without Extended Session Security
|
||||
|
||||
Generates the NTLM signature when Extended Session Security has not been negotiated. The structure of the signature
|
||||
is documented at `NTLM signature without ESS`_.
|
||||
|
||||
The algorithm as documented by `MAC without ESS`_ is::
|
||||
|
||||
Define MAC(Handle, SigningKey, SeqNum, Message) as
|
||||
Set NTLMSSP_MESSAGE_SIGNATURE.Version to 0x00000001
|
||||
Set NTLMSSP_MESSAGE_SIGNATURE.Checksum to CRC32(Message)
|
||||
Set NTLMSSP_MESSAGE_SIGNATURE.RandomPad RC4(Handle, RandomPad)
|
||||
Set NTLMSSP_MESSAGE_SIGNATURE.Checksum to RC4(Handle, NTLMSSP_MESSAGE_SIGNATURE.Checksum)
|
||||
Set NTLMSSP_MESSAGE_SIGNATURE.SeqNum to RC4(Handle, 0x00000000)
|
||||
|
||||
If (connection oriented)
|
||||
Set NTLMSSP_MESSAGE_SIGNATURE.SeqNum to NTLMSSP_MESSAGE_SIGNATURE.SeqNum XOR SeqNum
|
||||
Set SeqNum to SeqNum + 1
|
||||
|
||||
Else
|
||||
Set NTLMSSP_MESSAGE_SIGNATURE.SeqNum to NTLMSSP_MESSAGE_SIGNATURE.SeqNum XOR (app supplied SeqNum)
|
||||
|
||||
Endif
|
||||
|
||||
Set NTLMSSP_MESSAGE_SIGNATURE.RandomPad to 0
|
||||
|
||||
EndDefine
|
||||
|
||||
Args:
|
||||
handle: The RC4 handle for the negotiated context.
|
||||
seq_num: The sequence number for the signature.
|
||||
b_data: The data/message bytes to sign.
|
||||
|
||||
Returns:
|
||||
bytes: The NTLM signature.
|
||||
|
||||
.. _NTLM signature without ESS:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/83fbd0e7-8ab0-4873-8cbe-795249b46b8a
|
||||
|
||||
.. _MAC without ESS:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/0b1fb6a6-7224-4d5b-af35-fdd45c0791e5
|
||||
"""
|
||||
checksum = crc32(b_data)
|
||||
rc4(handle, b"\x00\x00\x00\x00") # NTLMSSP_MESSAGE_SIGNATURE.RandomPad RC4(Handle, RandomPad)
|
||||
checksum = rc4(handle, checksum)
|
||||
|
||||
temp_seq_num = struct.unpack("<I", rc4(handle, b"\x00\x00\x00\x00"))[0]
|
||||
b_seq_num = struct.pack("<I", temp_seq_num ^ seq_num)
|
||||
|
||||
return b"\x01\x00\x00\x00" + b"\x00\x00\x00\x00" + checksum + b_seq_num
|
||||
|
||||
|
||||
def _mac_with_ess(flags: int, handle: RC4Handle, signing_key: bytes, seq_num: int, b_data: bytes) -> bytes:
|
||||
"""NTLM MAC with Extended Session Security
|
||||
|
||||
Generates the NTLM signature when Extended Session Security has been negotiated. The structure of the signature is
|
||||
documented at `NTLM signature with ESS`_.
|
||||
|
||||
The algorithm as documented by `MAC with ESS`_ is::
|
||||
|
||||
Define MAC(Handle, SigningKey, SeqNum, Message) as
|
||||
Set NTLMSSP_MESSAGE_SIGNATURE.Version to 0x00000001
|
||||
Set NTLMSSP_MESSAGE_SIGNATURE.Checksum to HMAC_MD5(SigningKey, ConcatenationOf(SeqNum, Message))[0..7]
|
||||
Set NTLMSSP_MESSAGE_SIGNATURE.SeqNum to SeqNum
|
||||
Set SeqNum to SeqNum + 1
|
||||
EndDefine
|
||||
|
||||
# When NegotiateFlags.key_exch
|
||||
|
||||
Define MAC(Handle, SigningKey, SeqNum, Message) as
|
||||
Set NTLMSSP_MESSAGE_SIGNATURE.Version to 0x00000001
|
||||
Set NTLMSSP_MESSAGE_SIGNATURE.Checksum to RC4(Handle,
|
||||
HMAC_MD5(SigningKey, ConcatenationOf(SeqNum, Message))[0..7])
|
||||
Set NTLMSSP_MESSAGE_SIGNATURE.SeqNum to SeqNum
|
||||
Set SeqNum to SeqNum + 1
|
||||
EndDefine
|
||||
|
||||
Args:
|
||||
flags: The negotiated flags between the initiator and acceptor.
|
||||
handle: The RC4 handle for the negotiated context.
|
||||
signing_key: The key used to sign the message.
|
||||
seq_num: The sequence number for the signature.
|
||||
b_data: The data/message bytes to sign.
|
||||
|
||||
Returns:
|
||||
bytes: The NTLM with ESS signature.
|
||||
|
||||
.. _NTLM signature with ESS:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/2c3b4689-d6f1-4dc6-85c9-0bf01ea34d9f
|
||||
|
||||
.. _MAC with ESS:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/a92716d5-d164-4960-9e15-300f4eef44a8
|
||||
"""
|
||||
b_seq_num = struct.pack("<I", seq_num)
|
||||
|
||||
checksum = hmac_md5(signing_key, b_seq_num + b_data)[:8]
|
||||
if flags & NegotiateFlags.key_exch:
|
||||
checksum = handle.update(checksum)
|
||||
|
||||
return b"\x01\x00\x00\x00" + checksum + b_seq_num
|
||||
498
env/lib/python3.12/site-packages/spnego/_spnego.py
vendored
Normal file
498
env/lib/python3.12/site-packages/spnego/_spnego.py
vendored
Normal file
@@ -0,0 +1,498 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import enum
|
||||
import struct
|
||||
import typing
|
||||
|
||||
from spnego._asn1 import (
|
||||
TagClass,
|
||||
TypeTagNumber,
|
||||
get_sequence_value,
|
||||
pack_asn1,
|
||||
pack_asn1_bit_string,
|
||||
pack_asn1_enumerated,
|
||||
pack_asn1_general_string,
|
||||
pack_asn1_object_identifier,
|
||||
pack_asn1_octet_string,
|
||||
pack_asn1_sequence,
|
||||
unpack_asn1,
|
||||
unpack_asn1_bit_string,
|
||||
unpack_asn1_enumerated,
|
||||
unpack_asn1_general_string,
|
||||
unpack_asn1_object_identifier,
|
||||
unpack_asn1_octet_string,
|
||||
unpack_asn1_sequence,
|
||||
unpack_asn1_tagged_sequence,
|
||||
)
|
||||
from spnego._context import GSSMech
|
||||
from spnego._kerberos import KerberosV5Msg
|
||||
from spnego._ntlm_raw.messages import NTLMMessage
|
||||
|
||||
|
||||
def pack_mech_type_list(
|
||||
mech_list: typing.Union[str, typing.List[str], typing.Tuple[str, ...], typing.Set[str]],
|
||||
) -> bytes:
|
||||
"""Packs a list of OIDs for the mechListMIC value.
|
||||
|
||||
Will pack a list of object identifiers to the raw byte string value for the mechListMIC.
|
||||
|
||||
Args:
|
||||
mech_list: The list of OIDs to back
|
||||
|
||||
Returns:
|
||||
bytes: The byte string of the packed ASN.1 MechTypeList SEQUENCE OF value.
|
||||
"""
|
||||
if not isinstance(mech_list, (list, tuple, set)):
|
||||
mech_list = [mech_list]
|
||||
|
||||
return pack_asn1_sequence([pack_asn1_object_identifier(oid) for oid in mech_list])
|
||||
|
||||
|
||||
def unpack_token(
|
||||
b_data: bytes,
|
||||
mech: typing.Optional[GSSMech] = None,
|
||||
unwrap: bool = False,
|
||||
encoding: typing.Optional[str] = None,
|
||||
) -> typing.Any:
|
||||
"""Unpacks a raw GSSAPI/SPNEGO token to a Python object.
|
||||
|
||||
Unpacks the byte string into a Python object that represents the token passed in. This can return many different
|
||||
token types such as:
|
||||
|
||||
* NTLM message(s)
|
||||
* SPNEGO/Negotiate init or response
|
||||
* Kerberos message(s)
|
||||
|
||||
Args:
|
||||
b_data: The raw byte string to unpack.
|
||||
mech: A hint as to what the byte string is for.
|
||||
unwrap: Whether to unwrap raw bytes to a structured message or return the raw tokens bytes.
|
||||
encoding: Optional encoding used when unwrapping NTLM messages.
|
||||
|
||||
Returns:
|
||||
any: The unpacked SPNEGO, Kerberos, or NTLM token.
|
||||
"""
|
||||
# First check if the message is an NTLM message.
|
||||
if b_data.startswith(b"NTLMSSP\x00"):
|
||||
if unwrap:
|
||||
return NTLMMessage.unpack(b_data, encoding=encoding)
|
||||
|
||||
else:
|
||||
return b_data
|
||||
|
||||
if mech and mech.is_kerberos_oid:
|
||||
# A Kerberos value inside an InitialContextToken contains 2 bytes which we ignore.
|
||||
raw_data = unpack_asn1(b_data[2:])[0]
|
||||
|
||||
else:
|
||||
raw_data = unpack_asn1(b_data)[0]
|
||||
|
||||
if raw_data.tag_class == TagClass.application and mech and mech.is_kerberos_oid:
|
||||
return KerberosV5Msg.unpack(unpack_asn1(raw_data.b_data)[0])
|
||||
|
||||
elif raw_data.tag_class == TagClass.application:
|
||||
# The first token is encapsulated in an InitialContextToken.
|
||||
if raw_data.tag_number != 0:
|
||||
raise ValueError("Expecting a tag number of 0 not %s for InitialContextToken" % raw_data.tag_number)
|
||||
|
||||
initial_context_token = InitialContextToken.unpack(raw_data.b_data)
|
||||
|
||||
# unwrap=True is called from python -m spnego and we don't want to loose any info in the output.
|
||||
if unwrap:
|
||||
return initial_context_token
|
||||
|
||||
this_mech: typing.Optional[GSSMech]
|
||||
try:
|
||||
this_mech = GSSMech.from_oid(initial_context_token.this_mech)
|
||||
except ValueError:
|
||||
this_mech = None
|
||||
|
||||
# We currently only support SPNEGO, or raw Kerberos here.
|
||||
if this_mech and (this_mech == GSSMech.spnego or (this_mech.is_kerberos_oid and unwrap)):
|
||||
return unpack_token(initial_context_token.inner_context_token, mech=this_mech)
|
||||
|
||||
return b_data
|
||||
|
||||
elif raw_data.tag_class == TagClass.context_specific:
|
||||
# This is a raw NegotiationToken that is wrapped in a CHOICE or 0 or 1.
|
||||
if raw_data.tag_number == 0:
|
||||
return NegTokenInit.unpack(raw_data.b_data)
|
||||
|
||||
elif raw_data.tag_number == 1:
|
||||
return NegTokenResp.unpack(raw_data.b_data)
|
||||
|
||||
else:
|
||||
raise ValueError("Unknown NegotiationToken CHOICE %d, only expecting 0 or 1" % raw_data.tag_number)
|
||||
|
||||
elif unwrap:
|
||||
# Could also be the ASN.1 Sequence of the Kerberos message.
|
||||
return KerberosV5Msg.unpack(raw_data)
|
||||
|
||||
else:
|
||||
return b_data
|
||||
|
||||
|
||||
# https://www.rfc-editor.org/rfc/rfc4178.html#section-4.2.1 - ContextFlags
|
||||
class ContextFlags(enum.IntFlag):
|
||||
deleg = 0
|
||||
mutual = 1
|
||||
replay = 2
|
||||
sequence = 3
|
||||
anon = 4
|
||||
conf = 5
|
||||
integ = 6
|
||||
|
||||
@classmethod
|
||||
def native_labels(cls) -> typing.Dict["ContextFlags", str]:
|
||||
return {
|
||||
ContextFlags.deleg: "delegFlag",
|
||||
ContextFlags.mutual: "mutualFlag",
|
||||
ContextFlags.replay: "replayFlag",
|
||||
ContextFlags.sequence: "sequenceFlag",
|
||||
ContextFlags.anon: "anonFlag",
|
||||
ContextFlags.conf: "confFlag",
|
||||
ContextFlags.integ: "integFlag",
|
||||
}
|
||||
|
||||
|
||||
# https://www.rfc-editor.org/rfc/rfc4178.html#section-4.2.2 - negState
|
||||
class NegState(enum.IntEnum):
|
||||
accept_complete = 0
|
||||
accept_incomplete = 1
|
||||
reject = 2
|
||||
request_mic = 3
|
||||
|
||||
@classmethod
|
||||
def native_labels(cls) -> typing.Dict["NegState", str]:
|
||||
return {
|
||||
NegState.accept_complete: "accept-complete",
|
||||
NegState.accept_incomplete: "accept-incomplete",
|
||||
NegState.reject: "reject",
|
||||
NegState.request_mic: "request-mic",
|
||||
}
|
||||
|
||||
|
||||
class InitialContextToken:
|
||||
"""GSSAPI InitialContextToken object.
|
||||
|
||||
The InitialContextToken is the ASN.1 structure that contains the first GSSAPI token that is sent across the wire.
|
||||
The ASN.1 definition for this structure is defined in `RFC 2743 3.1`_::
|
||||
|
||||
MechType ::= OBJECT IDENTIFIER
|
||||
-- data structure definitions
|
||||
-- callers must be able to distinguish among
|
||||
-- InitialContextToken, SubsequentContextToken,
|
||||
-- PerMsgToken, and SealedMessage data elements
|
||||
-- based on the usage in which they occur
|
||||
|
||||
InitialContextToken ::=
|
||||
-- option indication (delegation, etc.) indicated within
|
||||
-- mechanism-specific token
|
||||
[APPLICATION 0] IMPLICIT SEQUENCE {
|
||||
thisMech MechType,
|
||||
innerContextToken ANY DEFINED BY thisMech
|
||||
-- contents mechanism-specific
|
||||
-- ASN.1 structure not required
|
||||
}
|
||||
|
||||
Args:
|
||||
mech: The OID that defines the structure of the `token`.
|
||||
token: The token of the GSSAPI value.
|
||||
|
||||
Attributes:
|
||||
this_mech (str): The object identifier that identifies what the inner_context_token is for.
|
||||
inner_context_token (bytes): The token value as defined by `this_mech`.
|
||||
|
||||
.. _RFC 2743 3.1:
|
||||
https://www.rfc-editor.org/rfc/rfc2743#section-3.1.
|
||||
"""
|
||||
|
||||
def __init__(self, mech: typing.Union[GSSMech, str], token: bytes) -> None:
|
||||
if isinstance(mech, GSSMech):
|
||||
mech = mech.value
|
||||
|
||||
self.this_mech = mech
|
||||
self.inner_context_token = token
|
||||
|
||||
@property
|
||||
def token(self) -> typing.Any:
|
||||
mech: typing.Optional[GSSMech]
|
||||
try:
|
||||
mech = GSSMech.from_oid(self.this_mech)
|
||||
except ValueError:
|
||||
mech = None
|
||||
|
||||
return unpack_token(self.inner_context_token, mech=mech)
|
||||
|
||||
def pack(self) -> bytes:
|
||||
"""Packs the InitialContextToken as a byte string."""
|
||||
return pack_asn1(
|
||||
TagClass.application,
|
||||
True,
|
||||
0,
|
||||
pack_asn1_object_identifier(self.this_mech, tag=True) + self.inner_context_token,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def unpack(b_data: bytes) -> "InitialContextToken":
|
||||
"""Unpacks the InitialContextToken TLV value."""
|
||||
this_mech, inner_context_token = unpack_asn1(b_data)
|
||||
mech = unpack_asn1_object_identifier(this_mech)
|
||||
|
||||
return InitialContextToken(mech, inner_context_token)
|
||||
|
||||
|
||||
class NegTokenInit:
|
||||
"""The NegTokenInit GSSAPI value.
|
||||
|
||||
This is the initial negotiation message token in a GSSAPI exchange. Typically the `NegTokenInit` value is sent
|
||||
when sending the first authentication token. The `NegTokenInit2` token is an extension that adds the `negHints`
|
||||
field. Unfortunately as the tag number for the `mechListMIC` is the same for `negHints` unpacking the value
|
||||
requires some extra checks.
|
||||
|
||||
The ASN.1 definition for the NegTokenInit structure is defined in `RFC 4178 4.2.1`_::
|
||||
|
||||
NegTokenInit ::= SEQUENCE {
|
||||
mechTypes [0] MechTypeList,
|
||||
reqFlags [1] ContextFlags OPTIONAL,
|
||||
-- inherited from RFC 2478 for backward compatibility,
|
||||
-- RECOMMENDED to be left out
|
||||
mechToken [2] OCTET STRING OPTIONAL,
|
||||
mechListMIC [3] OCTET STRING OPTIONAL,
|
||||
...
|
||||
}
|
||||
ContextFlags ::= BIT STRING {
|
||||
delegFlag (0),
|
||||
mutualFlag (1),
|
||||
replayFlag (2),
|
||||
sequenceFlag (3),
|
||||
anonFlag (4),
|
||||
confFlag (5),
|
||||
integFlag (6)
|
||||
} (SIZE (32))
|
||||
|
||||
The ASN.1 definition for the `NegTokenInit2`_ structure is defined as::
|
||||
|
||||
NegHints ::= SEQUENCE {
|
||||
hintName[0] GeneralString OPTIONAL,
|
||||
hintAddress[1] OCTET STRING OPTIONAL
|
||||
}
|
||||
NegTokenInit2 ::= SEQUENCE {
|
||||
mechTypes[0] MechTypeList OPTIONAL,
|
||||
reqFlags [1] ContextFlags OPTIONAL,
|
||||
mechToken [2] OCTET STRING OPTIONAL,
|
||||
negHints [3] NegHints OPTIONAL,
|
||||
mechListMIC [4] OCTET STRING OPTIONAL,
|
||||
...
|
||||
}
|
||||
|
||||
Args:
|
||||
mech_types: One or more security mechanisms available for the initiator, in decreasing preference order.
|
||||
req_flags: Should be omitted, service options that are requested to establish the context.
|
||||
mech_token: Contains the optimistic mechanism token.
|
||||
hint_name: Used for the NegTokenInit2 structure only, should be omitted.
|
||||
hint_address: Used for the NegTokenINit2 structure only, should be omitted.
|
||||
mech_list_mic: The message integrity code (MIC) token.
|
||||
|
||||
Attributes:
|
||||
mech_types (List[str]): See args.
|
||||
req_flags (ContextFlags): See args.
|
||||
mech_token (bytes): See args.
|
||||
hint_name (bytes): See args.
|
||||
hint_address (bytes): See args.
|
||||
mech_list_mic (bytes): See args.
|
||||
|
||||
.. _RFC 4178 4.2.1:
|
||||
https://www.rfc-editor.org/rfc/rfc4178.html#section-4.2.1
|
||||
|
||||
.. _NegTokenInit2:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
mech_types: typing.Optional[typing.List[str]] = None,
|
||||
req_flags: typing.Optional[ContextFlags] = None,
|
||||
mech_token: typing.Optional[bytes] = None,
|
||||
hint_name: typing.Optional[bytes] = None,
|
||||
hint_address: typing.Optional[bytes] = None,
|
||||
mech_list_mic: typing.Optional[bytes] = None,
|
||||
) -> None:
|
||||
self.mech_types = mech_types or []
|
||||
self.req_flags = req_flags
|
||||
self.mech_token = mech_token
|
||||
self.hint_name = hint_name
|
||||
self.hint_address = hint_address
|
||||
self.mech_list_mic = mech_list_mic
|
||||
|
||||
def pack(self) -> bytes:
|
||||
"""Packs the NegTokenInit as a byte string."""
|
||||
|
||||
def pack_elements(
|
||||
value_map: typing.Iterable[typing.Tuple[int, typing.Any, typing.Callable]],
|
||||
) -> typing.List[bytes]:
|
||||
elements = []
|
||||
for tag, value, pack_func in value_map:
|
||||
if value is not None:
|
||||
elements.append(pack_asn1(TagClass.context_specific, True, tag, pack_func(value)))
|
||||
|
||||
return elements
|
||||
|
||||
req_flags = struct.pack("B", self.req_flags) if self.req_flags is not None else None
|
||||
base_map: typing.List[typing.Tuple[int, typing.Any, typing.Callable]] = [
|
||||
(0, self.mech_types, pack_mech_type_list),
|
||||
(1, req_flags, pack_asn1_bit_string),
|
||||
(2, self.mech_token, pack_asn1_octet_string),
|
||||
]
|
||||
|
||||
# The placement of the mechListMIC is dependent on whether we are packing a NegTokenInit with or without the
|
||||
# negHints field.
|
||||
neg_hints = pack_elements(
|
||||
[
|
||||
(0, self.hint_name, pack_asn1_general_string),
|
||||
(1, self.hint_address, pack_asn1_octet_string),
|
||||
]
|
||||
)
|
||||
|
||||
if neg_hints:
|
||||
base_map.append((3, neg_hints, pack_asn1_sequence))
|
||||
base_map.append((4, self.mech_list_mic, pack_asn1_octet_string))
|
||||
|
||||
else:
|
||||
base_map.append((3, self.mech_list_mic, pack_asn1_octet_string))
|
||||
|
||||
init_sequence = pack_elements(base_map)
|
||||
|
||||
# The NegTokenInit will always be wrapped in an InitialContextToken -> NegotiationToken - CHOICE 0.
|
||||
b_data = pack_asn1_sequence(init_sequence)
|
||||
return InitialContextToken(GSSMech.spnego.value, pack_asn1(TagClass.context_specific, True, 0, b_data)).pack()
|
||||
|
||||
@staticmethod
|
||||
def unpack(b_data: bytes) -> "NegTokenInit":
|
||||
"""Unpacks the NegTokenInit TLV value."""
|
||||
neg_seq = unpack_asn1_tagged_sequence(unpack_asn1(b_data)[0])
|
||||
|
||||
mech_types = [
|
||||
unpack_asn1_object_identifier(m)
|
||||
for m in get_sequence_value(neg_seq, 0, "NegTokenInit", "mechTypes", unpack_asn1_sequence) or []
|
||||
]
|
||||
|
||||
req_flags = get_sequence_value(neg_seq, 1, "NegTokenInit", "reqFlags", unpack_asn1_bit_string)
|
||||
if req_flags:
|
||||
# Can be up to 32 bits in length but RFC 4178 states "Implementations should not expect to receive exactly
|
||||
# 32 bits in an encoding of ContextFlags." The spec also documents req flags up to 6 so let's just get the
|
||||
# last byte. In reality we shouldn't ever receive this but it's left here for posterity.
|
||||
req_flags = ContextFlags(bytearray(req_flags)[-1])
|
||||
|
||||
mech_token = get_sequence_value(neg_seq, 2, "NegTokenInit", "mechToken", unpack_asn1_octet_string)
|
||||
|
||||
hint_name = hint_address = mech_list_mic = None
|
||||
if 3 in neg_seq:
|
||||
# Microsoft helpfully sends a NegTokenInit2 payload which sets 'negHints [3] NegHints OPTIONAL' and the
|
||||
# mechListMIC is actually at the 4th sequence entry. Because the NegTokenInit2 has the same choice in
|
||||
# NegotiationToken as NegTokenInit ([0]) we can only differentiate when unpacking based on the class/tags.
|
||||
tag_class = neg_seq[3].tag_class
|
||||
tag_number = neg_seq[3].tag_number
|
||||
|
||||
if tag_class == TagClass.universal and tag_number == TypeTagNumber.sequence:
|
||||
neg_hints = unpack_asn1_tagged_sequence(neg_seq[3].b_data)
|
||||
|
||||
# Windows 2000, 2003, and XP put the SPN encoded as the OEM code page, because there's no sane way
|
||||
# to decode this without prior knowledge a GeneralString stays a byte string in Python.
|
||||
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/211417c4-11ef-46c0-a8fb-f178a51c2088#Appendix_A_5
|
||||
hint_name = get_sequence_value(neg_hints, 0, "NegHints", "hintName", unpack_asn1_general_string)
|
||||
hint_address = get_sequence_value(neg_hints, 1, "NegHints", "hintAddress", unpack_asn1_octet_string)
|
||||
|
||||
else:
|
||||
# Wasn't a sequence, should be mechListMIC.
|
||||
mech_list_mic = get_sequence_value(neg_seq, 3, "NegTokenInit", "mechListMIC", unpack_asn1_octet_string)
|
||||
|
||||
if not mech_list_mic:
|
||||
mech_list_mic = get_sequence_value(neg_seq, 4, "NegTokenInit2", "mechListMIC", unpack_asn1_octet_string)
|
||||
|
||||
return NegTokenInit(mech_types, req_flags, mech_token, hint_name, hint_address, mech_list_mic)
|
||||
|
||||
|
||||
class NegTokenResp:
|
||||
"""The NegTokenResp GSSAPI value.
|
||||
|
||||
This is the message token in a GSSAPI exchange that is used for subsequent messages after the `NegTokenInit` has
|
||||
been exchanged.
|
||||
|
||||
The ASN.1 definition for the NegTokenResp structure is defined in `RFC 4178 4.2.2`_::
|
||||
|
||||
NegTokenResp ::= SEQUENCE {
|
||||
negState [0] ENUMERATED {
|
||||
accept-completed (0),
|
||||
accept-incomplete (1),
|
||||
reject (2),
|
||||
request-mic (3)
|
||||
} OPTIONAL,
|
||||
-- REQUIRED in the first reply from the target
|
||||
supportedMech [1] MechType OPTIONAL,
|
||||
-- present only in the first reply from the target
|
||||
responseToken [2] OCTET STRING OPTIONAL,
|
||||
mechListMIC [3] OCTET STRING OPTIONAL,
|
||||
...
|
||||
}
|
||||
|
||||
Args:
|
||||
neg_state: The state of the negotiation.
|
||||
supported_mech: Should only be present in the first reply, must be one of the mech(s) offered by the initiator.
|
||||
response_token: Contains the token specific to the mechanism selected.
|
||||
mech_list_mic: The message integrity code (MIC) token.
|
||||
|
||||
Attributes:
|
||||
neg_state (NegState): See args.
|
||||
supported_mech (str): See args.
|
||||
response_token (bytes): See args.
|
||||
mech_list_mic (bytes): See args.
|
||||
|
||||
.. _RFC 4178 4.2.2:
|
||||
https://www.rfc-editor.org/rfc/rfc4178.html#section-4.2.2
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
neg_state: typing.Optional[NegState] = None,
|
||||
supported_mech: typing.Optional[str] = None,
|
||||
response_token: typing.Optional[bytes] = None,
|
||||
mech_list_mic: typing.Optional[bytes] = None,
|
||||
) -> None:
|
||||
self.neg_state = neg_state
|
||||
self.supported_mech = supported_mech
|
||||
self.response_token = response_token
|
||||
self.mech_list_mic = mech_list_mic
|
||||
|
||||
def pack(self) -> bytes:
|
||||
"""Packs the NegTokenResp as a byte string."""
|
||||
value_map: typing.List[typing.Tuple[int, typing.Any, typing.Callable[[typing.Any], bytes]]] = [
|
||||
(0, self.neg_state, pack_asn1_enumerated),
|
||||
(1, self.supported_mech, pack_asn1_object_identifier),
|
||||
(2, self.response_token, pack_asn1_octet_string),
|
||||
(3, self.mech_list_mic, pack_asn1_octet_string),
|
||||
]
|
||||
elements = []
|
||||
for tag, value, pack_func in value_map:
|
||||
if value is not None:
|
||||
elements.append(pack_asn1(TagClass.context_specific, True, tag, pack_func(value)))
|
||||
|
||||
# The NegTokenResp will always be wrapped NegotiationToken - CHOICE 1.
|
||||
b_data = pack_asn1_sequence(elements)
|
||||
return pack_asn1(TagClass.context_specific, True, 1, b_data)
|
||||
|
||||
@staticmethod
|
||||
def unpack(b_data: bytes) -> "NegTokenResp":
|
||||
"""Unpacks the NegTokenResp TLV value."""
|
||||
neg_seq = unpack_asn1_tagged_sequence(unpack_asn1(b_data)[0])
|
||||
|
||||
neg_state = get_sequence_value(neg_seq, 0, "NegTokenResp", "negState", unpack_asn1_enumerated)
|
||||
if neg_state is not None:
|
||||
neg_state = NegState(neg_state)
|
||||
|
||||
supported_mech = get_sequence_value(neg_seq, 1, "NegTokenResp", "supportedMech", unpack_asn1_object_identifier)
|
||||
response_token = get_sequence_value(neg_seq, 2, "NegTokenResp", "responseToken", unpack_asn1_octet_string)
|
||||
mech_list_mic = get_sequence_value(neg_seq, 3, "NegTokenResp", "mechListMIC", unpack_asn1_octet_string)
|
||||
|
||||
return NegTokenResp(neg_state, supported_mech, response_token, mech_list_mic)
|
||||
533
env/lib/python3.12/site-packages/spnego/_sspi.py
vendored
Normal file
533
env/lib/python3.12/site-packages/spnego/_sspi.py
vendored
Normal file
@@ -0,0 +1,533 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import collections.abc
|
||||
import logging
|
||||
import os
|
||||
import typing as t
|
||||
|
||||
from spnego._context import (
|
||||
IOV,
|
||||
ContextProxy,
|
||||
ContextReq,
|
||||
IOVUnwrapResult,
|
||||
IOVWrapResult,
|
||||
SecPkgContextSizes,
|
||||
UnwrapResult,
|
||||
WinRMWrapResult,
|
||||
WrapResult,
|
||||
split_username,
|
||||
wrap_system_error,
|
||||
)
|
||||
from spnego._credential import (
|
||||
Credential,
|
||||
CredentialCache,
|
||||
KerberosKeytab,
|
||||
Password,
|
||||
unify_credentials,
|
||||
)
|
||||
from spnego.channel_bindings import GssChannelBindings
|
||||
from spnego.exceptions import (
|
||||
InvalidCredentialError,
|
||||
NegotiateOptions,
|
||||
NoContextError,
|
||||
SpnegoError,
|
||||
)
|
||||
from spnego.exceptions import WinError as NativeError
|
||||
from spnego.iov import BufferType, IOVBuffer, IOVResBuffer
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
if os.name == "nt":
|
||||
import sspilib
|
||||
|
||||
HAS_SSPI = True
|
||||
else:
|
||||
HAS_SSPI = False
|
||||
|
||||
|
||||
def _available_protocols() -> list[str]:
|
||||
"""Return a list of protocols that SSPIProxy can offer."""
|
||||
if HAS_SSPI:
|
||||
return ["kerberos", "negotiate", "ntlm"]
|
||||
else:
|
||||
return []
|
||||
|
||||
|
||||
def _create_iov_result(iov: sspilib.raw.SecBufferDesc) -> tuple[IOVResBuffer, ...]:
|
||||
"""Converts SSPI IOV buffer to generic IOVBuffer result."""
|
||||
buffers = []
|
||||
for i in iov:
|
||||
buffer_type = int(i.buffer_type)
|
||||
if i.buffer_flags & sspilib.raw.SecBufferFlags.SECBUFFER_READONLY_WITH_CHECKSUM:
|
||||
buffer_type = BufferType.sign_only
|
||||
elif i.buffer_flags & sspilib.raw.SecBufferFlags.SECBUFFER_READONLY:
|
||||
buffer_type = BufferType.data_readonly
|
||||
|
||||
buffer_entry = IOVResBuffer(type=BufferType(buffer_type), data=i.data)
|
||||
buffers.append(buffer_entry)
|
||||
|
||||
return tuple(buffers)
|
||||
|
||||
|
||||
def _get_sspi_credential(
|
||||
principal: str | None,
|
||||
protocol: str,
|
||||
usage: str,
|
||||
credentials: list[Credential],
|
||||
) -> sspilib.raw.CredHandle:
|
||||
"""Get the SSPI credential.
|
||||
|
||||
Will get an SSPI credential for the protocol specified. Currently only
|
||||
supports Password or CredentialCache credential types.
|
||||
|
||||
Args:
|
||||
principal: The principal to use for the AcquireCredentialsHandle call
|
||||
protocol: The protocol of the credential.
|
||||
usage: Either `initiate` for a client context or `accept` for a server
|
||||
context.
|
||||
credentials: List of credentials to retrieve from.
|
||||
|
||||
Returns:
|
||||
sspilib.raw.CredHandle: The handle to the SSPI credential to use.
|
||||
"""
|
||||
credential_kwargs: dict[str, t.Any] = {
|
||||
"package": protocol,
|
||||
"principal": principal,
|
||||
"credential_use": (
|
||||
sspilib.raw.CredentialUse.SECPKG_CRED_OUTBOUND
|
||||
if usage == "initiate"
|
||||
else sspilib.raw.CredentialUse.SECPKG_CRED_INBOUND
|
||||
),
|
||||
}
|
||||
|
||||
for cred in credentials:
|
||||
if isinstance(cred, Password):
|
||||
domain, username = split_username(cred.username)
|
||||
pass_data = sspilib.raw.WinNTAuthIdentity(
|
||||
username=username,
|
||||
domain=domain,
|
||||
password=cred.password,
|
||||
)
|
||||
|
||||
return sspilib.raw.acquire_credentials_handle(**credential_kwargs, auth_data=pass_data).credential
|
||||
|
||||
elif isinstance(cred, CredentialCache):
|
||||
return sspilib.raw.acquire_credentials_handle(**credential_kwargs).credential
|
||||
|
||||
elif isinstance(cred, KerberosKeytab):
|
||||
if not cred.principal:
|
||||
raise InvalidCredentialError(context_msg="KerberosKeytab for SSPI requires a principal to be set")
|
||||
|
||||
domain, username = split_username(cred.principal)
|
||||
with open(cred.keytab, mode="rb") as kt_file:
|
||||
keytab = kt_file.read()
|
||||
|
||||
kt_data = sspilib.raw.WinNTAuthIdentityPackedCredential(
|
||||
credential_type=sspilib.raw.WinNTAuthCredentialType.SEC_WINNT_AUTH_DATA_TYPE_KEYTAB,
|
||||
credential=keytab,
|
||||
username=username,
|
||||
domain=domain,
|
||||
)
|
||||
|
||||
return sspilib.raw.acquire_credentials_handle(**credential_kwargs, auth_data=kt_data).credential
|
||||
|
||||
raise InvalidCredentialError(context_msg="No applicable credentials available")
|
||||
|
||||
|
||||
class SSPIProxy(ContextProxy):
|
||||
"""SSPI proxy class for pure SSPI on Windows.
|
||||
|
||||
This proxy class for SSPI exposes this library into a common interface for SPNEGO authentication. This context
|
||||
uses compiled C code to interface directly into the SSPI functions on Windows to provide a native SPNEGO
|
||||
implementation.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
username: str | Credential | list[Credential] | None = None,
|
||||
password: str | None = None,
|
||||
hostname: str | None = None,
|
||||
service: str | None = None,
|
||||
channel_bindings: GssChannelBindings | None = None,
|
||||
context_req: ContextReq = ContextReq.default,
|
||||
usage: str = "initiate",
|
||||
protocol: str = "negotiate",
|
||||
options: NegotiateOptions = NegotiateOptions.none,
|
||||
**kwargs: t.Any,
|
||||
) -> None:
|
||||
|
||||
if not HAS_SSPI:
|
||||
raise ImportError("SSPIProxy requires the Windows only sspilib python package")
|
||||
|
||||
credentials = unify_credentials(username, password)
|
||||
super(SSPIProxy, self).__init__(
|
||||
credentials, hostname, service, channel_bindings, context_req, usage, protocol, options
|
||||
)
|
||||
|
||||
self._native_channel_bindings: sspilib.SecChannelBindings | None
|
||||
if channel_bindings:
|
||||
self._native_channel_bindings = self._get_native_bindings(channel_bindings)
|
||||
else:
|
||||
self._native_channel_bindings = None
|
||||
|
||||
self._block_size = 0
|
||||
self._max_signature = 0
|
||||
self._security_trailer = 0
|
||||
|
||||
self._complete = False
|
||||
self._context: sspilib.raw.CtxtHandle | None = None
|
||||
self.__seq_num = 0
|
||||
|
||||
sspi_credential = kwargs.get("_sspi_credential", None)
|
||||
if not sspi_credential:
|
||||
try:
|
||||
principal = self.spn if usage == "accept" else None
|
||||
sspi_credential = _get_sspi_credential(principal, protocol, usage, credentials)
|
||||
except NativeError as win_err:
|
||||
raise SpnegoError(base_error=win_err, context_msg="Getting SSPI credential") from win_err
|
||||
|
||||
self._credential = sspi_credential
|
||||
|
||||
@classmethod
|
||||
def available_protocols(
|
||||
cls,
|
||||
options: NegotiateOptions | None = None,
|
||||
) -> list[str]:
|
||||
return _available_protocols()
|
||||
|
||||
@property
|
||||
def client_principal(self) -> str | None:
|
||||
if self.usage == "accept":
|
||||
names = sspilib.raw.query_context_attributes(
|
||||
t.cast(sspilib.raw.CtxtHandle, self._context),
|
||||
sspilib.raw.SecPkgContextNames,
|
||||
)
|
||||
return names.username
|
||||
else:
|
||||
return None
|
||||
|
||||
@property
|
||||
def complete(self) -> bool:
|
||||
return self._complete
|
||||
|
||||
@property
|
||||
def negotiated_protocol(self) -> str | None:
|
||||
# FIXME: Try and replicate GSSAPI. Will return None for acceptor until the first token is returned. Negotiate
|
||||
# for both iniator and acceptor until the context is established.
|
||||
package_info = sspilib.raw.query_context_attributes(
|
||||
t.cast(sspilib.raw.CtxtHandle, self._context),
|
||||
sspilib.raw.SecPkgContextPackageInfo,
|
||||
)
|
||||
return package_info.name.lower()
|
||||
|
||||
@property
|
||||
@wrap_system_error(NativeError, "Retrieving session key")
|
||||
def session_key(self) -> bytes:
|
||||
session_key = sspilib.raw.query_context_attributes(
|
||||
t.cast(sspilib.raw.CtxtHandle, self._context),
|
||||
sspilib.raw.SecPkgContextSessionKey,
|
||||
)
|
||||
return session_key.session_key
|
||||
|
||||
def new_context(self) -> SSPIProxy:
|
||||
return SSPIProxy(
|
||||
hostname=self._hostname,
|
||||
service=self._service,
|
||||
channel_bindings=self.channel_bindings,
|
||||
context_req=self.context_req,
|
||||
usage=self.usage,
|
||||
protocol=self.protocol,
|
||||
options=self.options,
|
||||
_sspi_credential=self._credential,
|
||||
)
|
||||
|
||||
@wrap_system_error(NativeError, "Processing security token")
|
||||
def step(
|
||||
self,
|
||||
in_token: bytes | None = None,
|
||||
*,
|
||||
channel_bindings: GssChannelBindings | None = None,
|
||||
) -> bytes | None:
|
||||
if not self._is_wrapped:
|
||||
log.debug("SSPI step input: %s", base64.b64encode(in_token or b"").decode())
|
||||
|
||||
sec_tokens: list[sspilib.raw.SecBuffer] = []
|
||||
if in_token:
|
||||
in_token = bytearray(in_token)
|
||||
sec_tokens.append(sspilib.raw.SecBuffer(in_token, sspilib.raw.SecBufferType.SECBUFFER_TOKEN))
|
||||
|
||||
native_channel_bindings: sspilib.SecChannelBindings | None
|
||||
if channel_bindings:
|
||||
native_channel_bindings = self._get_native_bindings(channel_bindings)
|
||||
else:
|
||||
native_channel_bindings = self._native_channel_bindings
|
||||
|
||||
if native_channel_bindings:
|
||||
sec_tokens.append(native_channel_bindings.dangerous_get_sec_buffer())
|
||||
|
||||
in_buffer: sspilib.raw.SecBufferDesc | None = None
|
||||
if sec_tokens:
|
||||
in_buffer = sspilib.raw.SecBufferDesc(sec_tokens)
|
||||
|
||||
out_buffer = sspilib.raw.SecBufferDesc(
|
||||
[
|
||||
sspilib.raw.SecBuffer(None, sspilib.raw.SecBufferType.SECBUFFER_TOKEN),
|
||||
]
|
||||
)
|
||||
|
||||
context_req: int
|
||||
res: sspilib.raw.InitializeContextResult | sspilib.raw.AcceptContextResult
|
||||
if self.usage == "initiate":
|
||||
context_req = self._context_req | sspilib.IscReq.ISC_REQ_ALLOCATE_MEMORY
|
||||
res = sspilib.raw.initialize_security_context(
|
||||
credential=self._credential,
|
||||
context=self._context,
|
||||
target_name=self.spn or "",
|
||||
context_req=context_req,
|
||||
target_data_rep=sspilib.raw.TargetDataRep.SECURITY_NATIVE_DREP,
|
||||
input_buffers=in_buffer,
|
||||
output_buffers=out_buffer,
|
||||
)
|
||||
status = res.status
|
||||
self._context = res.context
|
||||
else:
|
||||
context_req = self._context_req | sspilib.AscReq.ASC_REQ_ALLOCATE_MEMORY
|
||||
res = sspilib.raw.accept_security_context(
|
||||
credential=self._credential,
|
||||
context=self._context,
|
||||
input_buffers=in_buffer,
|
||||
context_req=context_req,
|
||||
target_data_rep=sspilib.raw.TargetDataRep.SECURITY_NATIVE_DREP,
|
||||
output_buffers=out_buffer,
|
||||
)
|
||||
status = res.status
|
||||
self._context = res.context
|
||||
|
||||
out_token = out_buffer[0].data or None
|
||||
|
||||
self._context_attr = int(res.attributes)
|
||||
|
||||
if status == sspilib.raw.NtStatus.SEC_E_OK:
|
||||
self._complete = True
|
||||
|
||||
attr_sizes = sspilib.raw.query_context_attributes(self._context, sspilib.raw.SecPkgContextSizes)
|
||||
self._block_size = attr_sizes.block_size
|
||||
self._max_signature = attr_sizes.max_signature
|
||||
self._security_trailer = attr_sizes.security_trailer
|
||||
|
||||
if not self._is_wrapped:
|
||||
log.debug("SSPI step output: %s", base64.b64encode(out_token or b"").decode())
|
||||
|
||||
return out_token
|
||||
|
||||
def query_message_sizes(self) -> SecPkgContextSizes:
|
||||
if not self._security_trailer:
|
||||
raise NoContextError(context_msg="Cannot get message sizes until context has been established")
|
||||
|
||||
return SecPkgContextSizes(header=self._security_trailer)
|
||||
|
||||
def wrap(
|
||||
self,
|
||||
data: bytes,
|
||||
encrypt: bool = True,
|
||||
qop: int | None = None,
|
||||
) -> WrapResult:
|
||||
res = self.wrap_iov([BufferType.header, data, BufferType.padding], encrypt=encrypt, qop=qop)
|
||||
return WrapResult(data=b"".join([r.data for r in res.buffers if r.data]), encrypted=res.encrypted)
|
||||
|
||||
@wrap_system_error(NativeError, "Wrapping IOV buffer")
|
||||
def wrap_iov(
|
||||
self,
|
||||
iov: collections.abc.Iterable[IOV],
|
||||
encrypt: bool = True,
|
||||
qop: int | None = None,
|
||||
) -> IOVWrapResult:
|
||||
qop = qop or 0
|
||||
if encrypt and qop & sspilib.raw.QopFlags.SECQOP_WRAP_NO_ENCRYPT:
|
||||
raise ValueError("Cannot set qop with SECQOP_WRAP_NO_ENCRYPT and encrypt=True")
|
||||
elif not encrypt:
|
||||
qop |= sspilib.raw.QopFlags.SECQOP_WRAP_NO_ENCRYPT
|
||||
|
||||
buffers = self._build_iov_list(iov, self._convert_iov_buffer)
|
||||
iov_buffer = sspilib.raw.SecBufferDesc(buffers)
|
||||
|
||||
sspilib.raw.encrypt_message(
|
||||
t.cast(sspilib.raw.CtxtHandle, self._context),
|
||||
qop=qop,
|
||||
message=iov_buffer,
|
||||
seq_no=self._seq_num,
|
||||
)
|
||||
|
||||
return IOVWrapResult(buffers=_create_iov_result(iov_buffer), encrypted=encrypt)
|
||||
|
||||
def wrap_winrm(self, data: bytes) -> WinRMWrapResult:
|
||||
iov = self.wrap_iov([BufferType.header, data]).buffers
|
||||
header = iov[0].data or b""
|
||||
enc_data = iov[1].data or b""
|
||||
|
||||
return WinRMWrapResult(header=header, data=enc_data, padding_length=0)
|
||||
|
||||
def unwrap(self, data: bytes) -> UnwrapResult:
|
||||
res = self.unwrap_iov([(BufferType.stream, data), BufferType.data])
|
||||
|
||||
dec_data = res.buffers[1].data or b""
|
||||
return UnwrapResult(data=dec_data, encrypted=res.encrypted, qop=res.qop)
|
||||
|
||||
@wrap_system_error(NativeError, "Unwrapping IOV buffer")
|
||||
def unwrap_iov(
|
||||
self,
|
||||
iov: collections.abc.Iterable[IOV],
|
||||
) -> IOVUnwrapResult:
|
||||
buffers = self._build_iov_list(iov, self._convert_iov_buffer)
|
||||
iov_buffer = sspilib.raw.SecBufferDesc(buffers)
|
||||
|
||||
qop = sspilib.raw.decrypt_message(
|
||||
t.cast(sspilib.raw.CtxtHandle, self._context),
|
||||
iov_buffer,
|
||||
seq_no=self._seq_num,
|
||||
)
|
||||
encrypted = qop & sspilib.raw.QopFlags.SECQOP_WRAP_NO_ENCRYPT == 0
|
||||
|
||||
return IOVUnwrapResult(buffers=_create_iov_result(iov_buffer), encrypted=encrypted, qop=qop)
|
||||
|
||||
def unwrap_winrm(self, header: bytes, data: bytes) -> bytes:
|
||||
iov = self.unwrap_iov([(BufferType.header, header), data]).buffers
|
||||
return iov[1].data or b""
|
||||
|
||||
@wrap_system_error(NativeError, "Signing message")
|
||||
def sign(
|
||||
self,
|
||||
data: bytes,
|
||||
qop: int | None = None,
|
||||
) -> bytes:
|
||||
data = bytearray(data)
|
||||
signature = bytearray(self._max_signature)
|
||||
iov = sspilib.raw.SecBufferDesc(
|
||||
[
|
||||
sspilib.raw.SecBuffer(data, sspilib.raw.SecBufferType.SECBUFFER_DATA),
|
||||
sspilib.raw.SecBuffer(signature, sspilib.raw.SecBufferType.SECBUFFER_TOKEN),
|
||||
]
|
||||
)
|
||||
sspilib.raw.make_signature(
|
||||
t.cast(sspilib.raw.CtxtHandle, self._context),
|
||||
qop or 0,
|
||||
iov,
|
||||
self._seq_num,
|
||||
)
|
||||
|
||||
return iov[1].data
|
||||
|
||||
@wrap_system_error(NativeError, "Verifying message")
|
||||
def verify(self, data: bytes, mic: bytes) -> int:
|
||||
data = bytearray(data)
|
||||
mic = bytearray(mic)
|
||||
iov = sspilib.raw.SecBufferDesc(
|
||||
[
|
||||
sspilib.raw.SecBuffer(data, sspilib.raw.SecBufferType.SECBUFFER_DATA),
|
||||
sspilib.raw.SecBuffer(mic, sspilib.raw.SecBufferType.SECBUFFER_TOKEN),
|
||||
]
|
||||
)
|
||||
|
||||
return sspilib.raw.verify_signature(
|
||||
t.cast(sspilib.raw.CtxtHandle, self._context),
|
||||
iov,
|
||||
self._seq_num,
|
||||
)
|
||||
|
||||
@property
|
||||
def _context_attr_map(self) -> list[tuple[ContextReq, int]]:
|
||||
# The flags values slightly differ for a initiate and accept context.
|
||||
attr_map = []
|
||||
|
||||
sspi_req: type[int] | None
|
||||
if self.usage == "initiate":
|
||||
attr_map.append((ContextReq.no_integrity, "REQ_NO_INTEGRITY"))
|
||||
sspi_req = sspilib.IscReq
|
||||
sspi_prefix = "ISC"
|
||||
else:
|
||||
sspi_req = sspilib.AscReq
|
||||
sspi_prefix = "ASC"
|
||||
|
||||
attr_map.extend(
|
||||
[
|
||||
# SSPI does not differ between delegate and delegate_policy, it always respects delegate_policy.
|
||||
(ContextReq.delegate, "REQ_DELEGATE"),
|
||||
(ContextReq.delegate_policy, "REQ_DELEGATE"),
|
||||
(ContextReq.mutual_auth, "REQ_MUTUAL_AUTH"),
|
||||
(ContextReq.replay_detect, "REQ_REPLAY_DETECT"),
|
||||
(ContextReq.sequence_detect, "REQ_SEQUENCE_DETECT"),
|
||||
(ContextReq.confidentiality, "REQ_CONFIDENTIALITY"),
|
||||
(ContextReq.integrity, "REQ_INTEGRITY"),
|
||||
(ContextReq.dce_style, "REQ_USE_DCE_STYLE"),
|
||||
(ContextReq.identify, "REQ_IDENTIFY"),
|
||||
]
|
||||
)
|
||||
|
||||
attrs = []
|
||||
for spnego_flag, gssapi_name in attr_map:
|
||||
attrs.append((spnego_flag, getattr(sspi_req, f"{sspi_prefix}_{gssapi_name}")))
|
||||
|
||||
return attrs
|
||||
|
||||
@property
|
||||
def _seq_num(self) -> int:
|
||||
num = self.__seq_num
|
||||
self.__seq_num += 1
|
||||
return num
|
||||
|
||||
def _convert_iov_buffer(self, buffer: IOVBuffer) -> sspilib.raw.SecBuffer:
|
||||
data = bytearray()
|
||||
|
||||
if isinstance(buffer.data, bytes):
|
||||
data = bytearray(buffer.data)
|
||||
elif isinstance(buffer.data, int) and not isinstance(buffer.data, bool):
|
||||
data = bytearray(buffer.data)
|
||||
else:
|
||||
auto_alloc_size = {
|
||||
BufferType.header: self._security_trailer,
|
||||
BufferType.padding: self._block_size,
|
||||
BufferType.trailer: self._security_trailer,
|
||||
}
|
||||
|
||||
# If alloc wasn't explicitly set, only alloc if the type is a specific auto alloc type.
|
||||
alloc = buffer.data
|
||||
if alloc is None:
|
||||
alloc = buffer.type in auto_alloc_size
|
||||
|
||||
if alloc:
|
||||
if buffer.type not in auto_alloc_size:
|
||||
raise ValueError(
|
||||
"Cannot auto allocate buffer of type %s.%s" % (type(buffer.type).__name__, buffer.type.name)
|
||||
)
|
||||
|
||||
data = bytearray(auto_alloc_size[buffer.type])
|
||||
|
||||
# This buffer types need manual mapping from the generic value to the
|
||||
# one understood by sspilib.
|
||||
buffer_type = int(buffer.type)
|
||||
buffer_flags = 0
|
||||
if buffer_type == BufferType.sign_only:
|
||||
buffer_type = sspilib.raw.SecBufferType.SECBUFFER_DATA
|
||||
buffer_flags = sspilib.raw.SecBufferFlags.SECBUFFER_READONLY_WITH_CHECKSUM
|
||||
elif buffer_type == BufferType.data_readonly:
|
||||
buffer_type = sspilib.raw.SecBufferType.SECBUFFER_DATA
|
||||
buffer_flags = sspilib.raw.SecBufferFlags.SECBUFFER_READONLY
|
||||
|
||||
return sspilib.raw.SecBuffer(data, buffer_type, buffer_flags)
|
||||
|
||||
def _get_native_bindings(
|
||||
self,
|
||||
channel_bindings: GssChannelBindings,
|
||||
) -> sspilib.SecChannelBindings:
|
||||
"""Gets the raw byte value of the SEC_CHANNEL_BINDINGS structure."""
|
||||
return sspilib.SecChannelBindings(
|
||||
initiator_addr_type=int(channel_bindings.initiator_addrtype),
|
||||
initiator_addr=channel_bindings.initiator_address,
|
||||
acceptor_addr_type=int(channel_bindings.acceptor_addrtype),
|
||||
acceptor_addr=channel_bindings.acceptor_address,
|
||||
application_data=channel_bindings.application_data,
|
||||
)
|
||||
68
env/lib/python3.12/site-packages/spnego/_text.py
vendored
Normal file
68
env/lib/python3.12/site-packages/spnego/_text.py
vendored
Normal file
@@ -0,0 +1,68 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import typing
|
||||
|
||||
|
||||
def _obj_str(
|
||||
obj: typing.Any,
|
||||
default: str,
|
||||
) -> str:
|
||||
# First try to get the str() then repr() before falling back to the default value.
|
||||
to_str_funcs: typing.List[typing.Callable] = [str, repr]
|
||||
for func in to_str_funcs:
|
||||
try:
|
||||
obj = func(obj)
|
||||
except (UnicodeError, TypeError):
|
||||
continue
|
||||
else:
|
||||
return obj
|
||||
else:
|
||||
return default
|
||||
|
||||
|
||||
def to_bytes(
|
||||
obj: typing.Any,
|
||||
encoding: str = "utf-8",
|
||||
errors: str = "strict",
|
||||
nonstring: str = "str",
|
||||
) -> typing.Any:
|
||||
if isinstance(obj, bytes):
|
||||
return obj
|
||||
elif isinstance(obj, str):
|
||||
return obj.encode(encoding, errors)
|
||||
|
||||
if nonstring == "str":
|
||||
return to_bytes(_obj_str(obj, ""), encoding=encoding, errors=errors)
|
||||
elif nonstring == "passthru":
|
||||
return obj
|
||||
elif nonstring == "empty":
|
||||
return b""
|
||||
else:
|
||||
raise ValueError("Invalid nonstring value '%s', expecting str, passthru, or empty" % nonstring)
|
||||
|
||||
|
||||
def to_text(
|
||||
obj: typing.Any,
|
||||
encoding: str = "utf-8",
|
||||
errors: str = "strict",
|
||||
nonstring: str = "str",
|
||||
) -> typing.Any:
|
||||
if isinstance(obj, str):
|
||||
return obj
|
||||
elif isinstance(obj, bytes):
|
||||
return obj.decode(encoding, errors)
|
||||
|
||||
if nonstring == "str":
|
||||
try:
|
||||
obj = obj.__unicode__()
|
||||
except (AttributeError, UnicodeError):
|
||||
obj = _obj_str(obj, "")
|
||||
|
||||
return to_text(obj, errors=errors, encoding=encoding)
|
||||
elif nonstring == "passthru":
|
||||
return obj
|
||||
elif nonstring == "empty":
|
||||
return ""
|
||||
else:
|
||||
raise ValueError("Invalid nonstring value '%s', expecting repr, passthru, or empty" % nonstring)
|
||||
804
env/lib/python3.12/site-packages/spnego/_tls_struct.py
vendored
Normal file
804
env/lib/python3.12/site-packages/spnego/_tls_struct.py
vendored
Normal file
@@ -0,0 +1,804 @@
|
||||
# Copyright: (c) 2022, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import enum
|
||||
import typing
|
||||
|
||||
|
||||
def _add_missing_enum_member(
|
||||
cls: typing.Type[enum.IntEnum],
|
||||
value: object,
|
||||
label: str,
|
||||
) -> typing.Optional[enum.Enum]:
|
||||
if not isinstance(value, int):
|
||||
return None
|
||||
|
||||
new_member = int.__new__(cls)
|
||||
new_member._name_ = label.format(value)
|
||||
new_member._value_ = value
|
||||
return cls._value2member_map_.setdefault(value, new_member)
|
||||
|
||||
|
||||
class TlsProtocolVersion(enum.IntEnum):
|
||||
tls1_0 = 0x0301
|
||||
tls1_1 = 0x0302
|
||||
tls1_2 = 0x0303
|
||||
tls1_3 = 0x0304
|
||||
|
||||
@classmethod
|
||||
def native_labels(cls) -> typing.Dict["TlsProtocolVersion", str]:
|
||||
return {
|
||||
TlsProtocolVersion.tls1_0: "TLS 1.0 (0x0301)",
|
||||
TlsProtocolVersion.tls1_1: "TLS 1.1 (0x0302)",
|
||||
TlsProtocolVersion.tls1_2: "TLS 1.2 (0x0303)",
|
||||
TlsProtocolVersion.tls1_3: "TLS 1.3 (0x0304)",
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> typing.Optional[enum.Enum]:
|
||||
return _add_missing_enum_member(cls, value, "Unknown TLS Protocol Version 0x{0:04X}")
|
||||
|
||||
|
||||
class TlsContentType(enum.IntEnum):
|
||||
invalid = 0
|
||||
change_cipher_spec = 20
|
||||
alert = 21
|
||||
handshake = 22
|
||||
application_data = 23
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> typing.Optional[enum.Enum]:
|
||||
return _add_missing_enum_member(cls, value, "Unknown TLS Content Type 0x{0:02X}")
|
||||
|
||||
|
||||
class TlsHandshakeMessageType(enum.IntEnum):
|
||||
hello_request = 0
|
||||
client_hello = 1
|
||||
server_hello = 2
|
||||
hello_verify_request = 3
|
||||
new_session_ticket = 4
|
||||
end_of_early_data = 5
|
||||
hello_retry_request = 6
|
||||
encrypted_extensions = 8
|
||||
request_connection_id = 9
|
||||
new_connection_id = 10
|
||||
certificate = 11
|
||||
server_key_exchange = 12
|
||||
certificate_request = 13
|
||||
server_hello_done = 14
|
||||
certificate_verify = 15
|
||||
client_key_exchange = 16
|
||||
client_certificate_request = 17
|
||||
finished = 20
|
||||
certificate_url = 21
|
||||
certificate_status = 22
|
||||
supplemental_data = 23
|
||||
key_update = 24
|
||||
compressed_certificate = 25
|
||||
ekt_key = 26
|
||||
message_hash = 254
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> typing.Optional[enum.Enum]:
|
||||
return _add_missing_enum_member(cls, value, "Unknown Handshake Message Type 0x{0:02X}")
|
||||
|
||||
|
||||
class TlsCipherSuite(enum.IntEnum):
|
||||
TLS_NULL_WITH_NULL_NULL = 0x0000
|
||||
TLS_RSA_WITH_NULL_MD5 = 0x0001
|
||||
TLS_RSA_WITH_NULL_SHA = 0x0002
|
||||
TLS_RSA_EXPORT_WITH_RC4_40_MD5 = 0x0003
|
||||
TLS_RSA_WITH_RC4_128_MD5 = 0x0004
|
||||
TLS_RSA_WITH_RC4_128_SHA = 0x0005
|
||||
TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = 0x0006
|
||||
TLS_RSA_WITH_IDEA_CBC_SHA = 0x0007
|
||||
TLS_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x0008
|
||||
TLS_RSA_WITH_DES_CBC_SHA = 0x0009
|
||||
TLS_RSA_WITH_3DES_EDE_CBC_SHA = 0x000A
|
||||
TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA = 0x000B
|
||||
TLS_DH_DSS_WITH_DES_CBC_SHA = 0x000C
|
||||
TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA = 0x000D
|
||||
TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x000E
|
||||
TLS_DH_RSA_WITH_DES_CBC_SHA = 0x000F
|
||||
TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA = 0x0010
|
||||
TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA = 0x0011
|
||||
TLS_DHE_DSS_WITH_DES_CBC_SHA = 0x0012
|
||||
TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = 0x0013
|
||||
TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x0014
|
||||
TLS_DHE_RSA_WITH_DES_CBC_SHA = 0x0015
|
||||
TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x0016
|
||||
TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 = 0x0017
|
||||
TLS_DH_anon_WITH_RC4_128_MD5 = 0x0018
|
||||
TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA = 0x0019
|
||||
TLS_DH_anon_WITH_DES_CBC_SHA = 0x001A
|
||||
TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = 0x001B
|
||||
TLS_KRB5_WITH_DES_CBC_SHA = 0x001E
|
||||
TLS_KRB5_WITH_3DES_EDE_CBC_SHA = 0x001F
|
||||
TLS_KRB5_WITH_RC4_128_SHA = 0x0020
|
||||
TLS_KRB5_WITH_IDEA_CBC_SHA = 0x0021
|
||||
TLS_KRB5_WITH_DES_CBC_MD5 = 0x0022
|
||||
TLS_KRB5_WITH_3DES_EDE_CBC_MD5 = 0x0023
|
||||
TLS_KRB5_WITH_RC4_128_MD5 = 0x0024
|
||||
TLS_KRB5_WITH_IDEA_CBC_MD5 = 0x0025
|
||||
TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA = 0x0026
|
||||
TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA = 0x0027
|
||||
TLS_KRB5_EXPORT_WITH_RC4_40_SHA = 0x0028
|
||||
TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 = 0x0029
|
||||
TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5 = 0x002A
|
||||
TLS_KRB5_EXPORT_WITH_RC4_40_MD5 = 0x002B
|
||||
TLS_PSK_WITH_NULL_SHA = 0x002C
|
||||
TLS_DHE_PSK_WITH_NULL_SHA = 0x002D
|
||||
TLS_RSA_PSK_WITH_NULL_SHA = 0x002E
|
||||
TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F
|
||||
TLS_DH_DSS_WITH_AES_128_CBC_SHA = 0x0030
|
||||
TLS_DH_RSA_WITH_AES_128_CBC_SHA = 0x0031
|
||||
TLS_DHE_DSS_WITH_AES_128_CBC_SHA = 0x0032
|
||||
TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033
|
||||
TLS_DH_anon_WITH_AES_128_CBC_SHA = 0x0034
|
||||
TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035
|
||||
TLS_DH_DSS_WITH_AES_256_CBC_SHA = 0x0036
|
||||
TLS_DH_RSA_WITH_AES_256_CBC_SHA = 0x0037
|
||||
TLS_DHE_DSS_WITH_AES_256_CBC_SHA = 0x0038
|
||||
TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039
|
||||
TLS_DH_anon_WITH_AES_256_CBC_SHA = 0x003A
|
||||
TLS_RSA_WITH_NULL_SHA256 = 0x003B
|
||||
TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C
|
||||
TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D
|
||||
TLS_DH_DSS_WITH_AES_128_CBC_SHA256 = 0x003E
|
||||
TLS_DH_RSA_WITH_AES_128_CBC_SHA256 = 0x003F
|
||||
TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 = 0x0040
|
||||
TLS_RSA_WITH_CAMELLIA_128_CBC_SHA = 0x0041
|
||||
TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA = 0x0042
|
||||
TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA = 0x0043
|
||||
TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA = 0x0044
|
||||
TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA = 0x0045
|
||||
TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA = 0x0046
|
||||
TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067
|
||||
TLS_DH_DSS_WITH_AES_256_CBC_SHA256 = 0x0068
|
||||
TLS_DH_RSA_WITH_AES_256_CBC_SHA256 = 0x0069
|
||||
TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 = 0x006A
|
||||
TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B
|
||||
TLS_DH_anon_WITH_AES_128_CBC_SHA256 = 0x006C
|
||||
TLS_DH_anon_WITH_AES_256_CBC_SHA256 = 0x006D
|
||||
TLS_RSA_WITH_CAMELLIA_256_CBC_SHA = 0x0084
|
||||
TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA = 0x0085
|
||||
TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA = 0x0086
|
||||
TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA = 0x0087
|
||||
TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA = 0x0088
|
||||
TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA = 0x0089
|
||||
TLS_PSK_WITH_RC4_128_SHA = 0x008A
|
||||
TLS_PSK_WITH_3DES_EDE_CBC_SHA = 0x008B
|
||||
TLS_PSK_WITH_AES_128_CBC_SHA = 0x008C
|
||||
TLS_PSK_WITH_AES_256_CBC_SHA = 0x008D
|
||||
TLS_DHE_PSK_WITH_RC4_128_SHA = 0x008E
|
||||
TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA = 0x008F
|
||||
TLS_DHE_PSK_WITH_AES_128_CBC_SHA = 0x0090
|
||||
TLS_DHE_PSK_WITH_AES_256_CBC_SHA = 0x0091
|
||||
TLS_RSA_PSK_WITH_RC4_128_SHA = 0x0092
|
||||
TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA = 0x0093
|
||||
TLS_RSA_PSK_WITH_AES_128_CBC_SHA = 0x0094
|
||||
TLS_RSA_PSK_WITH_AES_256_CBC_SHA = 0x0095
|
||||
TLS_RSA_WITH_SEED_CBC_SHA = 0x0096
|
||||
TLS_DH_DSS_WITH_SEED_CBC_SHA = 0x0097
|
||||
TLS_DH_RSA_WITH_SEED_CBC_SHA = 0x0098
|
||||
TLS_DHE_DSS_WITH_SEED_CBC_SHA = 0x0099
|
||||
TLS_DHE_RSA_WITH_SEED_CBC_SHA = 0x009A
|
||||
TLS_DH_anon_WITH_SEED_CBC_SHA = 0x009B
|
||||
TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C
|
||||
TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D
|
||||
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E
|
||||
TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F
|
||||
TLS_DH_RSA_WITH_AES_128_GCM_SHA256 = 0x00A0
|
||||
TLS_DH_RSA_WITH_AES_256_GCM_SHA384 = 0x00A1
|
||||
TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 = 0x00A2
|
||||
TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 = 0x00A3
|
||||
TLS_DH_DSS_WITH_AES_128_GCM_SHA256 = 0x00A4
|
||||
TLS_DH_DSS_WITH_AES_256_GCM_SHA384 = 0x00A5
|
||||
TLS_DH_anon_WITH_AES_128_GCM_SHA256 = 0x00A6
|
||||
TLS_DH_anon_WITH_AES_256_GCM_SHA384 = 0x00A7
|
||||
TLS_PSK_WITH_AES_128_GCM_SHA256 = 0x00A8
|
||||
TLS_PSK_WITH_AES_256_GCM_SHA384 = 0x00A9
|
||||
TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 = 0x00AA
|
||||
TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 = 0x00AB
|
||||
TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 = 0x00AC
|
||||
TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 = 0x00AD
|
||||
TLS_PSK_WITH_AES_128_CBC_SHA256 = 0x00AE
|
||||
TLS_PSK_WITH_AES_256_CBC_SHA384 = 0x00AF
|
||||
TLS_PSK_WITH_NULL_SHA256 = 0x00B0
|
||||
TLS_PSK_WITH_NULL_SHA384 = 0x00B1
|
||||
TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 = 0x00B2
|
||||
TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 = 0x00B3
|
||||
TLS_DHE_PSK_WITH_NULL_SHA256 = 0x00B4
|
||||
TLS_DHE_PSK_WITH_NULL_SHA384 = 0x00B5
|
||||
TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 = 0x00B6
|
||||
TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 = 0x00B7
|
||||
TLS_RSA_PSK_WITH_NULL_SHA256 = 0x00B8
|
||||
TLS_RSA_PSK_WITH_NULL_SHA384 = 0x00B9
|
||||
TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 = 0x00BA
|
||||
TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 = 0x00BB
|
||||
TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 = 0x00BC
|
||||
TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 = 0x00BD
|
||||
TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 = 0x00BE
|
||||
TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256 = 0x00BF
|
||||
TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 = 0x00C0
|
||||
TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 = 0x00C1
|
||||
TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 = 0x00C2
|
||||
TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 = 0x00C3
|
||||
TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 = 0x00C4
|
||||
TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256 = 0x00C5
|
||||
TLS_SM4_GCM_SM3 = 0x00C6
|
||||
TLS_SM4_CCM_SM3 = 0x00C7
|
||||
TLS_EMPTY_RENEGOTIATION_INFO_SCSV = 0x00FF
|
||||
TLS_AES_128_GCM_SHA256 = 0x1301
|
||||
TLS_AES_256_GCM_SHA384 = 0x1302
|
||||
TLS_CHACHA20_POLY1305_SHA256 = 0x1303
|
||||
TLS_AES_128_CCM_SHA256 = 0x1304
|
||||
TLS_AES_128_CCM_8_SHA256 = 0x1305
|
||||
TLS_FALLBACK_SCSV = 0x5600
|
||||
TLS_ECDH_ECDSA_WITH_NULL_SHA = 0xC001
|
||||
TLS_ECDH_ECDSA_WITH_RC4_128_SHA = 0xC002
|
||||
TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = 0xC003
|
||||
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA = 0xC004
|
||||
TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA = 0xC005
|
||||
TLS_ECDHE_ECDSA_WITH_NULL_SHA = 0xC006
|
||||
TLS_ECDHE_ECDSA_WITH_RC4_128_SHA = 0xC007
|
||||
TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = 0xC008
|
||||
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009
|
||||
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A
|
||||
TLS_ECDH_RSA_WITH_NULL_SHA = 0xC00B
|
||||
TLS_ECDH_RSA_WITH_RC4_128_SHA = 0xC00C
|
||||
TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA = 0xC00D
|
||||
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA = 0xC00E
|
||||
TLS_ECDH_RSA_WITH_AES_256_CBC_SHA = 0xC00F
|
||||
TLS_ECDHE_RSA_WITH_NULL_SHA = 0xC010
|
||||
TLS_ECDHE_RSA_WITH_RC4_128_SHA = 0xC011
|
||||
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA = 0xC012
|
||||
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013
|
||||
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014
|
||||
TLS_ECDH_anon_WITH_NULL_SHA = 0xC015
|
||||
TLS_ECDH_anon_WITH_RC4_128_SHA = 0xC016
|
||||
TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA = 0xC017
|
||||
TLS_ECDH_anon_WITH_AES_128_CBC_SHA = 0xC018
|
||||
TLS_ECDH_anon_WITH_AES_256_CBC_SHA = 0xC019
|
||||
TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA = 0xC01A
|
||||
TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA = 0xC01B
|
||||
TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA = 0xC01C
|
||||
TLS_SRP_SHA_WITH_AES_128_CBC_SHA = 0xC01D
|
||||
TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA = 0xC01E
|
||||
TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA = 0xC01F
|
||||
TLS_SRP_SHA_WITH_AES_256_CBC_SHA = 0xC020
|
||||
TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA = 0xC021
|
||||
TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA = 0xC022
|
||||
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023
|
||||
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024
|
||||
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC025
|
||||
TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC026
|
||||
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027
|
||||
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028
|
||||
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 = 0xC029
|
||||
TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 = 0xC02A
|
||||
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B
|
||||
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C
|
||||
TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02D
|
||||
TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02E
|
||||
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F
|
||||
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030
|
||||
TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 = 0xC031
|
||||
TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 = 0xC032
|
||||
TLS_ECDHE_PSK_WITH_RC4_128_SHA = 0xC033
|
||||
TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA = 0xC034
|
||||
TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA = 0xC035
|
||||
TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA = 0xC036
|
||||
TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 = 0xC037
|
||||
TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 = 0xC038
|
||||
TLS_ECDHE_PSK_WITH_NULL_SHA = 0xC039
|
||||
TLS_ECDHE_PSK_WITH_NULL_SHA256 = 0xC03A
|
||||
TLS_ECDHE_PSK_WITH_NULL_SHA384 = 0xC03B
|
||||
TLS_RSA_WITH_ARIA_128_CBC_SHA256 = 0xC03C
|
||||
TLS_RSA_WITH_ARIA_256_CBC_SHA384 = 0xC03D
|
||||
TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256 = 0xC03E
|
||||
TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384 = 0xC03F
|
||||
TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256 = 0xC040
|
||||
TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384 = 0xC041
|
||||
TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256 = 0xC042
|
||||
TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384 = 0xC043
|
||||
TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 = 0xC044
|
||||
TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 = 0xC045
|
||||
TLS_DH_anon_WITH_ARIA_128_CBC_SHA256 = 0xC046
|
||||
TLS_DH_anon_WITH_ARIA_256_CBC_SHA384 = 0xC047
|
||||
TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 = 0xC048
|
||||
TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 = 0xC049
|
||||
TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 = 0xC04A
|
||||
TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 = 0xC04B
|
||||
TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 = 0xC04C
|
||||
TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 = 0xC04D
|
||||
TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 = 0xC04E
|
||||
TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 = 0xC04F
|
||||
TLS_RSA_WITH_ARIA_128_GCM_SHA256 = 0xC050
|
||||
TLS_RSA_WITH_ARIA_256_GCM_SHA384 = 0xC051
|
||||
TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 = 0xC052
|
||||
TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 = 0xC053
|
||||
TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256 = 0xC054
|
||||
TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384 = 0xC055
|
||||
TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256 = 0xC056
|
||||
TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384 = 0xC057
|
||||
TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256 = 0xC058
|
||||
TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384 = 0xC059
|
||||
TLS_DH_anon_WITH_ARIA_128_GCM_SHA256 = 0xC05A
|
||||
TLS_DH_anon_WITH_ARIA_256_GCM_SHA384 = 0xC05B
|
||||
TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 = 0xC05C
|
||||
TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 = 0xC05D
|
||||
TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 = 0xC05E
|
||||
TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 = 0xC05F
|
||||
TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 = 0xC060
|
||||
TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 = 0xC061
|
||||
TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 = 0xC062
|
||||
TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 = 0xC063
|
||||
TLS_PSK_WITH_ARIA_128_CBC_SHA256 = 0xC064
|
||||
TLS_PSK_WITH_ARIA_256_CBC_SHA384 = 0xC065
|
||||
TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 = 0xC066
|
||||
TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 = 0xC067
|
||||
TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 = 0xC068
|
||||
TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 = 0xC069
|
||||
TLS_PSK_WITH_ARIA_128_GCM_SHA256 = 0xC06A
|
||||
TLS_PSK_WITH_ARIA_256_GCM_SHA384 = 0xC06B
|
||||
TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 = 0xC06C
|
||||
TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 = 0xC06D
|
||||
TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 = 0xC06E
|
||||
TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 = 0xC06F
|
||||
TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 = 0xC070
|
||||
TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 = 0xC071
|
||||
TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 = 0xC072
|
||||
TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 = 0xC073
|
||||
TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 = 0xC074
|
||||
TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 = 0xC075
|
||||
TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 = 0xC076
|
||||
TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 = 0xC077
|
||||
TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 = 0xC078
|
||||
TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 = 0xC079
|
||||
TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 = 0xC07A
|
||||
TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 = 0xC07B
|
||||
TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 = 0xC07C
|
||||
TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 = 0xC07D
|
||||
TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256 = 0xC07E
|
||||
TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384 = 0xC07F
|
||||
TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256 = 0xC080
|
||||
TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384 = 0xC081
|
||||
TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256 = 0xC082
|
||||
TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384 = 0xC083
|
||||
TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256 = 0xC084
|
||||
TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384 = 0xC085
|
||||
TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 = 0xC086
|
||||
TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 = 0xC087
|
||||
TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 = 0xC088
|
||||
TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 = 0xC089
|
||||
TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 = 0xC08A
|
||||
TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 = 0xC08B
|
||||
TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 = 0xC08C
|
||||
TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 = 0xC08D
|
||||
TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 = 0xC08E
|
||||
TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 = 0xC08F
|
||||
TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 = 0xC090
|
||||
TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 = 0xC091
|
||||
TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 = 0xC092
|
||||
TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 = 0xC093
|
||||
TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 = 0xC094
|
||||
TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 = 0xC095
|
||||
TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 = 0xC096
|
||||
TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 = 0xC097
|
||||
TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 = 0xC098
|
||||
TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 = 0xC099
|
||||
TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 = 0xC09A
|
||||
TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 = 0xC09B
|
||||
TLS_RSA_WITH_AES_128_CCM = 0xC09C
|
||||
TLS_RSA_WITH_AES_256_CCM = 0xC09D
|
||||
TLS_DHE_RSA_WITH_AES_128_CCM = 0xC09E
|
||||
TLS_DHE_RSA_WITH_AES_256_CCM = 0xC09F
|
||||
TLS_RSA_WITH_AES_128_CCM_8 = 0xC0A0
|
||||
TLS_RSA_WITH_AES_256_CCM_8 = 0xC0A1
|
||||
TLS_DHE_RSA_WITH_AES_128_CCM_8 = 0xC0A2
|
||||
TLS_DHE_RSA_WITH_AES_256_CCM_8 = 0xC0A3
|
||||
TLS_PSK_WITH_AES_128_CCM = 0xC0A4
|
||||
TLS_PSK_WITH_AES_256_CCM = 0xC0A5
|
||||
TLS_DHE_PSK_WITH_AES_128_CCM = 0xC0A6
|
||||
TLS_DHE_PSK_WITH_AES_256_CCM = 0xC0A7
|
||||
TLS_PSK_WITH_AES_128_CCM_8 = 0xC0A8
|
||||
TLS_PSK_WITH_AES_256_CCM_8 = 0xC0A9
|
||||
TLS_PSK_DHE_WITH_AES_128_CCM_8 = 0xC0AA
|
||||
TLS_PSK_DHE_WITH_AES_256_CCM_8 = 0xC0AB
|
||||
TLS_ECDHE_ECDSA_WITH_AES_128_CCM = 0xC0AC
|
||||
TLS_ECDHE_ECDSA_WITH_AES_256_CCM = 0xC0AD
|
||||
TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 = 0xC0AE
|
||||
TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 = 0xC0AF
|
||||
TLS_ECCPWD_WITH_AES_128_GCM_SHA256 = 0xC0B0
|
||||
TLS_ECCPWD_WITH_AES_256_GCM_SHA384 = 0xC0B1
|
||||
TLS_ECCPWD_WITH_AES_128_CCM_SHA256 = 0xC0B2
|
||||
TLS_ECCPWD_WITH_AES_256_CCM_SHA384 = 0xC0B3
|
||||
TLS_SHA256_SHA256 = 0xC0B4
|
||||
TLS_SHA384_SHA384 = 0xC0B5
|
||||
TLS_GOSTR341112_256_WITH_KUZNYECHIK_CTR_OMAC = 0xC100
|
||||
TLS_GOSTR341112_256_WITH_MAGMA_CTR_OMAC = 0xC101
|
||||
TLS_GOSTR341112_256_WITH_28147_CNT_IMIT = 0xC102
|
||||
TLS_GOSTR341112_256_WITH_KUZNYECHIK_MGM_L = 0xC103
|
||||
TLS_GOSTR341112_256_WITH_MAGMA_MGM_L = 0xC104
|
||||
TLS_GOSTR341112_256_WITH_KUZNYECHIK_MGM_S = 0xC105
|
||||
TLS_GOSTR341112_256_WITH_MAGMA_MGM_S = 0xC106
|
||||
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA8
|
||||
TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA9
|
||||
TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCAA
|
||||
TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 = 0xCCAB
|
||||
TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 = 0xCCAC
|
||||
TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 = 0xCCAD
|
||||
TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 = 0xCCAE
|
||||
TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256 = 0xD001
|
||||
TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384 = 0xD002
|
||||
TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256 = 0xD003
|
||||
TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256 = 0xD005
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> typing.Optional[enum.Enum]:
|
||||
return _add_missing_enum_member(cls, value, "Unknown Cipher Suite 0x{0:04X}")
|
||||
|
||||
|
||||
class TlsCompressionMethod(enum.IntEnum):
|
||||
none = 0
|
||||
deflate = 1
|
||||
lzs = 64
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> typing.Optional[enum.Enum]:
|
||||
return _add_missing_enum_member(cls, value, "Unknown Compression Method 0x{0:02X}")
|
||||
|
||||
|
||||
class TlsExtensionType(enum.IntEnum):
|
||||
server_name = 0
|
||||
max_fragment_length = 1
|
||||
client_certificate_url = 2
|
||||
trusted_ca_keys = 3
|
||||
truncated_hmac = 4
|
||||
status_request = 5
|
||||
user_mapping = 6
|
||||
client_authz = 7
|
||||
server_authz = 8
|
||||
cert_type = 9
|
||||
supported_groups = 10
|
||||
ec_point_formats = 11
|
||||
srp = 12
|
||||
signature_algorithms = 13
|
||||
use_srtp = 14
|
||||
heartbeat = 15
|
||||
application_layer_protocol_negotiation = 16
|
||||
status_request_v2 = 17
|
||||
signed_certificate_timestamp = 18
|
||||
client_certificate_type = 19
|
||||
server_certificate_type = 20
|
||||
padding = 21
|
||||
encrypt_then_mac = 22
|
||||
extended_master_secret = 23
|
||||
token_binding = 24
|
||||
cached_info = 25
|
||||
tls_lts = 26
|
||||
compress_certificate = 27
|
||||
record_size_limit = 28
|
||||
pwd_protect = 29
|
||||
pwd_clear = 30
|
||||
password_salt = 31
|
||||
ticket_pinning = 32
|
||||
tls_cert_with_extern_psk = 33
|
||||
delegated_credentials = 34
|
||||
session_ticket = 35
|
||||
TLMSP = 36
|
||||
TLMSP_proxying = 37
|
||||
TLMSP_delegate = 38
|
||||
supported_ekt_ciphers = 39
|
||||
pre_shared_key = 41
|
||||
early_data = 42
|
||||
supported_versions = 43
|
||||
cookie = 44
|
||||
psk_key_exchange_modes = 45
|
||||
certificate_authorities = 47
|
||||
oid_filters = 48
|
||||
post_handshake_auth = 49
|
||||
signature_algorithms_cert = 50
|
||||
key_share = 51
|
||||
transparency_info = 52
|
||||
connection_id_deprecated = 53
|
||||
connection_id = 54
|
||||
external_id_hash = 55
|
||||
external_session_id = 56
|
||||
quic_transport_parameters = 57
|
||||
ticket_request = 58
|
||||
dnssec_chain = 69
|
||||
renegotiation_info = 65281
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> typing.Optional[enum.Enum]:
|
||||
return _add_missing_enum_member(cls, value, "Unknown Extension Type 0x{0:04X}")
|
||||
|
||||
|
||||
class TlsServerNameType(enum.IntEnum):
|
||||
server_name = 0
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> typing.Optional[enum.Enum]:
|
||||
return _add_missing_enum_member(cls, value, "Unknown Server Name Type 0x{0:02X}")
|
||||
|
||||
|
||||
class TlsECPointFormat(enum.IntEnum):
|
||||
uncompressed = 0
|
||||
ansiX962_compressed_prime = 1
|
||||
ansiX962_compressed_char2 = 2
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> typing.Optional[enum.Enum]:
|
||||
return _add_missing_enum_member(cls, value, "Unknown EC Point Format 0x{0:02X}")
|
||||
|
||||
|
||||
class TlsSupportedGroup(enum.IntEnum):
|
||||
reserved = 0
|
||||
sect163k1 = 1
|
||||
sect163r1 = 2
|
||||
sect163r2 = 3
|
||||
sect193r1 = 4
|
||||
sect193r2 = 5
|
||||
sect233k1 = 6
|
||||
sect233r1 = 7
|
||||
sect239k1 = 8
|
||||
sect283k1 = 9
|
||||
sect283r1 = 10
|
||||
sect409k1 = 11
|
||||
sect409r1 = 12
|
||||
sect571k1 = 13
|
||||
sect571r1 = 14
|
||||
secp160k1 = 15
|
||||
secp160r1 = 16
|
||||
secp160r2 = 17
|
||||
secp192k1 = 18
|
||||
secp192r1 = 19
|
||||
secp224k1 = 20
|
||||
secp224r1 = 21
|
||||
secp256k1 = 22
|
||||
secp256r1 = 23
|
||||
secp384r1 = 24
|
||||
secp521r1 = 25
|
||||
brainpoolP256r1 = 26
|
||||
brainpoolP384r1 = 27
|
||||
brainpoolP512r1 = 28
|
||||
x25519 = 29
|
||||
x448 = 30
|
||||
brainpoolP256r1tls13 = 31
|
||||
brainpoolP384r1tls13 = 32
|
||||
brainpoolP512r1tls13 = 33
|
||||
GC256A = 34
|
||||
GC256B = 35
|
||||
GC256C = 36
|
||||
GC256D = 37
|
||||
GC512A = 38
|
||||
GC512B = 39
|
||||
GC512C = 40
|
||||
curveSM2 = 41
|
||||
ffdhe2048 = 256
|
||||
ffdhe3072 = 257
|
||||
ffdhe4096 = 258
|
||||
ffdhe6144 = 259
|
||||
ffdhe8192 = 260
|
||||
arbitrary_explicit_prime_curves = 65281
|
||||
arbitrary_explicit_char2_curves = 65282
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> typing.Optional[enum.Enum]:
|
||||
return _add_missing_enum_member(cls, value, "Unknown Supported Group 0x{0:04X}")
|
||||
|
||||
|
||||
class TlsSignatureScheme(enum.IntEnum):
|
||||
rsa_pkcs1_sha1 = 0x0201
|
||||
dsa_sha1 = 0x0202
|
||||
ecdsa_sha1 = 0x0203
|
||||
sha224_rsa = 0x0301
|
||||
dsa_sha224 = 0x0302
|
||||
sha224_ecdsa = 0x0303
|
||||
rsa_pkcs1_sha256 = 0x0401
|
||||
dsa_sha256 = 0x0402
|
||||
ecdsa_secp256r1_sha256 = 0x0403
|
||||
rsa_pkcs1_sha256_legacy = 0x0420
|
||||
rsa_pkcs1_sha384 = 0x0501
|
||||
dsa_sha384 = 0x0502
|
||||
ecdsa_secp384r1_sha384 = 0x0503
|
||||
rsa_pkcs1_sha384_legacy = 0x0520
|
||||
rsa_pkcs1_sha512 = 0x0601
|
||||
dsa_sha512 = 0x0602
|
||||
ecdsa_secp521r1_sha512 = 0x0603
|
||||
rsa_pkcs1_sha512_legacy = 0x0620
|
||||
eccsi_sha256 = 0x0704
|
||||
iso_ibs1 = 0x0705
|
||||
iso_ibs2 = 0x0706
|
||||
iso_chinese_ibs = 0x0707
|
||||
sm2sig_sm3 = 0x0708
|
||||
gostr34102012_256a = 0x0709
|
||||
gostr34102012_256b = 0x070A
|
||||
gostr34102012_256c = 0x070B
|
||||
gostr34102012_256d = 0x070C
|
||||
gostr34102012_512a = 0x070D
|
||||
gostr34102012_512b = 0x070E
|
||||
gostr34102012_512c = 0x070F
|
||||
rsa_pss_rsae_sha256 = 0x0804
|
||||
rsa_pss_rsae_sha384 = 0x0805
|
||||
rsa_pss_rsae_sha512 = 0x0806
|
||||
ed25519 = 0x0807
|
||||
ed448 = 0x0808
|
||||
rsa_pss_pss_sha256 = 0x0809
|
||||
rsa_pss_pss_sha384 = 0x080A
|
||||
rsa_pss_pss_sha512 = 0x080B
|
||||
ecdsa_brainpoolP256r1tls13_sha256 = 0x081A
|
||||
ecdsa_brainpoolP384r1tls13_sha384 = 0x081B
|
||||
ecdsa_brainpoolP512r1tls13_sha512 = 0x081C
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> typing.Optional[enum.Enum]:
|
||||
return _add_missing_enum_member(cls, value, "Unknown Signature Scheme 0x{0:04X}")
|
||||
|
||||
|
||||
class TlsPskKeyExchangeMode(enum.IntEnum):
|
||||
psk_ke = 0
|
||||
psk_dhe_ke = 1
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> typing.Optional[enum.Enum]:
|
||||
return _add_missing_enum_member(cls, value, "Unknown PSK Key Exchange Mode 0x{0:02X}")
|
||||
|
||||
|
||||
class TlsECCurveType(enum.IntEnum):
|
||||
unassigned = 0
|
||||
explicit_primve = 1
|
||||
explicit_char2 = 2
|
||||
named_curve = 3
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> typing.Optional[enum.Enum]:
|
||||
return _add_missing_enum_member(cls, value, "Unknown EC Curve Type 0x{0:02X}")
|
||||
|
||||
|
||||
class TlsClientCertificateType(enum.IntEnum):
|
||||
rsa_sign = 1
|
||||
dss_sign = 2
|
||||
rsa_fixed_dh = 3
|
||||
dss_fixed_dh = 4
|
||||
rsa_ephemeral_dh = 5
|
||||
dss_ephemeral_dh = 6
|
||||
fortezza_dms = 20
|
||||
ecdsa_sign = 64
|
||||
rsa_fixed_ecdh = 65
|
||||
ecdsa_fixed_ecdh = 66
|
||||
gost_sign256 = 67
|
||||
gost_sign512 = 68
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> typing.Optional[enum.Enum]:
|
||||
return _add_missing_enum_member(cls, value, "Unknown Client Certificate Type 0x{0:02X}")
|
||||
|
||||
|
||||
class DistinguishedNameType(str, enum.Enum):
|
||||
object_class = "2.5.4.0"
|
||||
aliased_entry_name = "2.5.4.1"
|
||||
knowledge_information = "2.5.4.2"
|
||||
common_name = "2.5.4.3"
|
||||
surname = "2.5.4.4"
|
||||
serial_number = "2.5.4.5"
|
||||
country_name = "2.5.4.6"
|
||||
locality_name = "2.5.4.7"
|
||||
state_or_province_name = "2.5.4.8"
|
||||
street_address = "2.5.4.9"
|
||||
organizational_name = "2.5.4.10"
|
||||
organizational_unit_name = "2.5.4.11"
|
||||
id_title = "2.5.4.12"
|
||||
description = "2.5.4.13"
|
||||
search_guide = "2.5.4.14"
|
||||
business_category = "2.5.4.15"
|
||||
postal_address = "2.5.4.16"
|
||||
postal_code = "2.5.4.17"
|
||||
post_office_box = "2.5.4.18"
|
||||
physical_delivery_office_name = "2.5.4.19"
|
||||
telephone_number = "2.5.4.20"
|
||||
telex_number = "2.5.4.21"
|
||||
teletex_terminal_identifier = "2.5.4.22"
|
||||
facsimile_telephone_number = "2.5.4.23"
|
||||
x121_address = "2.5.4.24"
|
||||
international_isdn_number = "2.5.4.25"
|
||||
registered_address = "2.5.4.26"
|
||||
destination_indicator = "2.5.4.27"
|
||||
preferred_delivery_method = "2.5.4.28"
|
||||
presentation_address = "2.5.4.29"
|
||||
supported_application_context = "2.5.4.30"
|
||||
member = "2.5.4.31"
|
||||
owner = "2.5.4.32"
|
||||
role_occupant = "2.5.4.33"
|
||||
see_also = "2.5.4.34"
|
||||
user_password = "2.5.4.35"
|
||||
user_certificate = "2.5.4.36"
|
||||
ca_certificate = "2.5.4.37"
|
||||
authority_revocation_list = "2.5.4.38"
|
||||
certificate_revocation_list = "2.5.4.39"
|
||||
cross_certificate_pair = "2.5.4.40"
|
||||
id_name = "2.5.4.41"
|
||||
given_name = "2.5.4.42"
|
||||
initials = "2.5.4.43"
|
||||
generation_qualifier = "2.5.4.44"
|
||||
unique_identifier = "2.5.4.45"
|
||||
dn_qualifier = "2.5.4.46"
|
||||
enhanced_search_guide = "2.5.4.47"
|
||||
protocol_information = "2.5.4.48"
|
||||
distinguished_name = "2.5.4.49"
|
||||
unique_member = "2.5.4.50"
|
||||
house_identifier = "2.5.4.51"
|
||||
supported_algorithms = "2.5.4.52"
|
||||
delta_revocation_list = "2.5.4.53"
|
||||
attribute_certificate = "2.5.4.58"
|
||||
pseudonym = "2.5.4.65"
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> typing.Optional[enum.Enum]:
|
||||
new_member = str.__new__(cls)
|
||||
new_member._name_ = f"Unknown DN OID Type {value}"
|
||||
new_member._value_ = str(value)
|
||||
return cls._value2member_map_.setdefault(value, new_member)
|
||||
|
||||
@classmethod
|
||||
def native_labels(cls) -> typing.Dict["DistinguishedNameType", str]:
|
||||
return {
|
||||
DistinguishedNameType.object_class: "id-at-objectClass",
|
||||
DistinguishedNameType.aliased_entry_name: "id-at-aliasedEntryName",
|
||||
DistinguishedNameType.knowledge_information: "id-at-knowldgeinformation",
|
||||
DistinguishedNameType.common_name: "id-at-commonName",
|
||||
DistinguishedNameType.surname: "id-at-surname",
|
||||
DistinguishedNameType.serial_number: "id-at-serialNumber",
|
||||
DistinguishedNameType.country_name: "id-at-countryName",
|
||||
DistinguishedNameType.locality_name: "id-at-localityName",
|
||||
DistinguishedNameType.state_or_province_name: "id-at-stateOrProvinceName",
|
||||
DistinguishedNameType.street_address: "id-at-streetAddress",
|
||||
DistinguishedNameType.organizational_name: "id-at-organizationName",
|
||||
DistinguishedNameType.organizational_unit_name: "id-at-organizationalUnitName",
|
||||
DistinguishedNameType.id_title: "id-at-title",
|
||||
DistinguishedNameType.description: "id-at-description",
|
||||
DistinguishedNameType.search_guide: "id-at-searchGuide",
|
||||
DistinguishedNameType.business_category: "id-at-businessCategory",
|
||||
DistinguishedNameType.postal_address: "id-at-postalAddress",
|
||||
DistinguishedNameType.postal_code: "id-at-postalCode",
|
||||
DistinguishedNameType.post_office_box: "id-at-postOfficeBox",
|
||||
DistinguishedNameType.physical_delivery_office_name: "id-at-physicalDeliveryOfficeName",
|
||||
DistinguishedNameType.telephone_number: "id-at-telephoneNumber",
|
||||
DistinguishedNameType.telex_number: "id-at-telexNumber",
|
||||
DistinguishedNameType.teletex_terminal_identifier: "id-at-teletexTerminalIdentifier",
|
||||
DistinguishedNameType.facsimile_telephone_number: "id-at-facsimileTelephoneNumber",
|
||||
DistinguishedNameType.x121_address: "id-at-x121Address",
|
||||
DistinguishedNameType.international_isdn_number: "id-at-internationalISDNNumber",
|
||||
DistinguishedNameType.registered_address: "id-at-registeredAddress",
|
||||
DistinguishedNameType.destination_indicator: "id-at-destinationIndicator",
|
||||
DistinguishedNameType.preferred_delivery_method: "id-at-preferredDeliveryMethod",
|
||||
DistinguishedNameType.presentation_address: "id-at-presentationAddress",
|
||||
DistinguishedNameType.supported_application_context: "id-at-supportedApplicationContext",
|
||||
DistinguishedNameType.member: "id-at-member",
|
||||
DistinguishedNameType.owner: "id-at-owner",
|
||||
DistinguishedNameType.role_occupant: "id-at-roleOccupant",
|
||||
DistinguishedNameType.see_also: "id-at-seeAlso",
|
||||
DistinguishedNameType.user_password: "id-at-userPassword",
|
||||
DistinguishedNameType.user_certificate: "id-at-userCertificate",
|
||||
DistinguishedNameType.ca_certificate: "id-at-cACertificate",
|
||||
DistinguishedNameType.authority_revocation_list: "id-at-authorityRevocationList",
|
||||
DistinguishedNameType.certificate_revocation_list: "id-at-certificateRevocationList",
|
||||
DistinguishedNameType.cross_certificate_pair: "id-at-crossCertificatePair",
|
||||
DistinguishedNameType.id_name: "id-at-name",
|
||||
DistinguishedNameType.given_name: "id-at-givenName",
|
||||
DistinguishedNameType.initials: "id-at-initials",
|
||||
DistinguishedNameType.generation_qualifier: "id-at-generationQualifier",
|
||||
DistinguishedNameType.unique_identifier: "id-at-uniqueIdentifier",
|
||||
DistinguishedNameType.dn_qualifier: "id-at-dnQualifier",
|
||||
DistinguishedNameType.enhanced_search_guide: "id-at-enhancedSearchGuide",
|
||||
DistinguishedNameType.protocol_information: "id-at-protocolInformation",
|
||||
DistinguishedNameType.distinguished_name: "id-at-distinguishedName",
|
||||
DistinguishedNameType.unique_member: "id-at-uniqueMember",
|
||||
DistinguishedNameType.house_identifier: "id-at-houseIdentifier",
|
||||
DistinguishedNameType.supported_algorithms: "id-at-supportedAlgorithms",
|
||||
DistinguishedNameType.delta_revocation_list: "id-at-deltaRevocationList",
|
||||
DistinguishedNameType.attribute_certificate: "id-at-attributeCertificate",
|
||||
DistinguishedNameType.pseudonym: "id-at-pseudonym",
|
||||
}
|
||||
4
env/lib/python3.12/site-packages/spnego/_version.py
vendored
Normal file
4
env/lib/python3.12/site-packages/spnego/_version.py
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
__version__ = "0.12.2"
|
||||
206
env/lib/python3.12/site-packages/spnego/auth.py
vendored
Normal file
206
env/lib/python3.12/site-packages/spnego/auth.py
vendored
Normal file
@@ -0,0 +1,206 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import typing
|
||||
|
||||
from spnego._context import ContextProxy, ContextReq
|
||||
from spnego._credential import Credential, NTLMHash, unify_credentials
|
||||
from spnego._credssp import CredSSPProxy
|
||||
from spnego._gss import GSSAPIProxy
|
||||
from spnego._negotiate import NegotiateProxy
|
||||
from spnego._ntlm import NTLMProxy
|
||||
from spnego._sspi import SSPIProxy
|
||||
from spnego.channel_bindings import GssChannelBindings
|
||||
from spnego.exceptions import NegotiateOptions
|
||||
|
||||
|
||||
def _new_context(
|
||||
username: typing.Optional[typing.Union[str, Credential, typing.List[Credential]]],
|
||||
password: typing.Optional[str],
|
||||
hostname: str,
|
||||
service: str,
|
||||
channel_bindings: typing.Optional[GssChannelBindings],
|
||||
context_req: ContextReq,
|
||||
protocol: str,
|
||||
options: NegotiateOptions,
|
||||
usage: str,
|
||||
**kwargs: typing.Any,
|
||||
) -> ContextProxy:
|
||||
proto = protocol.lower()
|
||||
credentials = unify_credentials(username, password)
|
||||
sspi_protocols = SSPIProxy.available_protocols(options=options)
|
||||
gssapi_protocols = GSSAPIProxy.available_protocols(options=options)
|
||||
|
||||
# Unless otherwise specified, we always favour the platform implementations (SSPI/GSSAPI) if they are available.
|
||||
# Otherwise fallback to the Python implementations (NegotiateProxy/NTLMProxy).
|
||||
use_flags = (
|
||||
NegotiateOptions.use_sspi
|
||||
| NegotiateOptions.use_gssapi
|
||||
| NegotiateOptions.use_negotiate
|
||||
| NegotiateOptions.use_ntlm
|
||||
)
|
||||
use_specified = options & use_flags != 0
|
||||
|
||||
# Filter protocols that aren't compatible with the credentials provided.
|
||||
sspi_remove = set()
|
||||
for cred in credentials:
|
||||
# NTLMHash cannot be used with SSPI. The code falls back to using NTLMProxy if this credential is present.
|
||||
if isinstance(cred, NTLMHash):
|
||||
sspi_remove.add("negotiate")
|
||||
sspi_remove.add("ntlm")
|
||||
|
||||
if sspi_remove:
|
||||
for protocol in sspi_remove:
|
||||
if protocol in sspi_protocols:
|
||||
sspi_protocols.remove(protocol)
|
||||
|
||||
proxy: typing.Type[typing.Union[CredSSPProxy, NTLMProxy, SSPIProxy, GSSAPIProxy, NegotiateProxy]]
|
||||
|
||||
# If the protocol is CredSSP then we can only use CredSSPProxy. The use_flags still control what underlying
|
||||
# Negotiate auth is used in the CredSSP authentication process.
|
||||
if proto == "credssp":
|
||||
proxy = CredSSPProxy
|
||||
|
||||
elif options & NegotiateOptions.use_sspi or (not use_specified and proto in sspi_protocols):
|
||||
proxy = SSPIProxy
|
||||
|
||||
elif options & NegotiateOptions.use_gssapi or (
|
||||
not use_specified and (proto == "kerberos" or proto in gssapi_protocols)
|
||||
):
|
||||
proxy = GSSAPIProxy
|
||||
|
||||
elif options & NegotiateOptions.use_negotiate or (not use_specified and proto == "negotiate"):
|
||||
# If GSSAPI does not offer full negotiate support, use our own wrapper.
|
||||
proxy = NegotiateProxy
|
||||
|
||||
elif options & NegotiateOptions.use_ntlm or (not use_specified and proto == "ntlm"):
|
||||
# Finally if GSSAPI does not support ntlm, use our own wrapper.
|
||||
proto = "ntlm" if proto == "negotiate" else proto
|
||||
proxy = NTLMProxy
|
||||
|
||||
else:
|
||||
raise ValueError("Invalid protocol specified '%s', must be kerberos, negotiate, or ntlm" % protocol)
|
||||
|
||||
return proxy(
|
||||
username=credentials,
|
||||
password=None,
|
||||
hostname=hostname,
|
||||
service=service,
|
||||
channel_bindings=channel_bindings,
|
||||
context_req=context_req,
|
||||
usage=usage,
|
||||
protocol=proto,
|
||||
options=options,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
def client(
|
||||
username: typing.Optional[typing.Union[str, Credential, typing.List[Credential]]] = None,
|
||||
password: typing.Optional[str] = None,
|
||||
hostname: str = "unspecified",
|
||||
service: str = "host",
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
context_req: ContextReq = ContextReq.default,
|
||||
protocol: str = "negotiate",
|
||||
options: NegotiateOptions = NegotiateOptions.none,
|
||||
**kwargs: typing.Any,
|
||||
) -> ContextProxy:
|
||||
"""Create a client context to be used for authentication.
|
||||
|
||||
Credentials can be provides in 3 different ways:
|
||||
|
||||
* omitted entirely
|
||||
* `username` set to a string with an optional password
|
||||
* `username` set to a single or list of :class:`Credential` objects
|
||||
|
||||
If the credential is omitted the authentication protocol will use a
|
||||
protocol specific mechanism to find the credential in some cache. If no
|
||||
cache or credentials are found an exception is raised.
|
||||
|
||||
If `username` is a string but `password` is not defined then the provider
|
||||
specific cache is used but for the principal specified. If `password` is
|
||||
specified then a new credential is retrieved using the username/password
|
||||
combiniation. Using both `username` and `password` is the same as using
|
||||
:class:`Password` as a credential.
|
||||
|
||||
If `username` is a, or list of, `Credential` object the object(s) are
|
||||
passed into the authentication implementation for use. The behaviour of
|
||||
these credentials are defined by the authentication protocol
|
||||
implementation that uses the credential(s). Currently the :class:`Passowrd`
|
||||
credential is supported by all authentication protocols and is the same
|
||||
as specifying the username/password as separate arugments.
|
||||
|
||||
The ``negotiate`` protocol can be given a list of credentials for each of
|
||||
the sub auth protocols it negotiates to use. For example to have Negotiate
|
||||
use a Kerberos CCache for Kerberos and an NT/LM hash value for NTLM the
|
||||
following can be specified::
|
||||
|
||||
import spnego
|
||||
|
||||
credential = [
|
||||
spnego.KerberosCCache(ccache="FILE:/tmp/my-ccache"),
|
||||
spnego.NTLMHash(
|
||||
username="user",
|
||||
nt_hash="8ADB9B997580D69E69CAA2BBB68F4697",
|
||||
)
|
||||
]
|
||||
client = spnego.auth(credential, hostname="server")
|
||||
|
||||
In the example above, the negotiate protocol will attempt use the CCache
|
||||
for Kerberos auth and fallback to the NT/LM hash for NTLM auth if
|
||||
Kerberos fails. If a credential for a specific sub protocol is not
|
||||
available then Negotiate will move onto the next available one.
|
||||
|
||||
Args:
|
||||
username: The username/credential(s) to authenticate with. Certain providers can use a cache if omitted.
|
||||
password: The password to authenticate with. Should only be specified when username is a string.
|
||||
hostname: The principal part of the SPN. This is required for Kerberos auth to build the SPN.
|
||||
service: The service part of the SPN. This is required for Kerberos auth to build the SPN.
|
||||
channel_bindings: The optional :class:`spnego.channel_bindings.GssChannelBindings` for the context.
|
||||
context_req: The :class:`spnego.ContextReq` flags to use when setting up the context.
|
||||
protocol: The protocol to authenticate with, can be `ntlm`, `kerberos`, `negotiate`, or `credssp`.
|
||||
options: The :class:`spnego.NegotiateOptions` that define pyspnego specific options to control the negotiation.
|
||||
kwargs: Optional arguments to pass through to the authentiction context.
|
||||
|
||||
Returns:
|
||||
ContextProxy: The context proxy for a client.
|
||||
"""
|
||||
return _new_context(
|
||||
username, password, hostname, service, channel_bindings, context_req, protocol, options, "initiate", **kwargs
|
||||
)
|
||||
|
||||
|
||||
def server(
|
||||
hostname: str = "unspecified",
|
||||
service: str = "host",
|
||||
channel_bindings: typing.Optional[GssChannelBindings] = None,
|
||||
context_req: ContextReq = ContextReq.default,
|
||||
protocol: str = "negotiate",
|
||||
options: NegotiateOptions = NegotiateOptions.none,
|
||||
*,
|
||||
credentials: typing.Optional[typing.Union[str, Credential, typing.List[Credential]]] = None,
|
||||
**kwargs: typing.Any,
|
||||
) -> ContextProxy:
|
||||
"""Create a server context to be used for authentication.
|
||||
|
||||
It is only possible to specify a credential when running on Windows and
|
||||
using Kerberos either through Negotiate or Kerberos directly. Other
|
||||
platforms and protocols may be supported in the future.
|
||||
|
||||
Args:
|
||||
hostname: The principal part of the SPN. This is required for Kerberos auth to build the SPN.
|
||||
service: The service part of the SPN. This is required for Kerberos auth to build the SPN.
|
||||
channel_bindings: The optional :class:`spnego.channel_bindings.GssChannelBindings` for the context.
|
||||
context_req: The :class:`spnego.ContextReq` flags to use when setting up the context.
|
||||
protocol: The protocol to authenticate with, can be `ntlm`, `kerberos`, `negotiate`, or `credssp`.
|
||||
options: The :class:`spnego.NegotiateOptions` that define pyspnego specific options to control the negotiation.
|
||||
credentials: A credential or list or credentials to use with the server auth context.
|
||||
kwargs: Optional arguments to pass through to the authentiction context.
|
||||
|
||||
Returns:
|
||||
ContextProxy: The context proxy for a client.
|
||||
"""
|
||||
return _new_context(
|
||||
credentials, None, hostname, service, channel_bindings, context_req, protocol, options, "accept", **kwargs
|
||||
)
|
||||
148
env/lib/python3.12/site-packages/spnego/channel_bindings.py
vendored
Normal file
148
env/lib/python3.12/site-packages/spnego/channel_bindings.py
vendored
Normal file
@@ -0,0 +1,148 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import enum
|
||||
import struct
|
||||
import typing
|
||||
|
||||
|
||||
def _pack_value(addr_type: typing.Optional["AddressType"], b: typing.Optional[bytes]) -> bytes:
|
||||
"""Packs an type/data entry into the byte structure required."""
|
||||
if not b:
|
||||
b = b""
|
||||
|
||||
return (struct.pack("<I", addr_type) if addr_type is not None else b"") + struct.pack("<I", len(b)) + b
|
||||
|
||||
|
||||
def _unpack_value(b_mem: memoryview, offset: int) -> typing.Tuple[bytes, int]:
|
||||
"""Unpacks a raw C struct value to a byte string."""
|
||||
length = struct.unpack("<I", b_mem[offset : offset + 4].tobytes())[0]
|
||||
new_offset = offset + length + 4
|
||||
|
||||
data = b""
|
||||
if length:
|
||||
data = b_mem[offset + 4 : offset + 4 + length].tobytes()
|
||||
|
||||
return data, new_offset
|
||||
|
||||
|
||||
class AddressType(enum.IntEnum):
|
||||
unspecified = 0 # GSS_C_AF_UNSPEC
|
||||
local = 1 # GSS_C_AF_LOCAL
|
||||
inet = 2 # GSS_C_AF_INET
|
||||
implink = 3 # GSS_C_AF_IMPLINK
|
||||
pup = 4 # GSS_C_AF_PUP
|
||||
chaos = 5 # GSS_C_AF_CHAOS
|
||||
ns = 6 # GSS_C_AF_NS
|
||||
nbs = 8 # GSS_C_AF_NBS
|
||||
ecma = 8 # GSS_C_AF_ECMA
|
||||
datakit = 9 # GSS_C_AF_DATAKIT
|
||||
ccitt = 10 # GSS_C_AF_CCITT
|
||||
sna = 11 # GSS_C_AF_SNA
|
||||
decnet = 12 # GSS_C_AF_DECnet
|
||||
dli = 13 # GSS_C_AF_DLI
|
||||
lat = 14 # GSS_C_AF_LAT
|
||||
hylink = 15 # GSS_C_AF_HYLINK
|
||||
appletalk = 16 # GSS_C_AF_APPLETALK
|
||||
bsc = 17 # GSS_C_AF_BSC
|
||||
dss = 18 # GSS_C_AF_DSS
|
||||
osi = 19 # GSS_C_AF_OSI
|
||||
x25 = 21 # GSS_C_AF_X25
|
||||
inet6 = 24 # GSS_C_AF_INET6
|
||||
nulladdr = 255 # GSS_C_AF_NULLADDR
|
||||
|
||||
|
||||
class GssChannelBindings:
|
||||
"""Python representation of a GSSAPI Channel Binding data structure.
|
||||
|
||||
A common representation for a GSSAPI Channel Binding data structure that can be passed into a context to bind
|
||||
against that security context. Channel bindings are tags that identify the particular data channel that is used.
|
||||
Because these tags are specific to the originator and recipient applications, they offer more proof of a valid
|
||||
identity. Most HTTPS based authentications just set the application data to b'tls-server-end-point:<cert hash>'.
|
||||
|
||||
Args:
|
||||
initiator_addrtype: The address type of the initiator address.
|
||||
initiator_address: The initiator's address.
|
||||
acceptor_addrtype: The address type of the acceptor address.
|
||||
acceptor_address: The acceptor's address.
|
||||
application_data: Any extra application data to set on the bindings struct.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
initiator_addrtype: AddressType = AddressType.unspecified,
|
||||
initiator_address: typing.Optional[bytes] = None,
|
||||
acceptor_addrtype: AddressType = AddressType.unspecified,
|
||||
acceptor_address: typing.Optional[bytes] = None,
|
||||
application_data: typing.Optional[bytes] = None,
|
||||
) -> None:
|
||||
self.initiator_addrtype = AddressType(initiator_addrtype)
|
||||
self.initiator_address = initiator_address
|
||||
self.acceptor_addrtype = AddressType(acceptor_addrtype)
|
||||
self.acceptor_address = acceptor_address
|
||||
self.application_data = application_data
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
"{0}.{1} initiator_addrtype={2}|initiator_address={3}|acceptor_addrtype={4}|acceptor_address={5}|"
|
||||
"application_data={6}".format(
|
||||
type(self).__module__,
|
||||
type(self).__name__,
|
||||
repr(self.initiator_addrtype),
|
||||
repr(self.initiator_address),
|
||||
repr(self.acceptor_addrtype),
|
||||
repr(self.acceptor_address),
|
||||
repr(self.application_data),
|
||||
)
|
||||
)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return "{0} initiator_addr({1}.{2}|{3!r}) | acceptor_addr({4}.{5}|{6!r}) | application_data({7!r})".format(
|
||||
type(self).__name__,
|
||||
type(self.initiator_addrtype).__name__,
|
||||
self.initiator_addrtype.name,
|
||||
self.initiator_address,
|
||||
type(self.acceptor_addrtype).__name__,
|
||||
self.acceptor_addrtype.name,
|
||||
self.acceptor_address,
|
||||
self.application_data,
|
||||
)
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
if not isinstance(other, (bytes, GssChannelBindings)):
|
||||
return False
|
||||
|
||||
if isinstance(other, GssChannelBindings):
|
||||
other = other.pack()
|
||||
|
||||
return self.pack() == other
|
||||
|
||||
def pack(self) -> bytes:
|
||||
"""Pack struct into a byte string."""
|
||||
return b"".join(
|
||||
[
|
||||
_pack_value(self.initiator_addrtype, self.initiator_address),
|
||||
_pack_value(self.acceptor_addrtype, self.acceptor_address),
|
||||
_pack_value(None, self.application_data),
|
||||
]
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def unpack(b_data: bytes) -> "GssChannelBindings":
|
||||
b_mem = memoryview(b_data)
|
||||
|
||||
initiator_addrtype = struct.unpack("<I", b_mem[:4].tobytes())[0]
|
||||
initiator_address, offset = _unpack_value(b_mem, 4)
|
||||
|
||||
acceptor_addrtype = struct.unpack("<I", b_mem[offset : offset + 4].tobytes())[0]
|
||||
acceptor_address, offset = _unpack_value(b_mem, offset + 4)
|
||||
|
||||
application_data = _unpack_value(b_mem, offset)[0]
|
||||
|
||||
return GssChannelBindings(
|
||||
initiator_addrtype=initiator_addrtype,
|
||||
initiator_address=initiator_address,
|
||||
acceptor_addrtype=acceptor_addrtype,
|
||||
acceptor_address=acceptor_address,
|
||||
application_data=application_data,
|
||||
)
|
||||
377
env/lib/python3.12/site-packages/spnego/exceptions.py
vendored
Normal file
377
env/lib/python3.12/site-packages/spnego/exceptions.py
vendored
Normal file
@@ -0,0 +1,377 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import enum
|
||||
import typing
|
||||
|
||||
GSSError: typing.Type[Exception]
|
||||
try:
|
||||
from gssapi.raw import GSSError # type: ignore
|
||||
except ImportError as e:
|
||||
GSSError = Exception
|
||||
|
||||
WinError: typing.Type[Exception]
|
||||
try:
|
||||
WinError = WindowsError # type: ignore
|
||||
except NameError:
|
||||
WinError = Exception
|
||||
|
||||
|
||||
class NativeError(Exception):
|
||||
"""Stub for a native error that can be used to generate a SpnegoError from a known platform native code."""
|
||||
|
||||
def __init__(self, msg: str, **kwargs: typing.Any) -> None:
|
||||
self.msg = msg
|
||||
for key in ["maj_code", "winerror"]:
|
||||
if key in kwargs:
|
||||
setattr(self, key, kwargs[key])
|
||||
|
||||
|
||||
class NegotiateOptions(enum.IntFlag):
|
||||
"""Flags that the caller can use to control the negotiation behaviour.
|
||||
|
||||
A list of features as bit flags that the caller can specify when creating the security context. These flags can
|
||||
be used on both Windows or Linux but are a no-op on Windows as it should always have the same features available.
|
||||
On Linux the features it can implement depend on a wide range of factors like the system libraries/headers that
|
||||
are installed, what GSSAPI implementation is present, and what Python libraries are available.
|
||||
|
||||
This is a pretty advanced feature and is mostly a way to control the kerberos to ntlm fallback behaviour on Linux.
|
||||
The `use_*` options when combined with `protocol='credssp'` control the underlying auth proxy provider that is used
|
||||
in the CredSSP authentication process and not the parent context proxy the user interacts with.
|
||||
|
||||
These are the currently implemented feature flags:
|
||||
|
||||
use_sspi:
|
||||
Ensures the context proxy used is :class:`spnego._sspi.SSPIProxy`.
|
||||
|
||||
use_gssapi:
|
||||
Ensures the context proxy used is :class:`spnego._gss.GSSAPIProxy`.
|
||||
|
||||
use_negotiate:
|
||||
Ensures the context proxy used is :class:`spnego._negotiate.NegotiateProxy`.
|
||||
|
||||
use_ntlm:
|
||||
Ensures the context proxy used is :class:`spnego._ntlm.NTLMProxy`.
|
||||
|
||||
negotiate_kerberos:
|
||||
Will make sure that Kerberos is at least available to try for authentication when using the `negotiate`
|
||||
protocol. If Kerberos cannot be used due to the Python gssapi library not being installed then it will raise a
|
||||
:class:`spnego.exceptions.FeatureMissingError`. If Kerberos was available but it cannot get a credential or
|
||||
create a context then it will just fallback to NTLM auth. If you wish to only use Kerberos with no NTLM
|
||||
fallback, set `protocol='kerberos'` when creating the security context.
|
||||
|
||||
session_key:
|
||||
Ensure that the authenticated context will be able to return the session key that was negotiated between the
|
||||
client and the server. Older versions of `gss-ntlmssp`_ do not expose the functions required to retrieve this
|
||||
info so when this feature flag is set then the NTLM fallback process will use a builtin NTLM process and not
|
||||
`gss-ntlmssp`_ if the latter is too old to retrieve the session key. Cannot be used in combination with
|
||||
`protocol='credssp'` as CredSSP does not provide a session key.
|
||||
|
||||
wrapping_iov:
|
||||
The GSSAPI IOV methods are extensions to the Kerberos spec and not implemented or exposed on all platforms,
|
||||
macOS is a popular example. If the caller requires the wrap_iov and unwrap_iov methods this will ensure it
|
||||
fails fast before the auth has been set up. Unfortunately there is no fallback for this as if the headers
|
||||
aren't present for GSSAPI then we can't do anything to fix that. This won't fail if `negotiate` was used and
|
||||
NTLM was the chosen protocol as that happens post negotiation.
|
||||
|
||||
wrapping_winrm:
|
||||
To created a wrapped WinRM message the IOV extensions are required when using Kerberos auth. Setting this flag
|
||||
will skip Kerberos when `protocol='negotiate'` if the IOV headers aren't present and just fallback to NTLM.
|
||||
|
||||
.. _gss-ntlmssp:
|
||||
https://github.com/gssapi/gss-ntlmssp
|
||||
"""
|
||||
|
||||
none = 0x00000000
|
||||
|
||||
# Force a specific provider
|
||||
use_sspi = 0x00000001
|
||||
use_gssapi = 0x00000002
|
||||
use_negotiate = 0x00000004
|
||||
use_ntlm = 0x00000008
|
||||
|
||||
negotiate_kerberos = 0x00000010
|
||||
session_key = 0x00000020
|
||||
wrapping_iov = 0x00000040
|
||||
wrapping_winrm = 0x00000080
|
||||
|
||||
|
||||
class FeatureMissingError(Exception):
|
||||
@property
|
||||
def feature_id(self) -> NegotiateOptions:
|
||||
return self.args[0]
|
||||
|
||||
@property
|
||||
def message(self) -> str:
|
||||
msg = {
|
||||
NegotiateOptions.negotiate_kerberos: "The Python gssapi library is not installed so Kerberos cannot be "
|
||||
"negotiated.",
|
||||
NegotiateOptions.wrapping_iov: "The system is missing the GSSAPI IOV extension headers or CredSSP is "
|
||||
"being requested, cannot utilize wrap_iov and unwrap_iov",
|
||||
NegotiateOptions.wrapping_winrm: "The system is missing the GSSAPI IOV extension headers required for "
|
||||
"WinRM encryption with Kerberos.",
|
||||
NegotiateOptions.session_key: "The protocol selected does not support getting the session key.",
|
||||
}.get(self.feature_id, "Unknown option flag: %d" % self.feature_id)
|
||||
|
||||
return msg
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.message
|
||||
|
||||
|
||||
class ErrorCode(enum.IntEnum):
|
||||
"""Common error codes for SPNEGO operations.
|
||||
|
||||
Mostly a copy of the `GSS major error codes`_ with the names made more pythonic. Not all codes have a corresponding
|
||||
SpnegoError class as they are reserved for the codes that apply to both GSSAPI and SSPI.
|
||||
|
||||
.. _GSS major error codes:
|
||||
https://docs.oracle.com/cd/E19683-01/816-1331/reference-4/index.html
|
||||
"""
|
||||
|
||||
bad_mech = 1 # BadMechanismError
|
||||
bad_name = 2 # BadNameError
|
||||
# bad_nametype = 3 # No equivalent in SSPI, shouldn't happen in our code as well.
|
||||
bad_bindings = 4 # BadBindings
|
||||
# bad_status = 5 # Only used in gss_display_status which we don't care about.
|
||||
bad_mic = 6 # BadMICError
|
||||
no_cred = 7 # NoCredentialError
|
||||
no_context = 8 # NoContextError
|
||||
invalid_token = 9 # InvalidTokenError
|
||||
invalid_credential = 10 # InvalidCredentialError
|
||||
credentials_expired = 11 # CredentialsExpiredError
|
||||
context_expired = 12 # ContextExpiredError
|
||||
failure = 13 # This is a generic error with the error coming from the minor code, uses SpnegoError directly.
|
||||
bad_qop = 14 # UnsupportedQop
|
||||
# unauthorized = 15 # Shouldn't happen in our code, we don't do any authorization functions.
|
||||
unavailable = 16 # OperationNotAvailableError
|
||||
# duplicate_element = 17 # Shouldn't happen in our code.
|
||||
# name_not_mn = 18 # Shouldn't happen in our code.
|
||||
|
||||
|
||||
# Implementation is inspired by the python-gssapi project https://github.com/pythongssapi/python-gssapi.
|
||||
# https://github.com/pythongssapi/python-gssapi/blob/826c02de1c1885896924bf342c60087f369c6b1a/gssapi/raw/misc.pyx#L180
|
||||
class _SpnegoErrorRegistry(type):
|
||||
__registry: typing.Dict[int, typing.Type] = {}
|
||||
__gssapi_map: typing.Dict[int, int] = {}
|
||||
__sspi_map: typing.Dict[int, int] = {}
|
||||
|
||||
def __init__(
|
||||
cls,
|
||||
*args: typing.Any,
|
||||
**kwargs: typing.Any,
|
||||
) -> None:
|
||||
# Load up the registry with the instantiated class so we can look it up when creating a SpnegoError.
|
||||
error_code = getattr(cls, "ERROR_CODE", None)
|
||||
|
||||
if error_code is not None and error_code not in cls.__registry:
|
||||
cls.__registry[error_code] = cls
|
||||
|
||||
# Map the system error codes to the common spnego error code.
|
||||
for system_attr, mapping in [("_GSSAPI_CODE", cls.__gssapi_map), ("_SSPI_CODE", cls.__sspi_map)]:
|
||||
codes = getattr(cls, system_attr, None)
|
||||
|
||||
if codes is None:
|
||||
continue
|
||||
|
||||
if not isinstance(codes, (list, tuple)):
|
||||
codes = [codes]
|
||||
|
||||
for c in codes:
|
||||
mapping[c] = error_code or 0
|
||||
|
||||
def __call__(
|
||||
cls,
|
||||
error_code: typing.Optional[int] = None,
|
||||
base_error: typing.Optional[Exception] = None,
|
||||
*args: typing.Any,
|
||||
**kwargs: typing.Any,
|
||||
) -> "_SpnegoErrorRegistry":
|
||||
error_code = error_code if error_code is not None else getattr(cls, "ERROR_CODE", None)
|
||||
|
||||
if error_code is None:
|
||||
if not base_error:
|
||||
raise ValueError("%s requires either an error_code or base_error" % cls.__name__)
|
||||
|
||||
# GSSError
|
||||
maj_code = getattr(base_error, "maj_code", None)
|
||||
# WindowsError
|
||||
winerror = getattr(base_error, "winerror", None)
|
||||
|
||||
if maj_code is not None:
|
||||
error_code = cls.__gssapi_map.get(maj_code, None)
|
||||
|
||||
elif winerror is not None:
|
||||
error_code = cls.__sspi_map.get(winerror, None)
|
||||
|
||||
else:
|
||||
raise ValueError(
|
||||
"base_error of type '%s' is not supported, must be a gssapi.exceptions.GSSError or "
|
||||
"WindowsError" % type(base_error).__name__
|
||||
)
|
||||
|
||||
new_cls = cls.__registry.get(error_code or 0, cls)
|
||||
return super(_SpnegoErrorRegistry, new_cls).__call__(
|
||||
error_code, # type: ignore[arg-type] # I cannot understand this, seems to be bug?
|
||||
base_error,
|
||||
*args,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
class SpnegoError(Exception, metaclass=_SpnegoErrorRegistry):
|
||||
"""Common error for SPNEGO exception.
|
||||
|
||||
Creates an common error record for SPNEGO errors raised by pyspnego. This error record can wrap system level error
|
||||
records raised by GSSAPI or SSPI and wrap them into a common error record across the various platforms. While this
|
||||
reflects the GSSAPI major codes that can be raised, it is up to the GSSAPI platform to conform to those error
|
||||
codes. Some platforms like MIT krb5 always report `GSS_S_FAILURE` and use the minor code to report the actual
|
||||
error message.
|
||||
|
||||
Args:
|
||||
error_code: The ErrorCode for the error, this must be set if base_error is not set.
|
||||
base_error: The system level error from SSPI or GSSAPI, this must be set if error_code is not set.
|
||||
context_msg: Optional message to provide more context around the error.
|
||||
|
||||
Attributes:
|
||||
base_error (Optional[Union[GSSError, WinError]]): The system level error if one was provided.
|
||||
"""
|
||||
|
||||
# Classes the subclass this type need to provide the following class attribute:
|
||||
#
|
||||
# ERROR_CODE = common ErrorCode value for the exception
|
||||
# _BASE_MESSAGE = common string that explains the error code in the absence of the system error message.
|
||||
#
|
||||
# The following attributes are used to map specific system error codes to the common ErrorCode error.
|
||||
# _GSSAPI_CODE = The GSSAPI major_code from GSSError to map to the common error code
|
||||
# _SSPI_CODE = The winerror value from an WindowsError to map to the common error code
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
error_code: typing.Optional[typing.Union[int, ErrorCode]] = None,
|
||||
base_error: typing.Optional[Exception] = None,
|
||||
context_msg: typing.Optional[str] = None,
|
||||
) -> None:
|
||||
self.base_error = base_error
|
||||
self._error_code = error_code
|
||||
self._context_message = context_msg
|
||||
|
||||
super(SpnegoError, self).__init__(self.message)
|
||||
|
||||
@property
|
||||
def nt_status(self) -> int:
|
||||
"""The Windows NT Status code that represents this error."""
|
||||
codes = getattr(self, "_SSPI_CODE", self._error_code) or 0xFFFFFFFF
|
||||
return codes[0] if isinstance(codes, (list, tuple)) else codes
|
||||
|
||||
@property
|
||||
def message(self) -> str:
|
||||
error_code = self._error_code if self._error_code is not None else 0xFFFFFFFF
|
||||
|
||||
if self.base_error:
|
||||
base_message = str(self.base_error)
|
||||
|
||||
else:
|
||||
base_message = getattr(self, "_BASE_MESSAGE", "Unknown error code")
|
||||
|
||||
msg = "SpnegoError (%d): %s" % (error_code, base_message)
|
||||
if self._context_message:
|
||||
msg += ", Context: %s" % self._context_message
|
||||
|
||||
return msg
|
||||
|
||||
|
||||
class BadMechanismError(SpnegoError):
|
||||
ERROR_CODE = ErrorCode.bad_mech
|
||||
|
||||
_BASE_MESSAGE = "An unsupported mechanism was requested"
|
||||
_GSSAPI_CODE = 65536 # GSS_S_BAD_MECH
|
||||
_SSPI_CODE = -2146893051 # SEC_E_SECPKG_NOT_FOUND
|
||||
|
||||
|
||||
class BadNameError(SpnegoError):
|
||||
ERROR_CODE = ErrorCode.bad_name
|
||||
|
||||
_BASE_MESSAGE = "An invalid name was supplied"
|
||||
_GSSAPI_CODE = 1310722 # GSS_S_BAD_NAME
|
||||
_SSPI_CODE = -2146893053 # SEC_E_TARGET_UNKNOWN
|
||||
|
||||
|
||||
class BadBindingsError(SpnegoError):
|
||||
ERROR_CODE = ErrorCode.bad_bindings
|
||||
|
||||
_BASE_MESSAGE = "Invalid channel bindings"
|
||||
_GSSAPI_CODE = 262144 # GSS_BAD_BINDINGS
|
||||
_SSPI_CODE = -2146892986 # SEC_E_BAD_BINDINGS
|
||||
|
||||
|
||||
class BadMICError(SpnegoError):
|
||||
ERROR_CODE = ErrorCode.bad_mic
|
||||
|
||||
_BASE_MESSAGE = "A token had an invalid Message Integrity Check (MIC)"
|
||||
_GSSAPI_CODE = 3932166 # GSS_BAD_MIC
|
||||
_SSPI_CODE = -2146893041 # SEC_E_MESSAGE_ALTERED
|
||||
|
||||
|
||||
class NoCredentialError(SpnegoError):
|
||||
ERROR_CODE = ErrorCode.no_cred
|
||||
|
||||
_BASE_MESSAGE = "No credentials were supplied, or the credentials were unavailable or inaccessible"
|
||||
_GSSAPI_CODE = 458752 # GSS_NO_CRED
|
||||
_SSPI_CODE = -2146893042 # SEC_E_NO_CREDENTIALS
|
||||
|
||||
|
||||
class NoContextError(SpnegoError):
|
||||
ERROR_CODE = ErrorCode.no_context
|
||||
|
||||
_BASE_MESSAGE = "No context has been established, or invalid handled passed in"
|
||||
_GSSAPI_CODE = 524288 # GSS_S_NO_CONTEXT
|
||||
_SSPI_CODE = -2146893055 # SEC_E_INVALID_HANDLE
|
||||
|
||||
|
||||
class InvalidTokenError(SpnegoError):
|
||||
ERROR_CODE = ErrorCode.invalid_token
|
||||
|
||||
_BASE_MESSAGE = "A token was invalid, or the logon was denied"
|
||||
_GSSAPI_CODE = 589824 # GSS_S_DEFECTIVE_TOKEN
|
||||
_SSPI_CODE = [-2146893044, -2146893048] # SEC_E_LOGON_DENIED, SEC_E_INVALID_TOKEN
|
||||
|
||||
|
||||
class InvalidCredentialError(SpnegoError):
|
||||
ERROR_CODE = ErrorCode.invalid_credential
|
||||
|
||||
_BASE_MESSAGE = "A credential was invalid"
|
||||
_GSSAPI_CODE = 655360 # GSS_S_DEFECTIVE_CREDENTIAL
|
||||
_SSPI_CODE = -1073741715 # STATUS_LOGON_FAILURE
|
||||
|
||||
|
||||
class CredentialsExpiredError(SpnegoError):
|
||||
ERROR_CODE = ErrorCode.credentials_expired
|
||||
|
||||
_BASE_MESSAGE = "The referenced credentials have expired"
|
||||
_GSSAPI_CODE = 720896 # * GSS_S_CREDENTIALS_EXPIRED
|
||||
_SSPI_CODE = -1073741711 # STATUS_PASSWORD_EXPIRED
|
||||
|
||||
|
||||
class ContextExpiredError(SpnegoError):
|
||||
ERROR_CODE = ErrorCode.context_expired
|
||||
|
||||
_BASE_MESSAGE = "Security context has expired"
|
||||
_GSSAPI_CODE = 786432 # GSS_S_CONTEXT_EXPIRED
|
||||
_SSPI_CODE = -2146893033 # SEC_E_CONTEXT_EXPIRED
|
||||
|
||||
|
||||
class UnsupportedQop(SpnegoError):
|
||||
ERROR_CODE = ErrorCode.bad_qop
|
||||
|
||||
_BASE_MESSAGE = "The quality-of-protection requested could not be provided"
|
||||
_GSSAPI_CODE = 917504 # GSS_S_BAD_QOP
|
||||
_SSPI_CODE = -2146893046 # SEC_E_QOP_NOT_SUPPORTED
|
||||
|
||||
|
||||
class OperationNotAvailableError(SpnegoError):
|
||||
ERROR_CODE = ErrorCode.unavailable
|
||||
|
||||
_BASE_MESSAGE = "Operation not supported or available"
|
||||
_GSSAPI_CODE = 1048576 # GSS_S_UNAVAILABLE
|
||||
_SSPI_CODE = -2146893054 # SEC_E_UNSUPPORTED_FUNCTION
|
||||
9
env/lib/python3.12/site-packages/spnego/gss.py
vendored
Normal file
9
env/lib/python3.12/site-packages/spnego/gss.py
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright: (c) 2021, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import warnings
|
||||
|
||||
from spnego._gss import *
|
||||
|
||||
warnings.warn("spnego.gss is deprecated and will be removed in a future release.", DeprecationWarning)
|
||||
58
env/lib/python3.12/site-packages/spnego/iov.py
vendored
Normal file
58
env/lib/python3.12/site-packages/spnego/iov.py
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import enum
|
||||
import typing
|
||||
|
||||
|
||||
class BufferType(enum.IntEnum):
|
||||
"""Buffer types to use for an IOVBuffer type.
|
||||
|
||||
These are the IOVBuffer type flags that can be set for an IOVBuffer. The keys are a generified name for the
|
||||
respective SSPI and GSSAPI flags.
|
||||
"""
|
||||
|
||||
empty = 0 # SECBUFFER_EMPTY | GSS_IOV_BUFFER_TYPE_EMPTY
|
||||
data = 1 # SECBUFFER_DATA | GSS_IOV_BUFFER_TYPE_DATA
|
||||
header = 2 # SECBUFFER_TOKEN | GSS_IOV_BUFFER_TYPE_HEADER
|
||||
pkg_params = 3 # SECBUFFER_PKG_PARAMS | GSS_IOV_BUFFER_TYPE_MECH_PARAMS
|
||||
trailer = 7 # SECBUFFER_STREAM_HEADER | GSS_IOV_BUFFER_TYPE_TRAILER
|
||||
padding = 9 # SECBUFFER_PADDING | GSS_IOV_BUFFER_TYPE_PADDING
|
||||
stream = 10 # SECBUFFER_STREAM | GSS_IOV_BUFFER_TYPE_STREAM
|
||||
sign_only = 11 # (SECBUFFER_DATA | SECBUFFER_READONLY_WITH_CHECKSUM) | GSS_IOV_BUFFER_TYPE_SIGN_ONLY
|
||||
mic_token = 12 # SECBUFFER_MECHLIST_SIGNATURE | GSS_IOV_BUFFER_TYPE_MIC_TOKEN
|
||||
|
||||
# This doesn't have an equivalent in GSSAPI but is mapped internally to
|
||||
# the SSPI data + readonly buffer. Luckily GSSAPI seems to treat an empty
|
||||
# buffer as the same as SSPI so that will be used there.
|
||||
data_readonly = 4096 # (SECBUFFER_DATA | SECBUFFER_READONLY) | GSS_IOV_BUFFER_TYPE_EMPTY
|
||||
|
||||
|
||||
class IOVBuffer(typing.NamedTuple):
|
||||
"""A buffer to pass as a list to :meth:`wrap_iov()`.
|
||||
|
||||
Defines the buffer inside a list that is passed to :meth:`wrap_iov()`. A list of these buffers are also returned in
|
||||
the `IOVUnwrapResult` under the `buffers` attribute.
|
||||
|
||||
On SSPI only a buffer of the type `header`, `trailer`, or `padding` can be auto allocated. On GSSAPI all buffers
|
||||
can be auto allocated when `data=True` but the behaviour behind this is dependent on the mech it is run for.
|
||||
|
||||
On the output from the `*_iov` functions the data is the bytes buffer or `None` if the buffer wasn't set. When used
|
||||
as an input to the `*_iov` functions the data can be the buffer bytes, the length of buffer to allocate or a bool
|
||||
to state whether the buffer is auto allocated or not.
|
||||
"""
|
||||
|
||||
type: BufferType #: The type of IOV buffer
|
||||
data: typing.Optional[typing.Union[bytes, int, bool]] #: The IOV buffer type.
|
||||
|
||||
|
||||
class IOVResBuffer(typing.NamedTuple):
|
||||
"""Results of an IOV operation.
|
||||
|
||||
Unlike :class:`IOVBuffer` this limits the value of `data` to just an
|
||||
optionally set bytes. It is used as the return value of an IOV operation to
|
||||
better match what the expected values would be.
|
||||
"""
|
||||
|
||||
type: BufferType
|
||||
data: typing.Optional[bytes]
|
||||
9
env/lib/python3.12/site-packages/spnego/negotiate.py
vendored
Normal file
9
env/lib/python3.12/site-packages/spnego/negotiate.py
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright: (c) 2021, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import warnings
|
||||
|
||||
from spnego._negotiate import *
|
||||
|
||||
warnings.warn("spnego.negotiate is deprecated and will be removed in a future release.", DeprecationWarning)
|
||||
9
env/lib/python3.12/site-packages/spnego/ntlm.py
vendored
Normal file
9
env/lib/python3.12/site-packages/spnego/ntlm.py
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright: (c) 2021, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import warnings
|
||||
|
||||
from spnego._ntlm import *
|
||||
|
||||
warnings.warn("spnego.ntlm is deprecated and will be removed in a future release.", DeprecationWarning)
|
||||
0
env/lib/python3.12/site-packages/spnego/py.typed
vendored
Normal file
0
env/lib/python3.12/site-packages/spnego/py.typed
vendored
Normal file
9
env/lib/python3.12/site-packages/spnego/sspi.py
vendored
Normal file
9
env/lib/python3.12/site-packages/spnego/sspi.py
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright: (c) 2021, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import warnings
|
||||
|
||||
from spnego._sspi import *
|
||||
|
||||
warnings.warn("spnego.sspi is deprecated and will be removed in a future release.", DeprecationWarning)
|
||||
172
env/lib/python3.12/site-packages/spnego/tls.py
vendored
Normal file
172
env/lib/python3.12/site-packages/spnego/tls.py
vendored
Normal file
@@ -0,0 +1,172 @@
|
||||
# Copyright: (c) 2021, Jordan Borean (@jborean93) <jborean93@gmail.com>
|
||||
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
|
||||
|
||||
import dataclasses
|
||||
import datetime
|
||||
import platform
|
||||
import ssl
|
||||
import typing
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class CredSSPTLSContext:
|
||||
"""A TLS context generated for CredSSP.
|
||||
|
||||
This is the SSLContext object used by both an initiator and acceptor of
|
||||
CredSSP authentication. It allows the caller to finely control the SSL/TLS
|
||||
options used during the CredSSP authentication phase, e.g. selecting
|
||||
min/max protocol versions, specific cipher suites, etc.
|
||||
|
||||
The public_key attribute is used for acceptor CredSSP contexts as the
|
||||
DER encoded public key loaded in the SSLContext. Here is an example of
|
||||
generating and loading a X509 certificate for an acceptor context:
|
||||
|
||||
ctx = spnego.tls.default_tls_context()
|
||||
cert_pem, key_Pem, pub_key = spnego.tls.generate_tls_certificate()
|
||||
|
||||
# Cannot use tempfile.NamedTemporaryFile due to sharing violations on
|
||||
# Windows. Use a tempdir as a workaround.
|
||||
temp_dir = tempfile.mkdtemp()
|
||||
try:
|
||||
cert_path = os.path.join(tmpe_dir, 'ca.pem')
|
||||
with open(cert_path, mode'wb') as fd:
|
||||
fd.write(cert_pem)
|
||||
fd.write(key_pem)
|
||||
|
||||
ctx.context.load_cert_chain(cert_path)
|
||||
ctx.public_key = pub_key
|
||||
|
||||
finally:
|
||||
shutil.rmtree(temp_dir)
|
||||
|
||||
This context is then passed in through the `credssp_tls_context` kwarg of
|
||||
:meth:`spnego.client` or :meth:`spnego.server`.
|
||||
|
||||
Attributes:
|
||||
context (ssl.SSLContext): The TLS context generated for CredSSP.
|
||||
public_key (Optional[bytes]): When generating the TLS context for an
|
||||
acceptor this is the public key bytes for the generated cert in the
|
||||
TLS context.
|
||||
"""
|
||||
|
||||
context: ssl.SSLContext
|
||||
public_key: typing.Optional[bytes] = None
|
||||
|
||||
|
||||
def default_tls_context(
|
||||
usage: str = "initiate",
|
||||
) -> CredSSPTLSContext:
|
||||
"""CredSSP TLSContext with sane defaults.
|
||||
|
||||
Creates the TLS context used to generate the SSL object for CredSSP
|
||||
authentication. By default the TLS context will set the minimum protocol to
|
||||
TLSv1.2. Certificate verification is also disabled for both the initiator
|
||||
and acceptor as per the `MS-CSSP Events and Sequencing Rules`_ in step 1.
|
||||
This can be used as a base context where the caller applies further changes
|
||||
based on their requirements such as cert validation and so forth.
|
||||
|
||||
This context is then passed in through the `credssp_tls_context` kwarg of
|
||||
:meth:`spnego.client` or :meth:`spnego.server`.
|
||||
|
||||
Args:
|
||||
usage: Either `initiate` for a client context or `accept` for a server context.
|
||||
|
||||
Returns:
|
||||
TLSContext: The TLS context that can be used with CredSSP auth.
|
||||
|
||||
.. _MS-CSSP Events and Sequencing Rules:
|
||||
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cssp/385a7489-d46b-464c-b224-f7340e308a5c
|
||||
"""
|
||||
if usage == "initiate":
|
||||
# TLS_CLIENT enables CA/CN checking but CredSSP does not use this by default in the docs. The caller can
|
||||
# re-enable this if needed.
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
else:
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
|
||||
# Required to interop with SChannel which does not support compression, TLS padding, and empty fragments
|
||||
# SSL_OP_NO_COMPRESSION | SSL_OP_TLS_BLOCK_PADDING_BUG | SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
|
||||
ctx.options |= ssl.OP_NO_COMPRESSION | 0x00000200 | 0x00000800
|
||||
|
||||
# The minimum_version field requires OpenSSL 1.1.0g or newer, fallback to the deprecated method of setting the
|
||||
# OP_NO_* options.
|
||||
# FUTURE: Remove once Python 3.10 is minimum which requires 1.1.1 or newer
|
||||
tls_version = getattr(ssl, "TLSVersion", None)
|
||||
if hasattr(ctx, "minimum_version") and tls_version:
|
||||
setattr(ctx, "minimum_version", tls_version.TLSv1_2)
|
||||
|
||||
else:
|
||||
ctx.options |= (
|
||||
ssl.Options.OP_NO_SSLv2 | ssl.Options.OP_NO_SSLv3 | ssl.Options.OP_NO_TLSv1 | ssl.Options.OP_NO_TLSv1_1
|
||||
)
|
||||
|
||||
return CredSSPTLSContext(context=ctx)
|
||||
|
||||
|
||||
def generate_tls_certificate() -> typing.Tuple[bytes, bytes, bytes]:
|
||||
"""Generates X509 cert and key for CredSSP acceptor.
|
||||
|
||||
Generates a TLS X509 certificate and key that can be used by a CredSSP
|
||||
acceptor for authentication. This certificate is modelled after the one
|
||||
that the WSMan CredSSP service uses on Windows.
|
||||
|
||||
Returns:
|
||||
Tuple[bytes, bytes, bytes]: The X509 PEM encoded certificate,
|
||||
PEM encoded key, and DER encoded public key.
|
||||
"""
|
||||
key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())
|
||||
|
||||
# socket.getfqdn() can block for a few seconds if DNS is not set up properly.
|
||||
# The name also has a max length of 64 characters.
|
||||
cn_name = f"CREDSSP-{platform.node()}"[:64]
|
||||
name = x509.Name([x509.NameAttribute(x509.NameOID.COMMON_NAME, cn_name)])
|
||||
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
cert = (
|
||||
x509.CertificateBuilder()
|
||||
.subject_name(name)
|
||||
.issuer_name(name)
|
||||
.public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now)
|
||||
.not_valid_after(now + datetime.timedelta(days=365))
|
||||
.sign(key, hashes.SHA256(), default_backend())
|
||||
)
|
||||
cert_pem = cert.public_bytes(encoding=serialization.Encoding.PEM)
|
||||
key_pem = key.private_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PrivateFormat.TraditionalOpenSSL,
|
||||
encryption_algorithm=serialization.NoEncryption(),
|
||||
)
|
||||
public_key = cert.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.PKCS1)
|
||||
|
||||
return cert_pem, key_pem, public_key
|
||||
|
||||
|
||||
def get_certificate_public_key(
|
||||
data: bytes,
|
||||
) -> bytes:
|
||||
"""Public key bytes of an X.509 Certificate.
|
||||
|
||||
Gets the public key bytes used by CredSSP of the provided X.509
|
||||
certificate. Use this for the `public_key` attribute of
|
||||
class:`CredSSPTLSContext` for an acceptor context when providing your own
|
||||
certificate.
|
||||
|
||||
Args:
|
||||
data: The DER encoded bytes of the X.509 certificate.
|
||||
|
||||
Returns:
|
||||
bytes: The public key bytes of the certificate.
|
||||
"""
|
||||
cert = x509.load_der_x509_certificate(data, default_backend())
|
||||
public_key = cert.public_key()
|
||||
|
||||
return public_key.public_bytes(serialization.Encoding.DER, serialization.PublicFormat.PKCS1)
|
||||
Reference in New Issue
Block a user