From f524ea9a5fc719e4ce03389ad9767408c3cc735a Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Wed, 12 Aug 2026 23:20:34 +0200 Subject: [PATCH 01/10] Add a PKINIT client implementing RFC 4556, RFC 5349 and RFC 4557 --- examples/getTGT.py | 72 +- impacket/krb5/asn1.py | 102 ++- impacket/krb5/constants.py | 5 +- impacket/krb5/kerberosv5.py | 7 +- impacket/krb5/pkinit.py | 1265 +++++++++++++++++++++++++++++++++++ tests/misc/test_pkinit.py | 1136 +++++++++++++++++++++++++++++++ 6 files changed, 2577 insertions(+), 10 deletions(-) create mode 100644 impacket/krb5/pkinit.py create mode 100644 tests/misc/test_pkinit.py diff --git a/examples/getTGT.py b/examples/getTGT.py index 67ed43978e..2c786b323f 100755 --- a/examples/getTGT.py +++ b/examples/getTGT.py @@ -10,10 +10,11 @@ # for more information. # # Description: -# Given a password, hash or aesKey, it will request a TGT and save it as ccache +# Given a password, hash, aesKey or certificate, it will request a TGT and save it as ccache # # Examples: # ./getTGT.py -hashes lm:nt contoso.com/user +# ./getTGT.py -cert-pfx user.pfx contoso.com/user # # Author: # Alberto Solino (@agsolino) @@ -29,11 +30,34 @@ from impacket.examples.utils import parse_identity from impacket.krb5.kerberosv5 import getKerberosTGT from impacket.krb5 import constants +from impacket.krb5.pkinit import DH_GROUPS, EC_CURVES, PKINITCredentials, readPEMCertificates from impacket.krb5.types import Principal class GETTGT: - def __init__(self, target, password, domain, options): + @staticmethod + def loadCertificate(options): + """Build the PKINIT credentials out of the certificate options, if any.""" + if options.cert_pfx is None and options.cert_pem is None: + return None + + trustedCAs = [] + if options.ca_cert is not None: + with open(options.ca_cert, 'rb') as fd: + trustedCAs = readPEMCertificates(fd.read()) + + settings = {'keyExchange': options.key_exchange, 'dhGroup': options.dh_group, 'curve': options.curve, + 'trustedCAs': trustedCAs, 'verifyKDC': not options.no_verify_kdc, + 'requestOCSP': options.request_ocsp, 'requireOCSP': options.require_ocsp} + + if options.cert_pfx is not None: + return PKINITCredentials.fromPFX(options.cert_pfx, options.pfx_pass, **settings) + if options.key_pem is None: + logging.critical('-key-pem is required along with -cert-pem!') + sys.exit(1) + return PKINITCredentials.fromPEM(options.cert_pem, options.key_pem, options.pfx_pass, **settings) + + def __init__(self, target, password, domain, options, certificate=None): self.__password = password self.__user= target self.__domain = domain @@ -43,6 +67,7 @@ def __init__(self, target, password, domain, options): self.__options = options self.__kdcHost = options.dc_ip self.__service = options.service + self.__certificate = certificate if options.hashes is not None: self.__lmhash, self.__nthash = options.hashes.split(':') @@ -63,7 +88,8 @@ def run(self): nthash = unhexlify(self.__nthash), aesKey = self.__aesKey, kdcHost = self.__kdcHost, - serverName = self.__service) + serverName = self.__service, + certificate = self.__certificate) self.saveTicket(tgt,oldSessionKey) if __name__ == '__main__': @@ -89,29 +115,65 @@ def run(self): group.add_argument('-service', action='store', metavar="SPN", help='Request a Service Ticket directly through an AS-REQ') group.add_argument('-principalType', nargs="?", type=lambda value: constants.PrincipalNameType[value.upper()] if value.upper() in constants.PrincipalNameType.__members__ else None, action='store', default=constants.PrincipalNameType.NT_PRINCIPAL, help='PrincipalType of the token, can be one of NT_UNKNOWN, NT_PRINCIPAL, NT_SRV_INST, NT_SRV_HST, NT_SRV_XHST, NT_UID, NT_SMTP_NAME, NT_ENTERPRISE, NT_WELLKNOWN, NT_SRV_HST_DOMAIN, NT_MS_PRINCIPAL, NT_MS_PRINCIPAL_AND_ID, NT_ENT_PRINCIPAL_AND_ID; default is NT_PRINCIPAL, ') + group = parser.add_argument_group('certificate (PKINIT, RFC 4556)') + + group.add_argument('-cert-pfx', action='store', metavar="FILE", help='Client certificate and private key in PKCS#12 format') + group.add_argument('-pfx-pass', action='store', metavar="PASSWORD", help='Password of the PKCS#12 file') + group.add_argument('-cert-pem', action='store', metavar="FILE", help='Client certificate in PEM format') + group.add_argument('-key-pem', action='store', metavar="FILE", help='Client private key in PEM format') + group.add_argument('-key-exchange', action='store', choices=['dh', 'ecdh', 'rsa'], default='dh', + help='AS reply key delivery method: Diffie-Hellman (default), its elliptic curve variant ' + '(RFC 5349) or public key encryption') + group.add_argument('-dh-group', action='store', type=int, choices=sorted(DH_GROUPS), default=14, + help='MODP group to use for the Diffie-Hellman key agreement, default is 14 (2048 bits)') + group.add_argument('-curve', action='store', choices=sorted(EC_CURVES), default='P-256', + help='Named curve to use for the ECDH key agreement, default is P-256') + group.add_argument('-ca-cert', action='store', metavar="FILE", help='PEM file holding the CA certificates trusted ' + 'to certify the KDC. Without it the KDC certification path is not validated') + group.add_argument('-no-verify-kdc', action='store_true', help='Do not check the KDC certificate at all') + group.add_argument('-request-ocsp', action='store_true', help='Ask the KDC for the OCSP responses of its ' + 'certificates (RFC 4557)') + group.add_argument('-require-ocsp', action='store_true', help='Ask for the OCSP responses and fail if the KDC ' + 'returns no usable one for its certificate. Windows KDCs never do') + if len(sys.argv)==1: parser.print_help() print("\nExamples: ") print("\t./getTGT.py -hashes lm:nt contoso.com/user\n") print("\tit will use the lm:nt hashes for authentication. If you don't specify them, a password will be asked") + print("\t./getTGT.py -cert-pfx user.pfx contoso.com/user\n") + print("\tit will authenticate with the certificate of the PKCS#12 file, through PKINIT") sys.exit(1) options = parser.parse_args() # Init the example's logger theme logger.init(options.ts, options.debug) + certificate = GETTGT.loadCertificate(options) + if certificate is not None: + options.no_pass = True + domain, username, password, _, _, options.k = parse_identity(options.identity, options.hashes, options.no_pass, options.aesKey, options.k) - + if domain is None: logging.critical('Domain should be specified!') sys.exit(1) + if username == '' and certificate is not None: + # Fall back on the identity the certificate is bound to + upn = certificate.getUPN() + if upn is None: + logging.critical('No username given and the certificate holds no UPN!') + sys.exit(1) + username = upn.split('@')[0] + logging.info('Using %s, the UPN of the certificate' % upn) + if options.principalType is None: logging.critical('Invalid principalType!') sys.exit(1) try: - executer = GETTGT(username, password, domain, options) + executer = GETTGT(username, password, domain, options, certificate) executer.run() except Exception as e: if logging.getLogger().level == logging.DEBUG: diff --git a/impacket/krb5/asn1.py b/impacket/krb5/asn1.py index 4363b1236b..54360e7adb 100644 --- a/impacket/krb5/asn1.py +++ b/impacket/krb5/asn1.py @@ -45,6 +45,7 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # from pyasn1.type import tag, namedtype, univ, constraint, char, useful +from pyasn1_modules.rfc5280 import AlgorithmIdentifier, SubjectPublicKeyInfo from . import constants @@ -77,6 +78,18 @@ def _sequence_optional_component(name, tag_value, type, **subkwargs): tag_value), **subkwargs)) +def sequence_implicit_component(name, tag_value, type, **subkwargs): + return namedtype.NamedType(name, type.subtype( + implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, + tag_value), + **subkwargs)) + +def sequence_optional_implicit_component(name, tag_value, type, **subkwargs): + return namedtype.OptionalNamedType(name, type.subtype( + implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, + tag_value), + **subkwargs)) + def seq_set(seq, name, builder=None, *args, **kwargs): component = seq.setComponentByName(name).getComponentByName(name) if builder is not None: @@ -453,10 +466,10 @@ class KRB_ERROR(univ.Sequence): ) class TYPED_DATA(univ.SequenceOf): - componentType = namedtype.NamedTypes( + componentType = univ.Sequence(componentType=namedtype.NamedTypes( _sequence_component('data-type', 0, Int32()), _sequence_optional_component('data-value', 1, univ.OctetString()), - ) + )) class PA_ENC_TIMESTAMP(EncryptedData): pass @@ -556,4 +569,87 @@ class KERB_DMSA_KEY_PACKAGE(univ.Sequence): _sequence_component("effective-time", 2, KerberosTime()), _sequence_optional_component("reserved", 3, univ.OctetString()), _sequence_component("expiration-time", 4, KerberosTime()) - ) \ No newline at end of file + ) + +# RFC 4556 (PKINIT): Every type below is EXPLICIT tagged unless the module marks it IMPLICIT. +class DHNonce(univ.OctetString): + pass + +class ExternalPrincipalIdentifier(univ.Sequence): + componentType = namedtype.NamedTypes( + sequence_optional_implicit_component('subjectName', 0, univ.OctetString()), + sequence_optional_implicit_component('issuerAndSerialNumber', 1, univ.OctetString()), + sequence_optional_implicit_component('subjectKeyIdentifier', 2, univ.OctetString()) + ) + +class TD_TRUSTED_CERTIFIERS(univ.SequenceOf): + componentType = ExternalPrincipalIdentifier() + +class TD_INVALID_CERTIFICATES(univ.SequenceOf): + componentType = ExternalPrincipalIdentifier() + +class AD_INITIAL_VERIFIED_CAS(univ.SequenceOf): + componentType = ExternalPrincipalIdentifier() + +class TD_DH_PARAMETERS(univ.SequenceOf): + componentType = AlgorithmIdentifier() + +class KRB5PrincipalName(univ.Sequence): + componentType = namedtype.NamedTypes( + _sequence_component('realm', 0, Realm()), + _sequence_component('principalName', 1, PrincipalName()) + ) + +class PKAuthenticator(univ.Sequence): + componentType = namedtype.NamedTypes( + _sequence_component('cusec', 0, Microseconds()), + _sequence_component('ctime', 1, KerberosTime()), + _sequence_component('nonce', 2, UInt32()), + _sequence_optional_component('paChecksum', 3, univ.OctetString()) + ) + +class AuthPack(univ.Sequence): + componentType = namedtype.NamedTypes( + _sequence_component('pkAuthenticator', 0, PKAuthenticator()), + _sequence_optional_component('clientPublicValue', 1, SubjectPublicKeyInfo()), + _sequence_optional_component('supportedCMSTypes', 2, + univ.SequenceOf(componentType=AlgorithmIdentifier())), + _sequence_optional_component('clientDHNonce', 3, DHNonce()) + ) + +class PA_PK_AS_REQ(univ.Sequence): + componentType = namedtype.NamedTypes( + sequence_implicit_component('signedAuthPack', 0, univ.OctetString()), + _sequence_optional_component('trustedCertifiers', 1, + univ.SequenceOf(componentType=ExternalPrincipalIdentifier())), + sequence_optional_implicit_component('kdcPkId', 2, univ.OctetString()) + ) + +class DHRepInfo(univ.Sequence): + componentType = namedtype.NamedTypes( + sequence_implicit_component('dhSignedData', 0, univ.OctetString()), + _sequence_optional_component('serverDHNonce', 1, DHNonce()) + ) + +class PA_PK_AS_REP(univ.Choice): + componentType = namedtype.NamedTypes( + _sequence_component('dhInfo', 0, DHRepInfo()), + sequence_implicit_component('encKeyPack', 1, univ.OctetString()) + ) + +class KDCDHKeyInfo(univ.Sequence): + componentType = namedtype.NamedTypes( + _sequence_component('subjectPublicKey', 0, univ.BitString()), + _sequence_component('nonce', 1, UInt32()), + _sequence_optional_component('dhKeyExpiration', 2, KerberosTime()) + ) + +class ReplyKeyPack(univ.Sequence): + componentType = namedtype.NamedTypes( + _sequence_component('replyKey', 0, EncryptionKey()), + _sequence_component('asChecksum', 1, Checksum()) + ) + +# RFC 4557 (OCSP support for PKINIT): Each OcspResponse is a complete DER encoded OCSP response. +class PKOcspData(univ.SequenceOf): + componentType = univ.OctetString() diff --git a/impacket/krb5/constants.py b/impacket/krb5/constants.py index a272295be1..d455e33431 100644 --- a/impacket/krb5/constants.py +++ b/impacket/krb5/constants.py @@ -84,6 +84,7 @@ class PreAuthenticationDataTypes(Enum): PA_PK_AS_REP_OLD = 15 PA_PK_AS_REQ = 16 PA_PK_AS_REP = 17 + PA_PK_OCSP_RESPONSE = 18 PA_ETYPE_INFO2 = 19 PA_USE_SPECIFIED_KVNO = 20 PA_SAM_REDIRECT = 21 @@ -102,6 +103,7 @@ class PreAuthenticationDataTypes(Enum): TD_APP_DEFINED_ERROR = 106 TD_REQ_NONCE = 107 TD_REQ_SEQ = 108 + TD_DH_PARAMETERS = 109 PA_PAC_REQUEST = 128 PA_FOR_USER = 129 PA_S4U_X509_USER = 130 @@ -141,7 +143,8 @@ class AuthorizationDataType(Enum): AD_MANDATORY_TICKET_EXTENSIONS = 6 AD_IN_TICKET_EXTENSIONS = 7 AD_MANDATORY_FOR_KDC = 8 - #Reserved values = 9-63 + AD_INITIAL_VERIFIED_CAS = 9 # RFC 4556 + #Reserved values = 10-63 OSF_DCE = 64 SESAME = 65 AD_OSF_DCE_PKI_CERTID = 66 diff --git a/impacket/krb5/kerberosv5.py b/impacket/krb5/kerberosv5.py index e5ce8a75e4..2f9c62827e 100644 --- a/impacket/krb5/kerberosv5.py +++ b/impacket/krb5/kerberosv5.py @@ -126,7 +126,12 @@ def sendReceive(data, host, kdcHost, port=88, timeout=None): return r -def getKerberosTGT(clientName, password, domain, lmhash, nthash, aesKey='', kdcHost=None, requestPAC=True, serverName=None, kerberoast_no_preauth=False, timeout=None): +def getKerberosTGT(clientName, password, domain, lmhash, nthash, aesKey='', kdcHost=None, requestPAC=True, serverName=None, kerberoast_no_preauth=False, timeout=None, certificate=None): + + if certificate is not None: + # PKINIT : the reply key comes from the certificate exchange, there is no long term key involved + from impacket.krb5.pkinit import getKerberosTGTPKINIT + return getKerberosTGTPKINIT(clientName, domain, certificate, kdcHost=kdcHost, requestPAC=requestPAC, serverName=serverName, timeout=timeout) # Convert to binary form, just in case we're receiving strings if isinstance(lmhash, str): diff --git a/impacket/krb5/pkinit.py b/impacket/krb5/pkinit.py new file mode 100644 index 0000000000..09901744e1 --- /dev/null +++ b/impacket/krb5/pkinit.py @@ -0,0 +1,1265 @@ +# Impacket - Collection of Python classes for working with network protocols. +# +# Copyright Fortra, LLC and its affiliated companies +# +# All rights reserved. +# +# This software is provided under a slightly modified version +# of the Apache Software License. See the accompanying LICENSE file +# for more information. +# +# Description: +# PKINIT client implementation, as defined by: +# * RFC 4556 - Public Key Cryptography for Initial Authentication in Kerberos +# * RFC 5349 - Elliptic Curve Cryptography (ECC) support for PKINIT +# * RFC 4557 - Online Certificate Status Protocol (OCSP) support for PKINIT +# +# Both AS reply key delivery methods are implemented: the Diffie-Hellman key +# agreement method (RFC 4556 3.2.3.1, MODP and, per RFC 5349, ECDH) and the +# public key encryption method (RFC 4556 3.2.3.2). +# +# The TGT obtained here is a regular TGT: the reply key is derived from the +# certificate exchange itself. +# +# Author: +# Giovanni A. (@azoxlpf) +# +import datetime +import os +from binascii import hexlify +from hashlib import sha1, sha256, sha384, sha512 + +from Cryptodome.Cipher import AES, DES3 +from cryptography import x509 +from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, ed25519, padding, rsa +from cryptography.hazmat.primitives.serialization import pkcs12 +from cryptography.x509 import ocsp +from pyasn1.codec.der import decoder, encoder +from pyasn1.error import PyAsn1Error +from pyasn1.type import tag, univ +from pyasn1_modules import rfc3279, rfc5280, rfc5652 + +from impacket import LOG +from impacket.krb5 import constants +from impacket.krb5.asn1 import AS_REP, AS_REQ, AuthPack, EncASRepPart, KDCDHKeyInfo, KERB_PA_PAC_REQUEST, \ + KRB5PrincipalName, METHOD_DATA, PA_PK_AS_REP, PA_PK_AS_REQ, PKOcspData, ReplyKeyPack, \ + TD_DH_PARAMETERS, TYPED_DATA, seq_set, seq_set_iter +from impacket.krb5.crypto import Cksumtype, Enctype, InvalidChecksum, Key, _enctype_table, verify_checksum +from impacket.krb5.types import KerberosTime, Principal + +# PKINIT object identifiers (RFC 4556, Appendix A) +ID_PKINIT_AUTHDATA = '1.3.6.1.5.2.3.1' +ID_PKINIT_DHKEYDATA = '1.3.6.1.5.2.3.2' +ID_PKINIT_RKEYDATA = '1.3.6.1.5.2.3.3' +ID_PKINIT_KP_CLIENTAUTH = '1.3.6.1.5.2.3.4' +ID_PKINIT_KP_KDC = '1.3.6.1.5.2.3.5' +ID_PKINIT_SAN = '1.3.6.1.5.2.2' + +# Microsoft extensions (RFC 4556 Appendix C), what Windows issues instead of the PKINIT EKU and SAN +ID_MS_KP_SC_LOGON = '1.3.6.1.4.1.311.20.2.2' +ID_MS_SAN_SC_LOGON_UPN = '1.3.6.1.4.1.311.20.2.3' +ID_KP_SERVER_AUTH = '1.3.6.1.5.5.7.3.1' +ID_KP_OCSP_SIGNING = '1.3.6.1.5.5.7.3.9' + +# CMS (RFC 5652) and PKCS#9 object identifiers +ID_DATA = '1.2.840.113549.1.7.1' +ID_SIGNED_DATA = '1.2.840.113549.1.7.2' +ID_ENVELOPED_DATA = '1.2.840.113549.1.7.3' +ID_CONTENT_TYPE = '1.2.840.113549.1.9.3' +ID_MESSAGE_DIGEST = '1.2.840.113549.1.9.4' + +# Algorithm identifiers (RFC 3279, RFC 5349, RFC 3370) +ID_DH_PUBLIC_NUMBER = '1.2.840.10046.2.1' +ID_EC_PUBLIC_KEY = '1.2.840.10045.2.1' +ID_RSA_ENCRYPTION = '1.2.840.113549.1.1.1' +ID_RSAES_OAEP = '1.2.840.113549.1.1.7' +ID_DES_EDE3_CBC = '1.2.840.113549.3.7' +ID_AES128_CBC = '2.16.840.1.101.3.4.1.2' +ID_AES192_CBC = '2.16.840.1.101.3.4.1.22' +ID_AES256_CBC = '2.16.840.1.101.3.4.1.42' + +DIGEST_ALGORITHMS = { + 'sha1': ('1.3.14.3.2.26', '1.2.840.113549.1.1.5', '1.2.840.10045.4.1', sha1, hashes.SHA1), + 'sha256': ('2.16.840.1.101.3.4.2.1', '1.2.840.113549.1.1.11', '1.2.840.10045.4.3.2', sha256, hashes.SHA256), + 'sha384': ('2.16.840.1.101.3.4.2.2', '1.2.840.113549.1.1.12', '1.2.840.10045.4.3.3', sha384, hashes.SHA384), + 'sha512': ('2.16.840.1.101.3.4.2.3', '1.2.840.113549.1.1.13', '1.2.840.10045.4.3.4', sha512, hashes.SHA512), +} + +DIGEST_OIDS = {values[0]: name for name, values in DIGEST_ALGORITHMS.items()} +SIGNATURE_OIDS = {} +for name, values in DIGEST_ALGORITHMS.items(): + SIGNATURE_OIDS[values[1]] = name + SIGNATURE_OIDS[values[2]] = name +SIGNATURE_OIDS[ID_RSA_ENCRYPTION] = None # digest carried by digestAlgorithm + +# MODP groups usable for the Diffie-Hellman key agreement method (RFC 4556 3.2.1), as (prime, generator) +DH_GROUPS = { + 2: (int( + 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF', 16), 2), + 5: (int( + 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05' + '98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB' + '9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF', 16), 2), + 14: (int( + 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05' + '98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB' + '9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718' + '3995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF', 16), 2), + 15: (int( + 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05' + '98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB' + '9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718' + '3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33' + 'A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864' + 'D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E2' + '08E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF', 16), 2), + 16: (int( + 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05' + '98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB' + '9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718' + '3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33' + 'A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864' + 'D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E2' + '08E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7' + '88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8' + 'DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2' + '233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9' + '93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199FFFFFFFFFFFFFFFF', 16), 2), +} + +EC_CURVES = { + 'P-256': ec.SECP256R1, + 'P-384': ec.SECP384R1, + 'P-521': ec.SECP521R1, +} + +EC_CURVE_OIDS = { + '1.2.840.10045.3.1.7': 'P-256', # secp256r1 + '1.3.132.0.34': 'P-384', # secp384r1 + '1.3.132.0.35': 'P-521', # secp521r1 +} + +# Checksum required for the enctype of the reply key, to verify a ReplyKeyPack asChecksum (RFC 4556 3.2.3.2) +CHECKSUM_FOR_ENCTYPE = { + Enctype.DES3: Cksumtype.SHA1_DES3, + Enctype.AES128: Cksumtype.SHA1_AES128, + Enctype.AES256: Cksumtype.SHA1_AES256, + Enctype.RC4: Cksumtype.HMAC_MD5, +} + +KEY_USAGE_AS_REQ_CHECKSUM = 6 + + +class PKINITError(Exception): + pass + + +class KDCCertificateError(PKINITError): + pass + + +# Malformed input does not consistently raise PyAsn1Error: pyasn1 lets plain builtin errors through +PARSE_ERRORS = (PyAsn1Error, x509.InvalidVersion, x509.DuplicateExtension, x509.UnsupportedGeneralNameType, + UnsupportedAlgorithm, KeyError, IndexError, TypeError, ValueError) + + +def decodeASN1(data, asn1Spec, description): + try: + return decoder.decode(data, asn1Spec=asn1Spec)[0] + except PARSE_ERRORS as e: + raise PKINITError('Could not parse the %s the KDC sent: %s' % (description, e)) + + +def readCertificateFields(certificate): + return (certificate.subject.rfc4514_string(), certificate.issuer.public_bytes(), certificate.serial_number, + certificate.public_key(), certificate.signature_hash_algorithm, len(certificate.extensions), + getCertificateValidity(certificate)) + + +def loadCertificate(component, description): + try: + certificate = x509.load_der_x509_certificate(encoder.encode(component)) + readCertificateFields(certificate) + return certificate + except PARSE_ERRORS as e: + raise PKINITError('Could not parse a certificate of the %s: %s' % (description, e)) + + +def getPublicKey(certificate): + try: + return certificate.public_key() + except PARSE_ERRORS as e: + raise PKINITError('Could not read the public key of "%s": %s' % (getCertificateName(certificate), e)) + + +def getCipher(enctype, description): + try: + return _enctype_table[enctype] + except KeyError: + raise PKINITError('The KDC used the unsupported encryption type %d for the %s' % (enctype, description)) + + +def octetstring2key(x, cipher): + """Derive an AS reply key from an octet string, as defined in RFC 4556 3.2.3.1. + + octetstring2key(x) == random-to-key(K-truncate(SHA1(0x00 | x) | SHA1(0x01 | x) | ...)) + """ + seed = b'' + counter = 0 + while len(seed) < cipher.seedsize: + seed += sha1(bytes([counter]) + x).digest() + counter += 1 + return cipher.random_to_key(seed[:cipher.seedsize]) + + +class DiffieHellman: + """MODP Diffie-Hellman key agreement (RFC 4556 3.2.3.1).""" + + def __init__(self, group=14, prime=None, generator=2): + if prime is None: + if group not in DH_GROUPS: + raise PKINITError('Unsupported Diffie-Hellman group %s' % group) + prime, generator = DH_GROUPS[group] + self.group = group + self.prime = prime + self.generator = generator + self.modulusSize = (prime.bit_length() + 7) // 8 + # RFC 4556 3.2.1: the exponent needs at least twice as many bits as the 256 bit reply key + self.privateKey = int.from_bytes(os.urandom(self.modulusSize), 'big') % (prime - 2) + 1 + self.publicKey = pow(generator, self.privateKey, prime) + + def getSharedSecret(self, peerPublicKey): + if peerPublicKey <= 1 or peerPublicKey >= self.prime - 1: + raise PKINITError('KDC returned an invalid Diffie-Hellman public value') + shared = pow(peerPublicKey, self.privateKey, self.prime) + if shared <= 1: + raise PKINITError('Degenerate Diffie-Hellman shared secret') + # RFC 4556 3.2.3.1: DHSharedSecret is padded with leading zeros up to the modulus size + return shared.to_bytes(self.modulusSize, 'big') + + def getSubjectPublicKeyInfo(self): + parameters = rfc3279.DomainParameters() + parameters['p'] = self.prime + parameters['g'] = self.generator + parameters['q'] = (self.prime - 1) // 2 # safe prime + + algorithm = rfc5280.AlgorithmIdentifier() + algorithm['algorithm'] = univ.ObjectIdentifier(ID_DH_PUBLIC_NUMBER) + algorithm['parameters'] = univ.Any(encoder.encode(parameters)) + + publicKeyInfo = rfc5280.SubjectPublicKeyInfo() + publicKeyInfo['algorithm'] = algorithm + # RFC 3279 2.3.3: the public value is the DER encoding of an INTEGER + publicKeyInfo['subjectPublicKey'] = derToBitString(encoder.encode(univ.Integer(self.publicKey))) + return publicKeyInfo + + def getPeerPublicKey(self, bitString): + return int(decodeASN1(bitString.asOctets(), univ.Integer(), 'Diffie-Hellman public value')) + + +class EllipticCurveDiffieHellman: + """ECDH key agreement, as defined in RFC 5349 4.""" + + def __init__(self, curve='P-256'): + if curve not in EC_CURVES: + raise PKINITError('Unsupported elliptic curve %s' % curve) + self.curve = curve + self.privateKey = ec.generate_private_key(EC_CURVES[curve]()) + + def getSharedSecret(self, peerPublicKey): + # RFC 5349 4: the shared secret is the x coordinate of the point, which is what exchange() returns + return self.privateKey.exchange(ec.ECDH(), peerPublicKey) + + def getSubjectPublicKeyInfo(self): + publicKeyInfo = decoder.decode( + self.privateKey.public_key().public_bytes(serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo), + asn1Spec=rfc5280.SubjectPublicKeyInfo())[0] + return publicKeyInfo + + def getPeerPublicKey(self, bitString): + try: + return ec.EllipticCurvePublicKey.from_encoded_point(EC_CURVES[self.curve](), bitString.asOctets()) + except ValueError as e: + raise PKINITError('The KDC returned an invalid %s public value: %s' % (self.curve, e)) + + +def derToBitString(data): + return univ.BitString(hexValue=hexlify(data).decode('ascii')) + + +def getReqBodyBytes(reqBody): + """Return the DER encoding of the KDC-REQ-BODY itself.""" + encoded = encoder.encode(reqBody) + lengthOctet = encoded[1] + if lengthOctet & 0x80: + return encoded[2 + (lengthOctet & 0x7F):] + return encoded[2:] + + +def buildAlgorithmIdentifier(oid, parameters=None): + algorithm = rfc5280.AlgorithmIdentifier() + algorithm['algorithm'] = univ.ObjectIdentifier(oid) + if parameters is not None: + algorithm['parameters'] = univ.Any(parameters) + return algorithm + + +def buildDigestAlgorithm(digest): + oid = DIGEST_ALGORITHMS[digest][0] + # RFC 5754 2: SHA-2 identifiers have absent parameters, SHA-1 ones are commonly emitted with a NULL + if digest == 'sha1': + return buildAlgorithmIdentifier(oid, encoder.encode(univ.Null(''))) + return buildAlgorithmIdentifier(oid) + + +def buildAttribute(oid, value): + attribute = rfc5652.Attribute() + attribute['attrType'] = univ.ObjectIdentifier(oid) + seq_set_iter(attribute, 'attrValues', (univ.Any(value),)) + return attribute + + +def getSignatureAlgorithm(privateKey, digest): + rsaOid, ecdsaOid = DIGEST_ALGORITHMS[digest][1:3] + if isinstance(privateKey, rsa.RSAPrivateKey): + # RFC 3279 2.2.1: the parameters of an RSA signature algorithm are NULL + return buildAlgorithmIdentifier(rsaOid, encoder.encode(univ.Null(''))) + if isinstance(privateKey, ec.EllipticCurvePrivateKey): + # RFC 5758 3.2: ECDSA algorithm identifiers have absent parameters + return buildAlgorithmIdentifier(ecdsaOid) + raise PKINITError('Unsupported private key type %s' % type(privateKey).__name__) + + +def signData(privateKey, data, digest): + hashAlgorithm = DIGEST_ALGORITHMS[digest][4]() + if isinstance(privateKey, rsa.RSAPrivateKey): + return privateKey.sign(data, padding.PKCS1v15(), hashAlgorithm) + if isinstance(privateKey, ec.EllipticCurvePrivateKey): + return privateKey.sign(data, ec.ECDSA(hashAlgorithm)) + raise PKINITError('Unsupported private key type %s' % type(privateKey).__name__) + + +def verifySignature(publicKey, signature, data, digest): + if isinstance(publicKey, ed25519.Ed25519PublicKey): + publicKey.verify(signature, data) + return + verifyRawSignature(publicKey, signature, data, DIGEST_ALGORITHMS[digest][4]()) + + +def verifyRawSignature(publicKey, signature, data, hashAlgorithm): + if isinstance(publicKey, rsa.RSAPublicKey): + publicKey.verify(signature, data, padding.PKCS1v15(), hashAlgorithm) + elif isinstance(publicKey, ec.EllipticCurvePublicKey): + publicKey.verify(signature, data, ec.ECDSA(hashAlgorithm)) + else: + raise PKINITError('Unsupported public key type %s' % type(publicKey).__name__) + + +def buildSignedData(privateKey, certificate, chain, contentType, content, digest): + """Build the CMS ContentInfo/SignedData wrapping content (RFC 4556 3.2.1).""" + digestAlgorithm = buildDigestAlgorithm(digest) + hashFunction = DIGEST_ALGORITHMS[digest][3] + + # Built with the [0] IMPLICIT tag of the SignerInfo, subtyping a filled value would drop its components + signedAttributes = rfc5652.SignedAttributes().subtype( + implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)) + signedAttributes.setComponentByPosition(0, buildAttribute( + ID_CONTENT_TYPE, encoder.encode(univ.ObjectIdentifier(contentType)))) + signedAttributes.setComponentByPosition(1, buildAttribute( + ID_MESSAGE_DIGEST, encoder.encode(univ.OctetString(hashFunction(content).digest())))) + + signerInfo = rfc5652.SignerInfo() + signerInfo['version'] = 1 # issuerAndSerialNumber + signerInfo['sid'] = buildSignerIdentifier(certificate) + signerInfo['digestAlgorithm'] = digestAlgorithm + signerInfo['signedAttrs'] = signedAttributes + signerInfo['signatureAlgorithm'] = getSignatureAlgorithm(privateKey, digest) + signerInfo['signature'] = signData(privateKey, getSignedAttributesBytes(signedAttributes), digest) + + signedData = rfc5652.SignedData() + signedData['version'] = 3 + signedData['digestAlgorithms'].setComponentByPosition(0, digestAlgorithm) + signedData['encapContentInfo']['eContentType'] = univ.ObjectIdentifier(contentType) + signedData['encapContentInfo']['eContent'] = content + signedData['certificates'] = buildCertificateSet([certificate] + list(chain)) + signedData['signerInfos'].setComponentByPosition(0, signerInfo) + + return buildContentInfo(ID_SIGNED_DATA, encoder.encode(signedData)) + + +def buildContentInfo(contentType, content): + contentInfo = rfc5652.ContentInfo() + contentInfo['contentType'] = univ.ObjectIdentifier(contentType) + contentInfo['content'] = univ.Any(content).subtype( + explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0)) + return encoder.encode(contentInfo) + + +def buildSignerIdentifier(certificate): + issuerAndSerial = rfc5652.IssuerAndSerialNumber() + issuerAndSerial['issuer'] = decoder.decode(certificate.issuer.public_bytes(), + asn1Spec=rfc5280.Name())[0] + issuerAndSerial['serialNumber'] = certificate.serial_number + + signerIdentifier = rfc5652.SignerIdentifier() + signerIdentifier['issuerAndSerialNumber'] = issuerAndSerial + return signerIdentifier + + +def buildCertificateSet(certificates): + certificateSet = rfc5652.CertificateSet().subtype( + implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)) + for position, certificate in enumerate(certificates): + choice = rfc5652.CertificateChoices() + choice['certificate'] = decoder.decode(certificate.public_bytes(serialization.Encoding.DER), + asn1Spec=rfc5280.Certificate())[0] + certificateSet.setComponentByPosition(position, choice) + return certificateSet + + +def getSignedAttributesBytes(signedAttributes): + encoded = encoder.encode(signedAttributes) + # Only the identifier octet differs between the stored [0] IMPLICIT encoding and the signed SET OF + return b'\x31' + encoded[1:] + + +def getAttributeValue(signedAttributes, oid): + for attribute in signedAttributes: + if str(attribute['attrType']) == oid and len(attribute['attrValues']): + return attribute['attrValues'][0].asOctets() + return None + + +def parseSignedData(data, expectedContentType): + """Decode a CMS ContentInfo/SignedData and return (content, signerInfo, certificates).""" + contentInfo = decodeASN1(data, rfc5652.ContentInfo(), 'CMS ContentInfo') + if str(contentInfo['contentType']) != ID_SIGNED_DATA: + raise PKINITError('Expected a CMS SignedData, got content type %s' % contentInfo['contentType']) + + signedData = decodeASN1(bytes(contentInfo['content']), rfc5652.SignedData(), 'CMS SignedData') + contentType = str(signedData['encapContentInfo']['eContentType']) + if contentType != expectedContentType: + raise PKINITError('Unexpected eContentType %s, expected %s' % (contentType, expectedContentType)) + + if not signedData['encapContentInfo']['eContent'].hasValue(): + raise PKINITError('The SignedData carries no content') + content = signedData['encapContentInfo']['eContent'].asOctets() + + certificates = [] + if signedData['certificates'].hasValue(): + for choice in signedData['certificates']: + if choice.getName() != 'certificate': + continue + certificates.append(loadCertificate(choice.getComponent(), 'SignedData')) + + if len(signedData['signerInfos']) != 1: + raise PKINITError('Expected a single signerInfo, got %d' % len(signedData['signerInfos'])) + + return content, signedData['signerInfos'][0], certificates + + +def findSignerCertificate(signerInfo, certificates): + signerIdentifier = signerInfo['sid'] + if signerIdentifier.getName() == 'issuerAndSerialNumber': + issuerAndSerial = signerIdentifier.getComponent() + issuer = encoder.encode(issuerAndSerial['issuer']) + serialNumber = int(issuerAndSerial['serialNumber']) + for certificate in certificates: + if certificate.serial_number == serialNumber and certificate.issuer.public_bytes() == issuer: + return certificate + raise PKINITError('The signer certificate is not part of the SignedData') + + keyIdentifier = bytes(signerIdentifier.getComponent()) + for certificate in certificates: + extension = getExtension(certificate, x509.SubjectKeyIdentifier) + if extension is not None and extension.digest == keyIdentifier: + return certificate + raise PKINITError('The signer certificate is not part of the SignedData') + + +def verifySignedData(data, expectedContentType): + """Verify a CMS SignedData signature and return (content, signer certificate, certificates).""" + content, signerInfo, certificates = parseSignedData(data, expectedContentType) + certificate = findSignerCertificate(signerInfo, certificates) + + signatureOid = str(signerInfo['signatureAlgorithm']['algorithm']) + if signatureOid not in SIGNATURE_OIDS: + raise PKINITError('Unsupported signature algorithm %s' % signatureOid) + digest = SIGNATURE_OIDS[signatureOid] + if digest is None: + digestOid = str(signerInfo['digestAlgorithm']['algorithm']) + if digestOid not in DIGEST_OIDS: + raise PKINITError('Unsupported digest algorithm %s' % digestOid) + digest = DIGEST_OIDS[digestOid] + + # RFC 4556 3.2.3.1: signed attributes are mandatory here, so the signature always covers them + if not signerInfo['signedAttrs'].hasValue(): + raise PKINITError('The SignedData carries no signed attributes') + + contentTypeAttribute = getAttributeValue(signerInfo['signedAttrs'], ID_CONTENT_TYPE) + if contentTypeAttribute is None: + raise PKINITError('The content-type signed attribute is missing') + contentType = str(decodeASN1(contentTypeAttribute, univ.ObjectIdentifier(), 'content-type attribute')) + if contentType != expectedContentType: + raise PKINITError('The content-type signed attribute is %s, expected %s' + % (contentType, expectedContentType)) + + messageDigest = getAttributeValue(signerInfo['signedAttrs'], ID_MESSAGE_DIGEST) + if messageDigest is None: + raise PKINITError('The message-digest signed attribute is missing') + messageDigest = decodeASN1(messageDigest, univ.OctetString(), 'message-digest attribute').asOctets() + if messageDigest != DIGEST_ALGORITHMS[digest][3](content).digest(): + raise PKINITError('The message-digest signed attribute does not match the signed content') + + signature = signerInfo['signature'].asOctets() + try: + verifySignature(getPublicKey(certificate), signature, getSignedAttributesBytes(signerInfo['signedAttrs']), + digest) + except InvalidSignature: + raise PKINITError('The signature of "%s" over the SignedData is invalid' + % getCertificateName(certificate)) + return content, certificate, certificates + + +def getCertificateValidity(certificate): + try: + return certificate.not_valid_before_utc, certificate.not_valid_after_utc + except AttributeError: + return (certificate.not_valid_before.replace(tzinfo=datetime.timezone.utc), + certificate.not_valid_after.replace(tzinfo=datetime.timezone.utc)) + + +def getRevocationTime(ocspResponse): + try: + return ocspResponse.revocation_time_utc + except AttributeError: + return ocspResponse.revocation_time + + +def getOCSPValidity(ocspResponse): + try: + return ocspResponse.this_update_utc, ocspResponse.next_update_utc + except AttributeError: + nextUpdate = ocspResponse.next_update + return (ocspResponse.this_update.replace(tzinfo=datetime.timezone.utc), + nextUpdate.replace(tzinfo=datetime.timezone.utc) if nextUpdate is not None else None) + + +def findOCSPResponder(ocspResponse, certificates): + candidates = list(ocspResponse.certificates) + list(certificates) + for candidate in candidates: + if ocspResponse.responder_name is not None and candidate.subject == ocspResponse.responder_name: + return candidate + if ocspResponse.responder_key_hash is not None: + extension = getExtension(candidate, x509.SubjectKeyIdentifier) + if extension is not None and extension.digest == ocspResponse.responder_key_hash: + return candidate + return None + + +def isSignedBy(certificate, issuer): + try: + verifyCertificateSignature(certificate, issuer) + except KDCCertificateError: + return False + return True + + +def verifyOCSPResponse(ocspResponse, certificate, certificates): + """Check that an OCSP response is a fresh, authoritative answer about certificate.""" + candidates = list(ocspResponse.certificates) + list(certificates) + responder = findOCSPResponder(ocspResponse, candidates) + if responder is None: + raise PKINITError('The certificate of the OCSP responder is unknown') + + if ID_KP_OCSP_SIGNING in getExtendedKeyUsage(responder): + authoritative = any(isSignedBy(responder, issuer) and isSignedBy(certificate, issuer) + for issuer in candidates) + else: + authoritative = isSignedBy(certificate, responder) + if not authoritative: + raise PKINITError('The OCSP responder "%s" is not authoritative for "%s"' + % (getCertificateName(responder), getCertificateName(certificate))) + + try: + verifyRawSignature(getPublicKey(responder), ocspResponse.signature, ocspResponse.tbs_response_bytes, + ocspResponse.signature_hash_algorithm) + except (InvalidSignature, PKINITError, ValueError, TypeError) as e: + raise PKINITError('Invalid signature on the OCSP response: %s' % e) + + now = datetime.datetime.now(datetime.timezone.utc) + thisUpdate, nextUpdate = getOCSPValidity(ocspResponse) + if nextUpdate is not None and nextUpdate < now: + raise PKINITError('The OCSP response expired on %s' % nextUpdate) + if thisUpdate > now + datetime.timedelta(minutes=5): + raise PKINITError('The OCSP response is not valid before %s' % thisUpdate) + + +def getExtension(certificate, extensionClass): + """Return an extension of a certificate, or None if it has none of that class.""" + try: + return certificate.extensions.get_extension_for_class(extensionClass).value + except x509.ExtensionNotFound: + return None + except PARSE_ERRORS as e: + raise PKINITError('Could not read the extensions of a certificate: %s' % e) + + +def getExtendedKeyUsage(certificate): + extension = getExtension(certificate, x509.ExtendedKeyUsage) + if extension is None: + return [] + return [usage.dotted_string for usage in extension] + + +def getKeyUsage(certificate): + return getExtension(certificate, x509.KeyUsage) + + +def getOtherNames(certificate, oid): + extension = getExtension(certificate, x509.SubjectAlternativeName) + if extension is None: + return [] + return [name.value for name in extension.get_values_for_type(x509.OtherName) + if name.type_id.dotted_string == oid] + + +def getDNSNames(certificate): + extension = getExtension(certificate, x509.SubjectAlternativeName) + if extension is None: + return [] + return extension.get_values_for_type(x509.DNSName) + + +def getKerberosPrincipals(certificate): + principals = [] + for value in getOtherNames(certificate, ID_PKINIT_SAN): + principalName = decodeASN1(value, KRB5PrincipalName(), 'id-pkinit-san of a certificate') + components = [str(component) for component in principalName['principalName']['name-string']] + principals.append('%s@%s' % ('/'.join(components), principalName['realm'])) + return principals + + +def getUPNs(certificate): + upns = [] + for value in getOtherNames(certificate, ID_MS_SAN_SC_LOGON_UPN): + upns.append(str(decodeASN1(value, None, 'UPN of a certificate'))) + return upns + + +def getCertificateName(certificate): + subject = certificate.subject.rfc4514_string() + if subject: + return subject + for name in getKerberosPrincipals(certificate) + getDNSNames(certificate) + getUPNs(certificate): + return name + return 'serial number %d' % certificate.serial_number + + +def verifyCertificateAuthority(certificate, pathLength): + """Check the RFC 5280 6.1.4 constraints an issuing certificate must satisfy.""" + constraints = getExtension(certificate, x509.BasicConstraints) + if constraints is None: + raise KDCCertificateError('Certificate "%s" signed another certificate without a basicConstraints extension' + % getCertificateName(certificate)) + if not constraints.ca: + raise KDCCertificateError('Certificate "%s" is not a CA but signed another certificate' + % getCertificateName(certificate)) + if constraints.path_length is not None and constraints.path_length < pathLength: + raise KDCCertificateError('Certificate "%s" allows %d intermediate certificates below it, the path has %d' + % (getCertificateName(certificate), constraints.path_length, pathLength)) + keyUsage = getKeyUsage(certificate) + if keyUsage is not None and not keyUsage.key_cert_sign: + raise KDCCertificateError('Certificate "%s" is not allowed to sign certificates by its key usage' + % getCertificateName(certificate)) + + +def verifyCertificateChain(certificate, intermediates, anchors): + """Walk the certification path from certificate up to one of the trust anchors.""" + now = datetime.datetime.now(datetime.timezone.utc) + current = certificate + pathLength = 0 + for _ in range(len(intermediates) + len(anchors) + 1): + notBefore, notAfter = getCertificateValidity(current) + if not notBefore <= now <= notAfter: + raise KDCCertificateError('Certificate "%s" is not valid at this time' % getCertificateName(current)) + + issuers = [anchor for anchor in anchors if anchor.subject == current.issuer] + if issuers: + verifyCertificateAuthority(issuers[0], pathLength) + verifyCertificateSignature(current, issuers[0]) + return + issuers = [intermediate for intermediate in intermediates if intermediate.subject == current.issuer] + if not issuers: + raise KDCCertificateError('Cannot build a certification path for "%s", issuer "%s" is unknown' + % (getCertificateName(current), current.issuer.rfc4514_string())) + verifyCertificateAuthority(issuers[0], pathLength) + verifyCertificateSignature(current, issuers[0]) + current = issuers[0] + pathLength += 1 + raise KDCCertificateError('Certification path for "%s" is looping' % getCertificateName(certificate)) + + +def verifyCertificateSignature(certificate, issuer): + try: + verifyRawSignature(getPublicKey(issuer), certificate.signature, certificate.tbs_certificate_bytes, + certificate.signature_hash_algorithm) + except (InvalidSignature, PKINITError, ValueError, TypeError) as e: + raise KDCCertificateError('Invalid signature on certificate "%s": %s' + % (getCertificateName(certificate), e)) + + +def verifyKDCCertificate(certificate, certificates, realm, anchors=None): + """Apply the KDC certificate checks of RFC 4556 3.2.4.""" + + # RFC 4556 3.2.4: digitalSignature must be asserted, this certificate is what signs the reply + keyUsage = getKeyUsage(certificate) + if keyUsage is not None and not keyUsage.digital_signature: + raise KDCCertificateError('The KDC certificate is not allowed to sign by its key usage') + + expected = 'krbtgt/%s@%s' % (realm.upper(), realm.upper()) + principals = getKerberosPrincipals(certificate) + if principals: + if expected not in principals: + raise KDCCertificateError('The KDC certificate is bound to %s, expected %s' + % (', '.join(principals), expected)) + else: + usages = getExtendedKeyUsage(certificate) + if ID_PKINIT_KP_KDC not in usages and ID_MS_KP_SC_LOGON not in usages and ID_KP_SERVER_AUTH not in usages: + raise KDCCertificateError('The KDC certificate has neither an id-pkinit-san SAN nor a KDC extended key ' + 'usage, it cannot be verified to belong to a KDC of %s' % realm.upper()) + LOG.debug('KDC certificate has no id-pkinit-san SAN, accepted on its extended key usage (%s)' + % ', '.join(usages)) + + if not anchors: + # Without an anchor only the binding between the signature and the reply key is verified + LOG.debug('No trusted CA certificate given, skipping the KDC certification path validation') + return + + intermediates = [candidate for candidate in certificates if candidate != certificate] + verifyCertificateChain(certificate, intermediates, anchors) + + +def decryptEnvelopedData(data, privateKey): + """Decrypt a CMS EnvelopedData addressed to privateKey (RFC 4556 3.2.3.2).""" + contentInfo = decodeASN1(data, rfc5652.ContentInfo(), 'CMS ContentInfo') + if str(contentInfo['contentType']) != ID_ENVELOPED_DATA: + raise PKINITError('Expected a CMS EnvelopedData, got content type %s' % contentInfo['contentType']) + + envelopedData = decodeASN1(bytes(contentInfo['content']), rfc5652.EnvelopedData(), 'CMS EnvelopedData') + if len(envelopedData['recipientInfos']) != 1: + raise PKINITError('Expected a single recipientInfo, got %d' % len(envelopedData['recipientInfos'])) + if envelopedData['recipientInfos'][0].getName() != 'ktri': + raise PKINITError('The EnvelopedData does not hold a KeyTransRecipientInfo') + recipientInfo = envelopedData['recipientInfos'][0].getComponent() + + if not isinstance(privateKey, rsa.RSAPrivateKey): + raise PKINITError('The public key encryption method requires an RSA private key') + + keyEncryptionOid = str(recipientInfo['keyEncryptionAlgorithm']['algorithm']) + if keyEncryptionOid == ID_RSA_ENCRYPTION: + keyPadding = padding.PKCS1v15() + elif keyEncryptionOid == ID_RSAES_OAEP: + keyPadding = padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None) + else: + raise PKINITError('Unsupported key transport algorithm %s' % keyEncryptionOid) + + try: + contentEncryptionKey = privateKey.decrypt(recipientInfo['encryptedKey'].asOctets(), keyPadding) + except ValueError as e: + raise PKINITError('Could not decrypt the content encryption key with our private key: %s' % e) + + encryptedContentInfo = envelopedData['encryptedContentInfo'] + algorithm = encryptedContentInfo['contentEncryptionAlgorithm'] + initializationVector = decodeASN1(bytes(algorithm['parameters']), univ.OctetString(), + 'content encryption parameters').asOctets() + if not encryptedContentInfo['encryptedContent'].hasValue(): + raise PKINITError('The EnvelopedData carries no encrypted content') + encryptedContent = encryptedContentInfo['encryptedContent'].asOctets() + + contentEncryptionOid = str(algorithm['algorithm']) + if contentEncryptionOid not in (ID_DES_EDE3_CBC, ID_AES128_CBC, ID_AES192_CBC, ID_AES256_CBC): + raise PKINITError('Unsupported content encryption algorithm %s' % contentEncryptionOid) + + # Key, IV and content length all come from the KDC, a mismatch with the announced algorithm is its fault + try: + if contentEncryptionOid == ID_DES_EDE3_CBC: + cipher = DES3.new(contentEncryptionKey, DES3.MODE_CBC, initializationVector) + else: + cipher = AES.new(contentEncryptionKey, AES.MODE_CBC, initializationVector) + content = cipher.decrypt(encryptedContent) + except ValueError as e: + raise PKINITError('Could not decrypt the enveloped content: %s' % e) + + if not content: + raise PKINITError('The enveloped content is empty') + paddingLength = content[-1] + if paddingLength < 1 or paddingLength > len(content): + raise PKINITError('Invalid padding in the encrypted content') + return content[:-paddingLength] + + +class PKINITCredentials: + """A client certificate and its private key, used to authenticate through PKINIT. + + keyExchange selects the AS reply key delivery method: 'dh' for the MODP + Diffie-Hellman method (RFC 4556 3.2.3.1), 'ecdh' for its elliptic curve + variant (RFC 5349) and 'rsa' for the public key encryption method + (RFC 4556 3.2.3.2). + """ + + def __init__(self, privateKey, certificate, chain=None, keyExchange='dh', dhGroup=14, curve='P-256', + digest='sha256', trustedCAs=None, verifyKDC=True, requestOCSP=False, requireOCSP=False): + if keyExchange not in ('dh', 'ecdh', 'rsa'): + raise PKINITError('Unknown key exchange method %s' % keyExchange) + if digest not in DIGEST_ALGORITHMS: + raise PKINITError('Unknown digest algorithm %s' % digest) + + self.privateKey = privateKey + self.certificate = certificate + # RFC 4556 3.2.1: the certificates field must not carry root CA certificates + self.chain = [candidate for candidate in (chain or []) if candidate.subject != candidate.issuer] + self.keyExchange = keyExchange + self.dhGroup = dhGroup + self.curve = curve + self.digest = digest + self.trustedCAs = trustedCAs or [] + self.verifyKDC = verifyKDC + # RFC 4557 3: requiring a response only makes sense if one is asked for + self.requestOCSP = requestOCSP or requireOCSP + self.requireOCSP = requireOCSP + + @classmethod + def fromPFX(cls, pfxFile, password=None, **kwargs): + with open(pfxFile, 'rb') as fd: + data = fd.read() + return cls.fromPFXData(data, password, source='the PFX file %s' % pfxFile, **kwargs) + + @classmethod + def fromPFXData(cls, data, password=None, source='the PFX data', **kwargs): + """Load a PKCS#12 from memory, for callers holding it as bytes rather than a file.""" + if isinstance(password, str): + password = password.encode('utf-8') + try: + privateKey, certificate, chain = pkcs12.load_key_and_certificates(data, password or None) + except ValueError as e: + raise PKINITError('Could not load %s: %s. Certificates encrypted with legacy algorithms must be ' + 'converted first, e.g. openssl pkcs12 -in old.pfx -out new.pfx -legacy' % (source, e)) + if privateKey is None or certificate is None: + raise PKINITError('%s does not hold both a certificate and its private key' % source.capitalize()) + return cls(privateKey, certificate, chain, **kwargs) + + @classmethod + def fromPEM(cls, certFile, keyFile, password=None, **kwargs): + with open(certFile, 'rb') as fd: + certificateData = fd.read() + with open(keyFile, 'rb') as fd: + keyData = fd.read() + return cls.fromPEMData(certificateData, keyData, password, source='%s and %s' % (certFile, keyFile), **kwargs) + + @classmethod + def fromPEMData(cls, certificateData, keyData, password=None, source='the PEM data', **kwargs): + """Load a PEM certificate and its key from memory.""" + certificates = readPEMCertificates(certificateData) + if not certificates: + raise PKINITError('No certificate found in %s' % source) + if isinstance(password, str): + password = password.encode('utf-8') + try: + privateKey = serialization.load_pem_private_key(keyData, password or None) + except (TypeError, ValueError) as e: + raise PKINITError('Could not load the private key of %s: %s' % (source, e)) + return cls(privateKey, certificates[0], certificates[1:], **kwargs) + + def getUPN(self): + upns = getUPNs(self.certificate) + return upns[0] if upns else None + + def getPrincipal(self): + """Return the identity the certificate is bound to, as principal@realm.""" + principals = getKerberosPrincipals(self.certificate) + if principals: + return principals[0] + return self.getUPN() + + +def readPEMCertificates(data): + certificates = [] + marker = b'-----BEGIN CERTIFICATE-----' + while marker in data: + start = data.index(marker) + end = data.index(b'-----END CERTIFICATE-----', start) + len(b'-----END CERTIFICATE-----') + certificates.append(x509.load_pem_x509_certificate(data[start:end])) + data = data[end:] + return certificates + + +class PKINIT: + """Request a TGT with a certificate, as defined in RFC 4556.""" + + def __init__(self, clientName, domain, credentials, kdcHost=None, requestPAC=True, serverName=None, + supportedCiphers=None, timeout=None): + self.clientName = clientName + self.domain = domain.upper() + self.credentials = credentials + self.kdcHost = kdcHost + self.requestPAC = requestPAC + self.serverName = serverName + self.timeout = timeout + self.supportedCiphers = supportedCiphers or ( + int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value), + int(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value), + int(constants.EncryptionTypes.rc4_hmac.value), + ) + self.digest = credentials.digest + self.keyExchange = None + self.nonce = 0 + self.asReq = b'' + self.ocspResponses = [] + + def newKeyExchange(self): + if self.credentials.keyExchange == 'dh': + return DiffieHellman(self.credentials.dhGroup) + if self.credentials.keyExchange == 'ecdh': + return EllipticCurveDiffieHellman(self.credentials.curve) + return None + + def buildAuthPack(self, reqBody): + authPack = AuthPack() + pkAuthenticator = authPack['pkAuthenticator'] + now = datetime.datetime.now(datetime.timezone.utc) + pkAuthenticator['cusec'] = now.microsecond + pkAuthenticator['ctime'] = KerberosTime.to_asn1(now) + # Windows KDCs echo this nonce back as the AS-REP nonce, so it must match the KDC-REQ-BODY one + pkAuthenticator['nonce'] = self.nonce + pkAuthenticator['paChecksum'] = sha1(getReqBodyBytes(reqBody)).digest() + + if self.keyExchange is not None: + publicKeyInfo = self.keyExchange.getSubjectPublicKeyInfo() + clientPublicValue = authPack['clientPublicValue'] + clientPublicValue['algorithm'] = publicKeyInfo['algorithm'] + clientPublicValue['subjectPublicKey'] = publicKeyInfo['subjectPublicKey'] + + digests = [self.digest] + [name for name in ('sha512', 'sha384', 'sha256', 'sha1') if name != self.digest] + supportedCMSTypes = [getSignatureAlgorithm(self.credentials.privateKey, digest) for digest in digests] + if self.credentials.keyExchange == 'rsa': + supportedCMSTypes.append(buildAlgorithmIdentifier(ID_RSA_ENCRYPTION, encoder.encode(univ.Null('')))) + supportedCMSTypes.append(buildAlgorithmIdentifier(ID_AES256_CBC)) + supportedCMSTypes.append(buildAlgorithmIdentifier(ID_DES_EDE3_CBC)) + seq_set_iter(authPack, 'supportedCMSTypes', supportedCMSTypes) + return encoder.encode(authPack) + + def buildAsReq(self): + asReq = AS_REQ() + asReq['pvno'] = 5 + asReq['msg-type'] = int(constants.ApplicationTagNumbers.AS_REQ.value) + + reqBody = seq_set(asReq, 'req-body') + options = [constants.KDCOptions.forwardable.value, + constants.KDCOptions.renewable.value, + constants.KDCOptions.proxiable.value] + reqBody['kdc-options'] = constants.encodeFlags(options) + + serverName = self.serverName + if serverName is None: + serverName = Principal('krbtgt/%s' % self.domain, type=constants.PrincipalNameType.NT_PRINCIPAL.value) + elif not isinstance(serverName, Principal): + # getKerberosTGT also takes the service as a plain string + serverName = Principal(serverName, type=constants.PrincipalNameType.NT_PRINCIPAL.value) + seq_set(reqBody, 'sname', serverName.components_to_asn1) + seq_set(reqBody, 'cname', self.clientName.components_to_asn1) + reqBody['realm'] = self.domain + + now = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1) + reqBody['till'] = KerberosTime.to_asn1(now) + reqBody['rtime'] = KerberosTime.to_asn1(now) + self.nonce = int.from_bytes(os.urandom(4), 'big') >> 1 + reqBody['nonce'] = self.nonce + seq_set_iter(reqBody, 'etype', self.supportedCiphers) + + signedAuthPack = buildSignedData(self.credentials.privateKey, self.credentials.certificate, + self.credentials.chain, ID_PKINIT_AUTHDATA, + self.buildAuthPack(reqBody), self.digest) + paPkAsReq = PA_PK_AS_REQ() + paPkAsReq['signedAuthPack'] = signedAuthPack + + pacRequest = KERB_PA_PAC_REQUEST() + pacRequest['include-pac'] = self.requestPAC + + asReq['padata'] = univ.noValue + asReq['padata'][0] = univ.noValue + asReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PK_AS_REQ.value) + asReq['padata'][0]['padata-value'] = encoder.encode(paPkAsReq) + asReq['padata'][1] = univ.noValue + asReq['padata'][1]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value) + asReq['padata'][1]['padata-value'] = encoder.encode(pacRequest) + + if self.credentials.requestOCSP: + asReq['padata'][2] = univ.noValue + asReq['padata'][2]['padata-type'] = int( + constants.PreAuthenticationDataTypes.PA_PK_OCSP_RESPONSE.value) + asReq['padata'][2]['padata-value'] = encoder.encode(PKOcspData()) + + return encoder.encode(asReq) + + def getTGT(self): + # Imported here, kerberosv5 dispatches to this module + from impacket.krb5.kerberosv5 import KerberosError, sendReceive + + self.keyExchange = self.newKeyExchange() + # One retry per recoverable error: rejected domain parameters and rejected digest (RFC 4556 3.2.2) + for attempt in range(3): + self.asReq = self.buildAsReq() + try: + response = sendReceive(self.asReq, self.domain, self.kdcHost, timeout=self.timeout) + break + except KerberosError as e: + if attempt == 2: + raise + self.handleError(e) + + asRep = decodeASN1(response, AS_REP(), 'AS-REP') + replyKey = self.getReplyKey(asRep) + + # Key usage 3: AS-REP encrypted part, encrypted with the client key + cipher = getCipher(int(asRep['enc-part']['etype']), 'encrypted part of the AS-REP') + try: + plainText = cipher.decrypt(replyKey, 3, asRep['enc-part']['cipher'].asOctets()) + except InvalidChecksum: + raise PKINITError('The reply key derived from the certificate exchange does not decrypt the AS-REP') + encASRepPart = decodeASN1(plainText, EncASRepPart(), 'encrypted part of the AS-REP') + if int(encASRepPart['nonce']) != self.nonce: + raise PKINITError('The AS-REP nonce does not match the one of our AS-REQ') + + sessionCipher = getCipher(int(encASRepPart['key']['keytype']), 'session key') + sessionKey = Key(sessionCipher.enctype, encASRepPart['key']['keyvalue'].asOctets()) + return response, sessionCipher, replyKey, sessionKey + + def handleError(self, error): + """Recover from the errors RFC 4556 3.2.2 lets the client retry after.""" + errorCode = error.getErrorCode() + if errorCode == constants.ErrorCodes.KDC_ERR_KEY_TOO_WEAK.value: + # 65 is KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED in RFC 4556 3.1.3, not KDC_ERR_KEY_TOO_WEAK + self.keyExchange = self.getAcceptedKeyExchange(error) + elif errorCode in (constants.ErrorCodes.KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED.value, + constants.ErrorCodes.KDC_ERR_DIGEST_IN_CERT_NOT_ACCEPTED.value): + if self.digest == 'sha1': + raise error + LOG.debug('KDC rejected the %s digest, retrying with sha1' % self.digest) + self.digest = 'sha1' + elif errorCode in (constants.ErrorCodes.KDC_ERR_PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED.value, + constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value) and self.credentials.keyExchange == 'rsa': + # Windows KDCs implement no CMS algorithm for this method and answer KDC_ERR_ETYPE_NOSUPP + raise PKINITError('The KDC does not support the public key encryption method, use the Diffie-Hellman ' + 'key delivery method instead') + else: + raise error + + def getAcceptedKeyExchange(self, error): + """Pick a key exchange from the domain parameters the KDC proposed. + + RFC 4556 3.2.2 and RFC 5349 4: the KDC answers rejected domain parameters + with a TD-DH-PARAMETERS holding the ones it accepts, in decreasing + preference order, be they MODP groups or elliptic curves. + """ + eData = error.getErrorPacket()['e-data'] + if not eData.hasValue(): + raise PKINITError('The KDC rejected our Diffie-Hellman domain parameters without proposing any') + + for dataType, dataValue in self.parseErrorData(eData.asOctets()): + if dataType != constants.PreAuthenticationDataTypes.TD_DH_PARAMETERS.value: + continue + for algorithm in decoder.decode(dataValue, asn1Spec=TD_DH_PARAMETERS())[0]: + keyExchange = self.newKeyExchangeFromParameters(algorithm) + if keyExchange is not None: + return keyExchange + raise PKINITError('The KDC did not propose any Diffie-Hellman domain parameters we support') + + def newKeyExchangeFromParameters(self, algorithm): + """Build the key exchange a TD-DH-PARAMETERS entry stands for, or None if unsupported.""" + oid = str(algorithm['algorithm']) + if not algorithm['parameters'].hasValue(): + return None + try: + if oid == ID_DH_PUBLIC_NUMBER: + parameters = decoder.decode(bytes(algorithm['parameters']), asn1Spec=rfc3279.DomainParameters())[0] + prime = int(parameters['p']) + for group, (groupPrime, _) in DH_GROUPS.items(): + if groupPrime == prime: + LOG.debug('Retrying with the MODP group %d the KDC proposed' % group) + return DiffieHellman(group) + return None + if oid == ID_EC_PUBLIC_KEY: + # RFC 5480 2.1.1: named curves are an OID, custom curves a SEQUENCE we do not support + curveOid = str(decoder.decode(bytes(algorithm['parameters']), + asn1Spec=univ.ObjectIdentifier())[0]) + curve = EC_CURVE_OIDS.get(curveOid) + if curve is None: + return None + LOG.debug('Retrying with the %s curve the KDC proposed' % curve) + return EllipticCurveDiffieHellman(curve) + except PyAsn1Error as e: + LOG.debug('Ignoring domain parameters the KDC proposed for %s: %s' % (oid, e)) + return None + + def parseErrorData(self, eData): + """Return the (type, value) elements of a KRB-ERROR e-data field.""" + try: + return [(int(element['data-type']), element['data-value'].asOctets()) + for element in decoder.decode(eData, asn1Spec=TYPED_DATA())[0]] + except PyAsn1Error as e: + LOG.debug('e-data is not a TYPED-DATA (%s), reading it as a METHOD-DATA' % e) + return [(int(element['padata-type']), element['padata-value'].asOctets()) + for element in decoder.decode(eData, asn1Spec=METHOD_DATA())[0]] + + def getReplyKey(self, asRep): + paPkAsRep = None + for padata in asRep['padata']: + padataType = int(padata['padata-type']) + if padataType == constants.PreAuthenticationDataTypes.PA_PK_AS_REP.value: + paPkAsRep = decodeASN1(padata['padata-value'], PA_PK_AS_REP(), 'PA-PK-AS-REP') + elif padataType == constants.PreAuthenticationDataTypes.PA_PK_OCSP_RESPONSE.value: + try: + self.ocspResponses = decodeASN1(padata['padata-value'], PKOcspData(), 'PA-PK-OCSP-RESPONSE') + except PKINITError as e: + LOG.debug('Ignoring a malformed PA-PK-OCSP-RESPONSE: %s' % e) + + if paPkAsRep is None: + raise PKINITError('The KDC did not answer with a PA-PK-AS-REP, PKINIT is probably not enabled') + + cipher = getCipher(int(asRep['enc-part']['etype']), 'encrypted part of the AS-REP') + # Reading a component of a pyasn1 Choice selects it, so go through the name the KDC chose + if paPkAsRep.getName() == 'dhInfo': + return self.getReplyKeyFromDH(paPkAsRep.getComponent(), cipher) + return self.getReplyKeyFromEncKeyPack(bytes(paPkAsRep.getComponent()), cipher) + + def getReplyKeyFromDH(self, dhInfo, cipher): + """Derive the AS reply key from the DH exchange (RFC 4556 3.2.3.1).""" + if self.keyExchange is None: + raise PKINITError('The KDC answered with a Diffie-Hellman reply to a public key encryption request') + + content, certificate, certificates = verifySignedData(bytes(dhInfo['dhSignedData']), ID_PKINIT_DHKEYDATA) + self.checkKDCCertificate(certificate, certificates) + + keyInfo = decodeASN1(content, KDCDHKeyInfo(), 'KDCDHKeyInfo') + # RFC 4556 3.2.3.1: dhKeyExpiration is present if and only if the KDC reuses its DH keys + reusedKeys = keyInfo['dhKeyExpiration'].hasValue() + if reusedKeys: + expiration = KerberosTime.from_asn1(keyInfo['dhKeyExpiration']).replace(tzinfo=datetime.timezone.utc) + if expiration <= datetime.datetime.now(datetime.timezone.utc): + raise PKINITError('The Diffie-Hellman key the KDC reused expired on %s, its signature over the ' + 'DHRepInfo is no longer valid' % expiration) + + # RFC 4556 3.2.3.1: the nonce is our pkAuthenticator one, or 0 when the KDC reuses its DH keys + expectedNonce = 0 if reusedKeys else self.nonce + if int(keyInfo['nonce']) != expectedNonce: + raise PKINITError('The KDCDHKeyInfo nonce does not match the one of our PKAuthenticator') + + # k = octetstring2key(DHSharedSecret | n_c | n_k), n_c stays empty since we send no clientDHNonce + serverDHNonce = b'' + if reusedKeys: + if not dhInfo['serverDHNonce'].hasValue(): + raise PKINITError('The KDC reused its Diffie-Hellman key without sending a serverDHNonce') + serverDHNonce = bytes(dhInfo['serverDHNonce']) + + sharedSecret = self.keyExchange.getSharedSecret( + self.keyExchange.getPeerPublicKey(keyInfo['subjectPublicKey'])) + return octetstring2key(sharedSecret + serverDHNonce, cipher) + + def getReplyKeyFromEncKeyPack(self, encKeyPack, cipher): + """Extract the AS reply key from the encrypted key pack.""" + if self.keyExchange is not None: + raise PKINITError('The KDC answered with an encrypted key pack to a Diffie-Hellman request') + + content, certificate, certificates = verifySignedData( + decryptEnvelopedData(encKeyPack, self.credentials.privateKey), ID_PKINIT_RKEYDATA) + self.checkKDCCertificate(certificate, certificates) + + replyKeyPack = decodeASN1(content, ReplyKeyPack(), 'ReplyKeyPack') + enctype = int(replyKeyPack['replyKey']['keytype']) + try: + replyKey = Key(enctype, replyKeyPack['replyKey']['keyvalue'].asOctets()) + except ValueError as e: + raise PKINITError('The KDC sent an unusable reply key: %s' % e) + + checksum = replyKeyPack['asChecksum'] + cksumtype = int(checksum['cksumtype']) + if cksumtype != CHECKSUM_FOR_ENCTYPE.get(enctype): + raise PKINITError('The asChecksum uses checksum type %d, which is not the required one for the reply key' + % cksumtype) + try: + verify_checksum(cksumtype, replyKey, KEY_USAGE_AS_REQ_CHECKSUM, self.asReq, + checksum['checksum'].asOctets()) + except InvalidChecksum: + raise PKINITError('The asChecksum of the ReplyKeyPack does not match our AS-REQ') + return replyKey + + def checkKDCCertificate(self, certificate, certificates): + if not self.credentials.verifyKDC: + LOG.debug('KDC certificate validation is disabled') + return + verifyKDCCertificate(certificate, certificates, self.domain, self.credentials.trustedCAs) + self.checkOCSPResponses(certificate, certificates) + + def checkOCSPResponses(self, certificate, certificates): + """Check the revocation status the KDC piggybacked in the reply.""" + checked = False + for response in self.ocspResponses: + try: + ocspResponse = ocsp.load_der_ocsp_response(bytes(response)) + status = ocspResponse.response_status + if status != ocsp.OCSPResponseStatus.SUCCESSFUL: + LOG.debug('Ignoring an unsuccessful OCSP response (%s)' % status.name) + continue + if ocspResponse.serial_number != certificate.serial_number: + continue + verifyOCSPResponse(ocspResponse, certificate, certificates + self.credentials.trustedCAs) + if ocspResponse.certificate_status == ocsp.OCSPCertStatus.REVOKED: + raise KDCCertificateError('The KDC certificate was revoked on %s' + % getRevocationTime(ocspResponse)) + LOG.debug('OCSP status of the KDC certificate: %s' % ocspResponse.certificate_status.name) + checked = True + except (ValueError, PKINITError) as e: + if isinstance(e, KDCCertificateError): + raise + LOG.debug('Ignoring an invalid OCSP response: %s' % e) + + # RFC 4557 3: a missing response should be an error, but no Windows KDC sends one, so it is opt-in + if not checked and self.credentials.requireOCSP: + raise KDCCertificateError('The KDC did not return a usable OCSP response for its certificate') + + +def getKerberosTGTPKINIT(clientName, domain, credentials, kdcHost=None, requestPAC=True, serverName=None, + supportedCiphers=None, timeout=None): + """Request a TGT with a client certificate, as defined in RFC 4556. + + Returns the same (tgt, cipher, oldSessionKey, sessionKey) tuple as + getKerberosTGT, where oldSessionKey is the AS reply key derived from the + certificate exchange. + """ + pkinit = PKINIT(clientName, domain, credentials, kdcHost=kdcHost, requestPAC=requestPAC, serverName=serverName, + supportedCiphers=supportedCiphers, timeout=timeout) + return pkinit.getTGT() \ No newline at end of file diff --git a/tests/misc/test_pkinit.py b/tests/misc/test_pkinit.py new file mode 100644 index 0000000000..ae0abc4f90 --- /dev/null +++ b/tests/misc/test_pkinit.py @@ -0,0 +1,1136 @@ +#!/usr/bin/env python +# Impacket - Collection of Python classes for working with network protocols. +# +# Copyright Fortra, LLC and its affiliated companies +# +# All rights reserved. +# +# This software is provided under a slightly modified version +# of the Apache Software License. See the accompanying LICENSE file +# for more information. +# +# Description: +# Tests for the PKINIT client (RFC 4556, RFC 5349, RFC 4557). +# +# The AS exchange is played against a KDC implemented in this file, so both AS +# reply key delivery methods are exercised end to end without a domain. +# +from __future__ import print_function + +import datetime +import unittest +from binascii import hexlify, unhexlify +from hashlib import sha1 + +from Cryptodome.Cipher import AES, DES3 +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa +from cryptography.x509 import ocsp +from cryptography.x509.oid import NameOID +from pyasn1.codec.der import decoder, encoder +from pyasn1.type import char, tag, univ +from pyasn1_modules import rfc3279, rfc5280, rfc5652 + +import impacket.krb5.kerberosv5 as kerberosv5 +from impacket.krb5 import constants +from impacket.krb5.ccache import CCache +from impacket.krb5.asn1 import AS_REP, AS_REQ, AuthPack, EncASRepPart, KDCDHKeyInfo, METHOD_DATA, \ + PA_PK_AS_REP, PA_PK_AS_REQ, PKOcspData, ReplyKeyPack, TD_DH_PARAMETERS, TYPED_DATA, seq_set, seq_set_iter +from impacket.krb5.crypto import Cksumtype, Enctype, Key, _enctype_table, make_checksum +from impacket.krb5.pkinit import DH_GROUPS, DIGEST_ALGORITHMS, EC_CURVES, EC_CURVE_OIDS, ID_AES256_CBC, ID_DES_EDE3_CBC, \ + ID_ENVELOPED_DATA, decryptEnvelopedData, \ + ID_DH_PUBLIC_NUMBER, ID_EC_PUBLIC_KEY, ID_MS_SAN_SC_LOGON_UPN, ID_PKINIT_AUTHDATA, \ + ID_PKINIT_DHKEYDATA, ID_PKINIT_KP_KDC, ID_PKINIT_RKEYDATA, ID_PKINIT_SAN, ID_RSA_ENCRYPTION, DiffieHellman, \ + EllipticCurveDiffieHellman, KDCCertificateError, PKINIT, PKINITCredentials, PKINITError, buildAlgorithmIdentifier, \ + buildCertificateSet, buildContentInfo, buildSignedData, getReqBodyBytes, getSignatureAlgorithm,\ + buildSignerIdentifier, signData, octetstring2key, parseSignedData, verifyKDCCertificate, verifySignedData +from impacket.krb5.types import KerberosTime, Principal + +REALM = 'CONTOSO.COM' +CLIENT = 'jdoe' + + +def h(hexstr): + return unhexlify(hexstr.replace(' ', '').replace('\n', '')) + + +def setComponent(sequence, name, **kwargs): + """Set a simple component from raw octets, keeping the context tag of its slot.""" + sequence[name] = sequence[name].clone(**kwargs) + + +def makeKerberosPrincipalName(realm, components): + from impacket.krb5.asn1 import KRB5PrincipalName + principalName = KRB5PrincipalName() + principalName['realm'] = realm + principalName['principalName']['name-type'] = int(constants.PrincipalNameType.NT_SRV_INST.value) + seq_set_iter(principalName['principalName'], 'name-string', components) + return encoder.encode(principalName) + + +def makeKeyUsage(**bits): + """Build a KeyUsage extension, every bit defaulting to False.""" + usage = dict(digital_signature=False, content_commitment=False, key_encipherment=False, data_encipherment=False, + key_agreement=False, key_cert_sign=False, crl_sign=False, encipher_only=False, decipher_only=False) + usage.update(bits) + return x509.KeyUsage(**usage) + + +def makeCertificate(commonName, issuerCertificate=None, issuerKey=None, otherName=None, extendedKeyUsage=None, + isCA=None, key=None, pathLength=None, keyUsage=None): + key = key or rsa.generate_private_key(public_exponent=65537, key_size=2048) + subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, commonName)]) + issuer = issuerCertificate.subject if issuerCertificate is not None else subject + now = datetime.datetime.now(datetime.timezone.utc) + + builder = x509.CertificateBuilder().subject_name(subject).issuer_name(issuer).public_key(key.public_key()) \ + .serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(days=1)) \ + .not_valid_after(now + datetime.timedelta(days=365)) \ + .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False) + if isCA is not None: + builder = builder.add_extension(x509.BasicConstraints(ca=isCA, path_length=pathLength), critical=True) + if keyUsage is not None: + builder = builder.add_extension(keyUsage, critical=True) + if otherName is not None: + builder = builder.add_extension(x509.SubjectAlternativeName([otherName]), critical=False) + if extendedKeyUsage is not None: + builder = builder.add_extension( + x509.ExtendedKeyUsage([x509.ObjectIdentifier(oid) for oid in extendedKeyUsage]), critical=False) + + certificate = builder.sign(issuerKey or key, hashes.SHA256()) + return key, certificate + + +class PKI: + """A CA, a KDC certificate and a client certificate, as an enterprise CA would issue them.""" + + def __init__(self): + self.caKey, self.caCertificate = makeCertificate('Contoso Root CA', isCA=True) + self.kdcKey, self.kdcCertificate = makeCertificate( + 'dc01.contoso.com', self.caCertificate, self.caKey, + otherName=x509.OtherName(x509.ObjectIdentifier(ID_PKINIT_SAN), + makeKerberosPrincipalName(REALM, ['krbtgt', REALM])), + extendedKeyUsage=[ID_PKINIT_KP_KDC]) + self.clientKey, self.clientCertificate = makeCertificate( + CLIENT, self.caCertificate, self.caKey, + otherName=x509.OtherName(x509.ObjectIdentifier(ID_MS_SAN_SC_LOGON_UPN), + encoder.encode(char.UTF8String('%s@contoso.com' % CLIENT)))) + + +class KDC: + """A minimal PKINIT KDC, implementing RFC 4556 3.2.2 and 3.2.3.""" + + def __init__(self, pki, enctype=Enctype.AES256, useEncKeyPack=False, rejectDHGroup=None, nonceOverride=None, + rejectDigest=None, ocspStatus=None, contentEncryption='aes256-CBC', reuseDHKeys=False, + dhKeyLifetime=3600, serverDHNonce=None, rejectCurve=None, proposeCurve=None, useTypedData=False, + ocspResponder=None, ocspExpired=False, answerDHWithoutRequest=False): + self.pki = pki + self.cipher = _enctype_table[enctype] + self.useEncKeyPack = useEncKeyPack + self.rejectDHGroup = rejectDHGroup + self.nonceOverride = nonceOverride + self.rejectDigest = rejectDigest + self.ocspStatus = ocspStatus + self.contentEncryption = contentEncryption + self.reuseDHKeys = reuseDHKeys + self.dhKeyLifetime = dhKeyLifetime + self.serverDHNonce = serverDHNonce if serverDHNonce is not None else b'N' * 32 + self.rejectCurve = rejectCurve + self.proposeCurve = proposeCurve + self.useTypedData = useTypedData + self.ocspResponder = ocspResponder + self.ocspExpired = ocspExpired + self.answerDHWithoutRequest = answerDHWithoutRequest + self.replyKey = None + self.ocspRequested = False + self.sessionKey = Key(enctype, b'S' * self.cipher.keysize) + + def sendReceive(self, data, host, kdcHost, port=88, timeout=None): + asReq = decoder.decode(data, asn1Spec=AS_REQ())[0] + authPack, clientCertificate = self.verifyRequest(asReq) + + if self.useEncKeyPack: + paPkAsRep = self.buildEncKeyPack(data, clientCertificate) + else: + paPkAsRep = self.buildDHInfo(authPack) + return self.buildAsRep(asReq, paPkAsRep) + + def verifyRequest(self, asReq): + padata = {int(entry['padata-type']): entry['padata-value'] for entry in asReq['padata']} + assert constants.PreAuthenticationDataTypes.PA_PK_AS_REQ.value in padata, 'no PA-PK-AS-REQ in the AS-REQ' + assert constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value in padata, 'no PA-PAC-REQUEST in the AS-REQ' + + self.ocspRequested = constants.PreAuthenticationDataTypes.PA_PK_OCSP_RESPONSE.value in padata + + paPkAsReq = decoder.decode(padata[constants.PreAuthenticationDataTypes.PA_PK_AS_REQ.value], + asn1Spec=PA_PK_AS_REQ())[0] + if self.rejectDigest is not None and self.usesDigest(paPkAsReq, self.rejectDigest): + self.raiseError(constants.ErrorCodes.KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED.value) + content, certificate, _ = verifySignedData(bytes(paPkAsReq['signedAuthPack']), ID_PKINIT_AUTHDATA) + authPack = decoder.decode(content, asn1Spec=AuthPack())[0] + + expected = sha1(getReqBodyBytes(asReq['req-body'])).digest() + assert bytes(authPack['pkAuthenticator']['paChecksum']) == expected, 'bad paChecksum' + return authPack, certificate + + def buildDHInfo(self, authPack): + publicKeyInfo = authPack['clientPublicValue'] + if not publicKeyInfo.hasValue(): + assert self.answerDHWithoutRequest, 'no clientPublicValue in the AuthPack' + return self.buildDHRepInfo(DiffieHellman(14), b'unused', encoder.encode(univ.Integer(1)), 0) + + algorithm = str(publicKeyInfo['algorithm']['algorithm']) + if algorithm == ID_DH_PUBLIC_NUMBER: + parameters = decoder.decode(bytes(publicKeyInfo['algorithm']['parameters']), + asn1Spec=rfc3279.DomainParameters())[0] + prime, generator = int(parameters['p']), int(parameters['g']) + assert int(parameters['q']) == (prime - 1) // 2, 'bad DH subgroup order' + if self.rejectDHGroup is not None and prime == DH_GROUPS[self.rejectDHGroup][0]: + self.raiseDHParametersNotAccepted() + keyExchange = DiffieHellman(prime=prime, generator=generator) + clientPublicKey = int(decoder.decode(publicKeyInfo['subjectPublicKey'].asOctets(), + asn1Spec=univ.Integer())[0]) + sharedSecret = keyExchange.getSharedSecret(clientPublicKey) + subjectPublicKey = encoder.encode(univ.Integer(keyExchange.publicKey)) + else: + assert algorithm == ID_EC_PUBLIC_KEY, 'unexpected key agreement algorithm %s' % algorithm + curveOid = str(decoder.decode(bytes(publicKeyInfo['algorithm']['parameters']), + asn1Spec=univ.ObjectIdentifier())[0]) + curve = EC_CURVE_OIDS[curveOid] + if self.rejectCurve is not None and curve == self.rejectCurve: + self.raiseDHParametersNotAccepted() + keyExchange = EllipticCurveDiffieHellman(curve) + clientPublicKey = ec.EllipticCurvePublicKey.from_encoded_point( + EC_CURVES[curve](), publicKeyInfo['subjectPublicKey'].asOctets()) + sharedSecret = keyExchange.getSharedSecret(clientPublicKey) + subjectPublicKey = keyExchange.privateKey.public_key().public_bytes( + serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint) + + return self.buildDHRepInfo(keyExchange, sharedSecret, subjectPublicKey, + int(authPack['pkAuthenticator']['nonce'])) + + def buildDHRepInfo(self, keyExchange, sharedSecret, subjectPublicKey, nonce): + serverDHNonce = self.serverDHNonce if self.reuseDHKeys else b'' + self.replyKey = octetstring2key(sharedSecret + serverDHNonce, self.cipher) + + keyInfo = KDCDHKeyInfo() + setComponent(keyInfo, 'subjectPublicKey', hexValue=hexlify(subjectPublicKey).decode('ascii')) + if self.nonceOverride is not None: + keyInfo['nonce'] = self.nonceOverride + elif self.reuseDHKeys: + keyInfo['nonce'] = 0 + else: + keyInfo['nonce'] = nonce + + paPkAsRep = PA_PK_AS_REP() + dhRepInfo = paPkAsRep.setComponentByName('dhInfo').getComponentByName('dhInfo') + if self.reuseDHKeys: + expiration = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(seconds=self.dhKeyLifetime) + keyInfo['dhKeyExpiration'] = KerberosTime.to_asn1(expiration) + if self.serverDHNonce: + setComponent(dhRepInfo, 'serverDHNonce', value=self.serverDHNonce) + dhRepInfo['dhSignedData'] = buildSignedData(self.pki.kdcKey, self.pki.kdcCertificate, [], + ID_PKINIT_DHKEYDATA, encoder.encode(keyInfo), 'sha256') + return paPkAsRep + + def buildEncKeyPack(self, asReq, clientCertificate): + self.replyKey = Key(self.cipher.enctype, b'R' * self.cipher.keysize) + + replyKeyPack = ReplyKeyPack() + replyKeyPack['replyKey']['keytype'] = self.replyKey.enctype + replyKeyPack['replyKey']['keyvalue'] = self.replyKey.contents + # key usage 6 + cksumtype = {Enctype.AES256: Cksumtype.SHA1_AES256, Enctype.AES128: Cksumtype.SHA1_AES128, + Enctype.RC4: Cksumtype.HMAC_MD5}[self.cipher.enctype] + replyKeyPack['asChecksum']['cksumtype'] = cksumtype + replyKeyPack['asChecksum']['checksum'] = make_checksum(cksumtype, self.replyKey, 6, asReq) + + signedData = buildSignedData(self.pki.kdcKey, self.pki.kdcCertificate, [], ID_PKINIT_RKEYDATA, + encoder.encode(replyKeyPack), 'sha256') + + if self.contentEncryption == 'des-ede3-cbc': + contentEncryptionKey, initializationVector, blockSize = b'KEY' * 8, b'IV' * 4, 8 + algorithm = DES3.new(contentEncryptionKey, DES3.MODE_CBC, initializationVector) + algorithmOid = ID_DES_EDE3_CBC + else: + contentEncryptionKey, initializationVector, blockSize = b'K' * 32, b'I' * 16, 16 + algorithm = AES.new(contentEncryptionKey, AES.MODE_CBC, initializationVector) + algorithmOid = ID_AES256_CBC + padLength = blockSize - len(signedData) % blockSize + encryptedContent = algorithm.encrypt(signedData + bytes([padLength]) * padLength) + + recipientInfo = rfc5652.KeyTransRecipientInfo() + recipientInfo['version'] = 0 + issuerAndSerial = recipientInfo['rid'].setComponentByName('issuerAndSerialNumber').getComponentByName( + 'issuerAndSerialNumber') + issuerAndSerial['issuer'] = decoder.decode(clientCertificate.issuer.public_bytes(), + asn1Spec=rfc5280.Name())[0] + issuerAndSerial['serialNumber'] = clientCertificate.serial_number + recipientInfo['keyEncryptionAlgorithm'] = buildAlgorithmIdentifier( + ID_RSA_ENCRYPTION, encoder.encode(univ.Null(''))) + recipientInfo['encryptedKey'] = clientCertificate.public_key().encrypt(contentEncryptionKey, + padding.PKCS1v15()) + + envelopedData = rfc5652.EnvelopedData() + envelopedData['version'] = 0 + envelopedData['recipientInfos'].setComponentByPosition(0, rfc5652.RecipientInfo()) + envelopedData['recipientInfos'][0]['ktri'] = recipientInfo + envelopedData['encryptedContentInfo']['contentType'] = univ.ObjectIdentifier('1.2.840.113549.1.7.2') + envelopedData['encryptedContentInfo']['contentEncryptionAlgorithm'] = buildAlgorithmIdentifier( + algorithmOid, encoder.encode(univ.OctetString(initializationVector))) + envelopedData['encryptedContentInfo']['encryptedContent'] = univ.OctetString(encryptedContent).subtype( + implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)) + + paPkAsRep = PA_PK_AS_REP() + paPkAsRep['encKeyPack'] = buildContentInfo('1.2.840.113549.1.7.3', encoder.encode(envelopedData)) + return paPkAsRep + + def usesDigest(self, paPkAsReq, digest): + signerInfo = parseSignedData(bytes(paPkAsReq['signedAuthPack']), ID_PKINIT_AUTHDATA)[1] + return str(signerInfo['digestAlgorithm']['algorithm']) == DIGEST_ALGORITHMS[digest][0] + + def buildAcceptedParameters(self): + accepted = TD_DH_PARAMETERS() + if self.proposeCurve is not None: + # sect571r1 stands for a curve of RFC 5349 5 this client does not implement + curveOid = next((oid for oid, name in EC_CURVE_OIDS.items() if name == self.proposeCurve), + '1.3.132.0.39') + accepted.setComponentByPosition(0, buildAlgorithmIdentifier( + ID_EC_PUBLIC_KEY, encoder.encode(univ.ObjectIdentifier(curveOid)))) + return accepted + parameters = rfc3279.DomainParameters() + prime, generator = DH_GROUPS[14] + parameters['p'], parameters['g'], parameters['q'] = prime, generator, (prime - 1) // 2 + accepted.setComponentByPosition(0, buildAlgorithmIdentifier(ID_DH_PUBLIC_NUMBER, encoder.encode(parameters))) + return accepted + + def raiseDHParametersNotAccepted(self): + accepted = encoder.encode(self.buildAcceptedParameters()) + dataType = int(constants.PreAuthenticationDataTypes.TD_DH_PARAMETERS.value) + + if self.useTypedData: + # RFC 4556 3.2.2 carries the error details in a TYPED-DATA, which is what Windows KDCs send + errorData = TYPED_DATA() + errorData.setComponentByPosition(0, univ.noValue) + errorData[0]['data-type'] = dataType + errorData[0]['data-value'] = accepted + else: + errorData = METHOD_DATA() + errorData.setComponentByPosition(0, univ.noValue) + errorData[0]['padata-type'] = dataType + errorData[0]['padata-value'] = accepted + self.raiseError(constants.ErrorCodes.KDC_ERR_KEY_TOO_WEAK.value, encoder.encode(errorData)) + + def raiseError(self, errorCode, eData=None): + from impacket.krb5.asn1 import KRB_ERROR + + krbError = KRB_ERROR() + krbError['pvno'] = 5 + krbError['msg-type'] = int(constants.ApplicationTagNumbers.KRB_ERROR.value) + krbError['stime'] = KerberosTime.to_asn1(datetime.datetime.now(datetime.timezone.utc)) + krbError['susec'] = 0 + krbError['error-code'] = int(errorCode) + krbError['realm'] = REALM + seq_set(krbError, 'sname', + Principal('krbtgt/%s' % REALM, type=constants.PrincipalNameType.NT_SRV_INST.value).components_to_asn1) + if eData is not None: + krbError['e-data'] = eData + raise kerberosv5.KerberosError(packet=krbError) + + def buildOCSPResponse(self): + """Build the OCSP response for the KDC certificate, as RFC 4557 3 allows.""" + now = datetime.datetime.now(datetime.timezone.utc) + responderKey, responderCertificate = self.ocspResponder or (self.pki.caKey, self.pki.caCertificate) + thisUpdate = now - datetime.timedelta(days=2) if self.ocspExpired else now + nextUpdate = thisUpdate + datetime.timedelta(days=1) + builder = ocsp.OCSPResponseBuilder().add_response( + cert=self.pki.kdcCertificate, issuer=self.pki.caCertificate, algorithm=hashes.SHA1(), + cert_status=self.ocspStatus, this_update=thisUpdate, next_update=nextUpdate, + revocation_time=thisUpdate if self.ocspStatus == ocsp.OCSPCertStatus.REVOKED else None, + revocation_reason=x509.ReasonFlags.key_compromise if self.ocspStatus == ocsp.OCSPCertStatus.REVOKED + else None).responder_id(ocsp.OCSPResponderEncoding.NAME, responderCertificate) \ + .certificates([responderCertificate, self.pki.caCertificate]) + response = builder.sign(responderKey, hashes.SHA256()) + + ocspData = PKOcspData() + ocspData.setComponentByPosition(0, response.public_bytes(serialization.Encoding.DER)) + return encoder.encode(ocspData) + + def buildAsRep(self, asReq, paPkAsRep): + encPart = EncASRepPart() + encPart['key']['keytype'] = self.sessionKey.enctype + encPart['key']['keyvalue'] = self.sessionKey.contents + encPart['last-req'] = univ.noValue + encPart['last-req'][0] = univ.noValue + encPart['last-req'][0]['lr-type'] = 0 + encPart['last-req'][0]['lr-value'] = KerberosTime.to_asn1(datetime.datetime.now(datetime.timezone.utc)) + encPart['nonce'] = int(asReq['req-body']['nonce']) + encPart['flags'] = constants.encodeFlags([constants.TicketFlags.initial.value]) + now = datetime.datetime.now(datetime.timezone.utc) + encPart['authtime'] = KerberosTime.to_asn1(now) + encPart['starttime'] = KerberosTime.to_asn1(now) + encPart['endtime'] = KerberosTime.to_asn1(now + datetime.timedelta(hours=10)) + encPart['renew-till'] = KerberosTime.to_asn1(now + datetime.timedelta(days=7)) + encPart['srealm'] = REALM + seq_set(encPart, 'sname', + Principal('krbtgt/%s' % REALM, type=constants.PrincipalNameType.NT_SRV_INST.value).components_to_asn1) + + asRep = AS_REP() + asRep['pvno'] = 5 + asRep['msg-type'] = int(constants.ApplicationTagNumbers.AS_REP.value) + asRep['padata'] = univ.noValue + asRep['padata'][0] = univ.noValue + asRep['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PK_AS_REP.value) + asRep['padata'][0]['padata-value'] = encoder.encode(paPkAsRep) + if self.ocspStatus is not None: + asRep['padata'][1] = univ.noValue + asRep['padata'][1]['padata-type'] = int( + constants.PreAuthenticationDataTypes.PA_PK_OCSP_RESPONSE.value) + asRep['padata'][1]['padata-value'] = self.buildOCSPResponse() + asRep['crealm'] = REALM + seq_set(asRep, 'cname', + Principal(CLIENT, type=constants.PrincipalNameType.NT_PRINCIPAL.value).components_to_asn1) + + ticket = asRep['ticket'] + ticket['tkt-vno'] = 5 + ticket['realm'] = REALM + seq_set(ticket, 'sname', + Principal('krbtgt/%s' % REALM, type=constants.PrincipalNameType.NT_SRV_INST.value).components_to_asn1) + ticket['enc-part']['etype'] = self.cipher.enctype + ticket['enc-part']['cipher'] = b'T' * 32 + + asRep['enc-part']['etype'] = self.cipher.enctype + # Key usage 3: AS-REP encrypted part + asRep['enc-part']['cipher'] = self.cipher.encrypt(self.replyKey, 3, encoder.encode(encPart), None) + return encoder.encode(asRep) + + +class OctetString2KeyTests(unittest.TestCase): + """RFC 4556, Appendix B: test vectors of octetstring2key().""" + + def check(self, x, expected): + cipher = _enctype_table[Enctype.AES256] + self.assertEqual(octetstring2key(x, cipher).contents, h(expected)) + + def test_set1(self): + self.check(b'\x00' * 256, '5ee50d675c809fe59e4a7762c54b65837547eafb159bd8cdc75ffca5911e4c41') + + def test_set2(self): + self.check(b'\x00' * 128, 'acf7707c08973ddfdb27cd361442ccfba355c8884cb472f37da636d07d56787e') + + def test_set3(self): + self.check(bytes(bytearray(range(0x11)) * 8)[:128], + 'c442da585fcb80e43b47946f254093e37329d99001380db78371db3acf5c797e') + + def test_set4(self): + self.check(bytes(bytearray(range(0x11)) * 8)[:77], + '0053953b84c896f4eb385c3f2e751c4a590ed6ffadca6ff64f47ebeb8d780ffc') + + +class DiffieHellmanTests(unittest.TestCase): + def test_groupsAreTheRFCSafePrimes(self): + # RFC 2409 E.2 and RFC 3526: p = 2^b - 2^(b-64) - 1 + 2^64 * ([2^(b-130) pi] + offset) + for group, bits, offset in ((2, 1024, 129093), (5, 1536, 741804), (14, 2048, 124476), + (15, 3072, 1690314), (16, 4096, 240904)): + prime, generator = DH_GROUPS[group] + self.assertEqual(prime, self.modpPrime(bits, offset), 'MODP group %d does not match the RFC' % group) + self.assertEqual(generator, 2) + self.assertEqual(prime.bit_length(), bits) + + def modpPrime(self, bits, offset): + return (1 << bits) - (1 << (bits - 64)) - 1 + (1 << 64) * ((self.pi(bits - 130)) + offset) + + def pi(self, bits): + # Machin's formula in fixed point, with guard bits to absorb the rounding + one = 1 << (bits + 64) + value = 4 * (4 * self.arctanInverse(5, one) - self.arctanInverse(239, one)) + return value >> 64 + + def arctanInverse(self, x, one): + total = term = one // x + square = x * x + n = 1 + while term: + term //= square + n += 2 + total += term // n if (n // 2) % 2 == 0 else -(term // n) + return total + + def test_sharedSecretIsPaddedToTheModulusSize(self): + alice, bob = DiffieHellman(group=14), DiffieHellman(group=14) + shared = alice.getSharedSecret(bob.publicKey) + self.assertEqual(shared, bob.getSharedSecret(alice.publicKey)) + self.assertEqual(len(shared), 256) + + def test_invalidPublicValueIsRejected(self): + alice = DiffieHellman(group=14) + for invalid in (0, 1, alice.prime - 1, alice.prime): + self.assertRaises(PKINITError, alice.getSharedSecret, invalid) + + def test_subjectPublicKeyInfoRoundTrip(self): + alice = DiffieHellman(group=2) + publicKeyInfo = alice.getSubjectPublicKeyInfo() + self.assertEqual(str(publicKeyInfo['algorithm']['algorithm']), '1.2.840.10046.2.1') + parameters = decoder.decode(bytes(publicKeyInfo['algorithm']['parameters']), + asn1Spec=rfc3279.DomainParameters())[0] + self.assertEqual(int(parameters['p']), alice.prime) + self.assertEqual(alice.getPeerPublicKey(publicKeyInfo['subjectPublicKey']), alice.publicKey) + + def test_ellipticCurveSharedSecret(self): + alice, bob = EllipticCurveDiffieHellman('P-256'), EllipticCurveDiffieHellman('P-256') + publicKeyInfo = alice.getSubjectPublicKeyInfo() + self.assertEqual(str(publicKeyInfo['algorithm']['algorithm']), '1.2.840.10045.2.1') + self.assertEqual(bob.getSharedSecret(bob.getPeerPublicKey(publicKeyInfo['subjectPublicKey'])), + alice.getSharedSecret(alice.getPeerPublicKey(bob.getSubjectPublicKeyInfo()['subjectPublicKey']))) + + +class SignedDataTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.pki = PKI() + + def test_roundTrip(self): + for digest in ('sha1', 'sha256', 'sha384', 'sha512'): + data = buildSignedData(self.pki.clientKey, self.pki.clientCertificate, [self.pki.caCertificate], + ID_PKINIT_AUTHDATA, b'signed content', digest) + content, certificate, certificates = verifySignedData(data, ID_PKINIT_AUTHDATA) + self.assertEqual(content, b'signed content') + self.assertEqual(certificate, self.pki.clientCertificate) + self.assertEqual(len(certificates), 2) + + def test_ecdsaSignature(self): + key, certificate = makeCertificate('ecdsa client', self.pki.caCertificate, self.pki.caKey, + key=ec.generate_private_key(ec.SECP256R1())) + data = buildSignedData(key, certificate, [], ID_PKINIT_AUTHDATA, b'signed content', 'sha256') + self.assertEqual(verifySignedData(data, ID_PKINIT_AUTHDATA)[0], b'signed content') + + def test_tamperedSignatureIsRejected(self): + signed = bytearray(buildSignedData(self.pki.kdcKey, self.pki.kdcCertificate, [], ID_PKINIT_DHKEYDATA, + b'content', 'sha256')) + signed[-1] ^= 0xFF + self.assertRaisesRegex(PKINITError, 'signature .* is invalid', verifySignedData, bytes(signed), + ID_PKINIT_DHKEYDATA) + + def test_tamperedContentIsRejected(self): + data = buildSignedData(self.pki.clientKey, self.pki.clientCertificate, [], ID_PKINIT_AUTHDATA, + b'signed content', 'sha256') + tampered = data.replace(b'signed content', b'forged content') + self.assertRaises(PKINITError, verifySignedData, tampered, ID_PKINIT_AUTHDATA) + + def test_unexpectedContentTypeIsRejected(self): + data = buildSignedData(self.pki.clientKey, self.pki.clientCertificate, [], ID_PKINIT_AUTHDATA, + b'signed content', 'sha256') + self.assertRaises(PKINITError, verifySignedData, data, ID_PKINIT_DHKEYDATA) + + +class KDCCertificateTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.pki = PKI() + + def test_pkinitSanIsAccepted(self): + verifyKDCCertificate(self.pki.kdcCertificate, [self.pki.caCertificate], REALM, [self.pki.caCertificate]) + + def test_certificateOfAnotherRealmIsRejected(self): + self.assertRaises(KDCCertificateError, verifyKDCCertificate, self.pki.kdcCertificate, + [self.pki.caCertificate], 'OTHER.COM', [self.pki.caCertificate]) + + def test_certificateWithoutKDCPurposeIsRejected(self): + self.assertRaises(KDCCertificateError, verifyKDCCertificate, self.pki.clientCertificate, + [self.pki.caCertificate], REALM, [self.pki.caCertificate]) + + def test_untrustedIssuerIsRejected(self): + otherPki = PKI() + self.assertRaises(KDCCertificateError, verifyKDCCertificate, self.pki.kdcCertificate, + [self.pki.caCertificate], REALM, [otherPki.caCertificate]) + + def test_pathIsNotValidatedWithoutAnchor(self): + verifyKDCCertificate(self.pki.kdcCertificate, [], REALM, []) + + def makeKDCCertificate(self, issuerCertificate, issuerKey): + return makeCertificate('dc01.contoso.com', issuerCertificate, issuerKey, + otherName=x509.OtherName(x509.ObjectIdentifier(ID_PKINIT_SAN), + makeKerberosPrincipalName(REALM, ['krbtgt', REALM])), + extendedKeyUsage=[ID_PKINIT_KP_KDC])[1] + + def test_issuerWithoutTheCAFlagIsRejected(self): + issuerKey, issuerCertificate = makeCertificate('Contoso Leaf', isCA=False) + certificate = self.makeKDCCertificate(issuerCertificate, issuerKey) + self.assertRaisesRegex(KDCCertificateError, 'not a CA', verifyKDCCertificate, certificate, + [issuerCertificate], REALM, [issuerCertificate]) + + def test_certificateWithoutTheDigitalSignatureKeyUsageIsRejected(self): + # RFC 4556 3.2.4: the digitalSignature key usage bit must be asserted + certificate = makeCertificate('dc01.contoso.com', self.pki.caCertificate, self.pki.caKey, + otherName=x509.OtherName(x509.ObjectIdentifier(ID_PKINIT_SAN), + makeKerberosPrincipalName(REALM, ['krbtgt', REALM])), + extendedKeyUsage=[ID_PKINIT_KP_KDC], + keyUsage=makeKeyUsage(key_encipherment=True))[1] + self.assertRaisesRegex(KDCCertificateError, 'not allowed to sign', verifyKDCCertificate, certificate, + [self.pki.caCertificate], REALM, [self.pki.caCertificate]) + + def test_issuerWithoutBasicConstraintsIsRejected(self): + issuerKey, issuerCertificate = makeCertificate('Contoso Leaf') + certificate = self.makeKDCCertificate(issuerCertificate, issuerKey) + self.assertRaisesRegex(KDCCertificateError, 'without a basicConstraints', verifyKDCCertificate, certificate, + [issuerCertificate], REALM, [issuerCertificate]) + + def test_issuerWithoutTheCertificateSigningKeyUsageIsRejected(self): + issuerKey, issuerCertificate = makeCertificate('Contoso Root CA', isCA=True, keyUsage=makeKeyUsage(digital_signature=True)) + certificate = self.makeKDCCertificate(issuerCertificate, issuerKey) + self.assertRaisesRegex(KDCCertificateError, 'not allowed to sign certificates', verifyKDCCertificate, + certificate, [issuerCertificate], REALM, [issuerCertificate]) + + def test_pathLengthConstraintIsEnforced(self): + rootKey, rootCertificate = makeCertificate('Contoso Root CA', isCA=True, pathLength=0) + subKey, subCertificate = makeCertificate('Contoso Issuing CA', rootCertificate, rootKey, isCA=True) + certificate = self.makeKDCCertificate(subCertificate, subKey) + self.assertRaisesRegex(KDCCertificateError, 'intermediate certificates', verifyKDCCertificate, certificate, + [subCertificate], REALM, [rootCertificate]) + + +class ASExchangeTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.pki = PKI() + + def setUp(self): + self.sendReceive = kerberosv5.sendReceive + + def tearDown(self): + kerberosv5.sendReceive = self.sendReceive + + def credentials(self, **kwargs): + kwargs.setdefault('trustedCAs', [self.pki.caCertificate]) + return PKINITCredentials(self.pki.clientKey, self.pki.clientCertificate, [], **kwargs) + + def getTGT(self, kdc, credentials): + kerberosv5.sendReceive = kdc.sendReceive + clientName = Principal(CLIENT, type=constants.PrincipalNameType.NT_PRINCIPAL.value) + return PKINIT(clientName, REALM, credentials).getTGT() + + def test_diffieHellmanKeyDelivery(self): + kdc = KDC(self.pki) + tgt, cipher, replyKey, sessionKey = self.getTGT(kdc, self.credentials()) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + self.assertEqual(sessionKey.contents, kdc.sessionKey.contents) + self.assertEqual(cipher.enctype, Enctype.AES256) + self.assertEqual(decoder.decode(tgt, asn1Spec=AS_REP())[0]['crealm'], REALM) + + def test_diffieHellmanWithGroup2(self): + kdc = KDC(self.pki) + _, _, replyKey, _ = self.getTGT(kdc, self.credentials(dhGroup=2)) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_reusedDHKeysBringTheServerNonceIntoTheReplyKey(self): + kdc = KDC(self.pki, reuseDHKeys=True) + _, _, replyKey, _ = self.getTGT(kdc, self.credentials()) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_expiredReusedDHKeyIsRejected(self): + kdc = KDC(self.pki, reuseDHKeys=True, dhKeyLifetime=-60) + with self.assertRaisesRegex(PKINITError, 'expired'): + self.getTGT(kdc, self.credentials()) + + def test_reusedDHKeysWithoutServerNonceAreRejected(self): + kdc = KDC(self.pki, reuseDHKeys=True, serverDHNonce=b'') + with self.assertRaisesRegex(PKINITError, 'without sending a serverDHNonce'): + self.getTGT(kdc, self.credentials()) + + def test_reusedDHKeysWithANonZeroNonceAreRejected(self): + kdc = KDC(self.pki, reuseDHKeys=True, nonceOverride=1234) + with self.assertRaisesRegex(PKINITError, 'nonce does not match'): + self.getTGT(kdc, self.credentials()) + + def test_ellipticCurveKeyDelivery(self): + kdc = KDC(self.pki) + _, _, replyKey, sessionKey = self.getTGT(kdc, self.credentials(keyExchange='ecdh')) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + self.assertEqual(sessionKey.contents, kdc.sessionKey.contents) + + def test_publicKeyEncryptionKeyDelivery(self): + kdc = KDC(self.pki, useEncKeyPack=True) + _, _, replyKey, sessionKey = self.getTGT(kdc, self.credentials(keyExchange='rsa')) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + self.assertEqual(sessionKey.contents, kdc.sessionKey.contents) + + def test_publicKeyEncryptionWithTripleDES(self): + kdc = KDC(self.pki, useEncKeyPack=True, contentEncryption='des-ede3-cbc') + _, _, replyKey, _ = self.getTGT(kdc, self.credentials(keyExchange='rsa')) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_serviceTicketIsRequestedDirectly(self): + # -service of getTGT.py hands the SPN over as a plain string + kdc = KDC(self.pki) + kerberosv5.sendReceive = kdc.sendReceive + clientName = Principal(CLIENT, type=constants.PrincipalNameType.NT_PRINCIPAL.value) + _, _, replyKey, _ = PKINIT(clientName, REALM, self.credentials(), + serverName='cifs/dc01.contoso.com').getTGT() + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_aes128ReplyKey(self): + kdc = KDC(self.pki, enctype=Enctype.AES128) + _, _, replyKey, _ = self.getTGT(kdc, self.credentials()) + self.assertEqual(len(replyKey.contents), 16) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_rejectedDomainParametersAreRetried(self): + # The KDC refuses group 2 and advertises group 14 in TD-DH-PARAMETERS + kdc = KDC(self.pki, rejectDHGroup=2) + _, _, replyKey, _ = self.getTGT(kdc, self.credentials(dhGroup=2)) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_rejectedDomainParametersInTypedDataAreRetried(self): + # RFC 4556 3.2.2: Windows KDCs carry the accepted parameters in a TYPED-DATA + kdc = KDC(self.pki, rejectDHGroup=2, useTypedData=True) + _, _, replyKey, _ = self.getTGT(kdc, self.credentials(dhGroup=2)) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_rejectedCurveIsRetriedWithTheProposedOne(self): + # RFC 5349 4: the KDC may propose elliptic curves instead of MODP groups + kdc = KDC(self.pki, rejectCurve='P-256', proposeCurve='P-384') + _, _, replyKey, _ = self.getTGT(kdc, self.credentials(keyExchange='ecdh', curve='P-256')) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_rejectedModpGroupIsRetriedWithAProposedCurve(self): + kdc = KDC(self.pki, rejectDHGroup=2, proposeCurve='P-256') + _, _, replyKey, _ = self.getTGT(kdc, self.credentials(dhGroup=2)) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_unsupportedProposedParametersAreReported(self): + kdc = KDC(self.pki, rejectDHGroup=2, proposeCurve='sect571r1') + with self.assertRaisesRegex(PKINITError, 'did not propose any'): + self.getTGT(kdc, self.credentials(dhGroup=2)) + + def test_replayedNonceIsRejected(self): + kdc = KDC(self.pki, nonceOverride=1) + self.assertRaises(PKINITError, self.getTGT, kdc, self.credentials()) + + def test_kdcCertificateOfAnotherRealmIsRejected(self): + otherPki = PKI() + otherPki.clientKey, otherPki.clientCertificate = self.pki.clientKey, self.pki.clientCertificate + kdc = KDC(otherPki) + self.assertRaises(KDCCertificateError, self.getTGT, kdc, self.credentials()) + + def test_rejectedDigestIsRetriedWithSha1(self): + # RFC 4556 3.2.2: KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED lets the client retry with another digest + kdc = KDC(self.pki, rejectDigest='sha256') + _, _, replyKey, _ = self.getTGT(kdc, self.credentials()) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_rejectedSha1DigestIsNotRetried(self): + kdc = KDC(self.pki, rejectDigest='sha1') + self.assertRaises(kerberosv5.KerberosError, self.getTGT, kdc, self.credentials(digest='sha1')) + + def test_ocspResponseIsRequestedAndAccepted(self): + kdc = KDC(self.pki, ocspStatus=ocsp.OCSPCertStatus.GOOD) + _, _, replyKey, _ = self.getTGT(kdc, self.credentials(requestOCSP=True)) + self.assertTrue(kdc.ocspRequested, 'no PA-PK-OCSP-RESPONSE in the AS-REQ') + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_revokedKDCCertificateIsRejected(self): + kdc = KDC(self.pki, ocspStatus=ocsp.OCSPCertStatus.REVOKED) + self.assertRaises(KDCCertificateError, self.getTGT, kdc, self.credentials(requestOCSP=True)) + + def test_keyDeliveryMethodDowngradeIsRejected(self): + # The client asked for key agreement, the KDC answers with key transport + kdc = KDC(self.pki, useEncKeyPack=True) + with self.assertRaisesRegex(PKINITError, 'encrypted key pack to a Diffie-Hellman request'): + self.getTGT(kdc, self.credentials()) + + def test_keyAgreementReplyToAKeyTransportRequestIsRejected(self): + kdc = KDC(self.pki, answerDHWithoutRequest=True) + with self.assertRaisesRegex(PKINITError, 'Diffie-Hellman reply to a public key encryption request'): + self.getTGT(kdc, self.credentials(keyExchange='rsa')) + + def test_ocspResponseFromANonAuthoritativeResponderIsIgnored(self): + # A revoked status nobody delegated authority for must not be acted upon + otherPki = PKI() + kdc = KDC(self.pki, ocspStatus=ocsp.OCSPCertStatus.REVOKED, + ocspResponder=(otherPki.caKey, otherPki.caCertificate)) + _, _, replyKey, _ = self.getTGT(kdc, self.credentials(requestOCSP=True)) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_expiredOCSPResponseIsIgnored(self): + kdc = KDC(self.pki, ocspStatus=ocsp.OCSPCertStatus.REVOKED, ocspExpired=True) + _, _, replyKey, _ = self.getTGT(kdc, self.credentials(requestOCSP=True)) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_delegatedOCSPResponderIsAccepted(self): + responder = makeCertificate('Contoso OCSP', self.pki.caCertificate, self.pki.caKey, + extendedKeyUsage=['1.3.6.1.5.5.7.3.9']) + kdc = KDC(self.pki, ocspStatus=ocsp.OCSPCertStatus.REVOKED, ocspResponder=responder) + self.assertRaises(KDCCertificateError, self.getTGT, kdc, self.credentials(requestOCSP=True)) + + def test_missingOCSPResponseIsAnErrorWhenRequired(self): + kdc = KDC(self.pki) + self.assertRaisesRegex(KDCCertificateError, 'did not return a usable OCSP response', + self.getTGT, kdc, self.credentials(requireOCSP=True)) + + def test_missingOCSPResponseIsToleratedByDefault(self): + kdc = KDC(self.pki) + _, _, replyKey, _ = self.getTGT(kdc, self.credentials(requestOCSP=True)) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_getKerberosTGTUsesPKINITWithACertificate(self): + # The whole path an example script goes through: certificate to ccache + kdc = KDC(self.pki) + kerberosv5.sendReceive = kdc.sendReceive + clientName = Principal(CLIENT, type=constants.PrincipalNameType.NT_PRINCIPAL.value) + tgt, _, replyKey, _ = kerberosv5.getKerberosTGT(clientName, '', REALM, '', '', certificate=self.credentials()) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + ccache = CCache() + ccache.fromTGT(tgt, replyKey, replyKey) + credential = ccache.credentials[0] + self.assertEqual(credential['client'].prettyPrint(), b'%s@%s' % (CLIENT.encode(), REALM.encode())) + self.assertEqual(credential['server'].prettyPrint(), b'krbtgt/%s@%s' % (REALM.encode(), REALM.encode())) + + def test_kdcVerificationCanBeDisabled(self): + otherPki = PKI() + otherPki.clientKey, otherPki.clientCertificate = self.pki.clientKey, self.pki.clientCertificate + kdc = KDC(otherPki) + _, _, replyKey, _ = self.getTGT(kdc, self.credentials(verifyKDC=False)) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + +class CredentialsTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.pki = PKI() + + def test_upnIsReadFromTheCertificate(self): + credentials = PKINITCredentials(self.pki.clientKey, self.pki.clientCertificate) + self.assertEqual(credentials.getUPN(), '%s@contoso.com' % CLIENT) + self.assertEqual(credentials.getPrincipal(), '%s@contoso.com' % CLIENT) + + def test_kerberosPrincipalIsReadFromTheCertificate(self): + credentials = PKINITCredentials(self.pki.kdcKey, self.pki.kdcCertificate) + self.assertEqual(credentials.getPrincipal(), 'krbtgt/%s@%s' % (REALM, REALM)) + + def test_rootCertificatesAreNotSent(self): + credentials = PKINITCredentials(self.pki.clientKey, self.pki.clientCertificate, + [self.pki.caCertificate, self.pki.kdcCertificate]) + self.assertEqual(credentials.chain, [self.pki.kdcCertificate]) + + def test_unknownKeyExchangeIsRejected(self): + self.assertRaises(PKINITError, PKINITCredentials, self.pki.clientKey, self.pki.clientCertificate, + keyExchange='rc4') + + def test_pemFilesAreLoaded(self): + import os + import tempfile + certificates = self.pki.clientCertificate.public_bytes(serialization.Encoding.PEM) + \ + self.pki.caCertificate.public_bytes(serialization.Encoding.PEM) + key = self.pki.clientKey.private_bytes(serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption()) + certPath, keyPath = tempfile.mktemp(suffix='.crt'), tempfile.mktemp(suffix='.key') + try: + with open(certPath, 'wb') as fd: + fd.write(certificates) + with open(keyPath, 'wb') as fd: + fd.write(key) + credentials = PKINITCredentials.fromPEM(certPath, keyPath) + self.assertEqual(credentials.certificate, self.pki.clientCertificate) + # The root CA of the file is dropped, RFC 4556 3.2.1 forbids sending it + self.assertEqual(credentials.chain, []) + self.assertEqual(credentials.getUPN(), '%s@contoso.com' % CLIENT) + finally: + os.unlink(certPath) + os.unlink(keyPath) + + def test_pfxIsLoadedFromMemory(self): + data = serialization.pkcs12.serialize_key_and_certificates( + b'client', self.pki.clientKey, self.pki.clientCertificate, None, + serialization.BestAvailableEncryption(b'Passw0rd!')) + credentials = PKINITCredentials.fromPFXData(data, 'Passw0rd!') + self.assertEqual(credentials.certificate, self.pki.clientCertificate) + self.assertEqual(credentials.getUPN(), '%s@contoso.com' % CLIENT) + + def test_pemIsLoadedFromMemory(self): + certificate = self.pki.clientCertificate.public_bytes(serialization.Encoding.PEM) + key = self.pki.clientKey.private_bytes(serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption()) + credentials = PKINITCredentials.fromPEMData(certificate, key) + self.assertEqual(credentials.certificate, self.pki.clientCertificate) + + def test_pfxWithTheWrongPasswordIsReported(self): + data = serialization.pkcs12.serialize_key_and_certificates( + b'client', self.pki.clientKey, self.pki.clientCertificate, None, + serialization.BestAvailableEncryption(b'Passw0rd!')) + self.assertRaisesRegex(PKINITError, 'Could not load', PKINITCredentials.fromPFXData, data, 'wrong') + + def test_pfxRoundTrip(self): + import os + import tempfile + data = serialization.pkcs12.serialize_key_and_certificates( + b'client', self.pki.clientKey, self.pki.clientCertificate, [self.pki.caCertificate], + serialization.BestAvailableEncryption(b'Passw0rd!')) + handle, path = tempfile.mkstemp(suffix='.pfx') + try: + with os.fdopen(handle, 'wb') as fd: + fd.write(data) + credentials = PKINITCredentials.fromPFX(path, 'Passw0rd!') + self.assertEqual(credentials.certificate, self.pki.clientCertificate) + self.assertEqual(credentials.getUPN(), '%s@contoso.com' % CLIENT) + finally: + os.unlink(path) + + +class HostileKDCTests(unittest.TestCase): + """A KDC that answers malformed or degenerate replies must get a clean error, never a traceback.""" + + @classmethod + def setUpClass(cls): + cls.pki = PKI() + + def setUp(self): + self.sendReceive = kerberosv5.sendReceive + + def tearDown(self): + kerberosv5.sendReceive = self.sendReceive + + def getTGT(self, mutate, kdcKwargs=None, **credentialKwargs): + kdc = KDC(self.pki, **(kdcKwargs or {})) + original = kdc.sendReceive + + def sendReceive(data, host, kdcHost, port=88, timeout=None): + kdc.lastNonce = int(decoder.decode(data, asn1Spec=AS_REQ())[0]['req-body']['nonce']) + return mutate(kdc, original(data, host, kdcHost, port)) + + kerberosv5.sendReceive = sendReceive + credentials = PKINITCredentials(self.pki.clientKey, self.pki.clientCertificate, [], **credentialKwargs) + clientName = Principal(CLIENT, type=constants.PrincipalNameType.NT_PRINCIPAL.value) + return PKINIT(clientName, REALM, credentials).getTGT() + + def setPaPkAsRep(self, asRep, paPkAsRep): + for padata in asRep['padata']: + if int(padata['padata-type']) == constants.PreAuthenticationDataTypes.PA_PK_AS_REP.value: + padata['padata-value'] = paPkAsRep + return encoder.encode(asRep) + + def signedDHKeyInfo(self, kdc, subjectPublicKey): + keyInfo = KDCDHKeyInfo() + setComponent(keyInfo, 'subjectPublicKey', hexValue=hexlify(subjectPublicKey).decode('ascii')) + keyInfo['nonce'] = kdc.lastNonce + paPkAsRep = PA_PK_AS_REP() + dhRepInfo = paPkAsRep.setComponentByName('dhInfo').getComponentByName('dhInfo') + dhRepInfo['dhSignedData'] = buildSignedData(self.pki.kdcKey, self.pki.kdcCertificate, [], + ID_PKINIT_DHKEYDATA, encoder.encode(keyInfo), 'sha256') + return encoder.encode(paPkAsRep) + + def test_truncatedReplyIsReported(self): + with self.assertRaisesRegex(PKINITError, 'Could not parse the AS-REP'): + self.getTGT(lambda kdc, response: response[:40]) + + def test_replyThatIsNotAnAsRepIsReported(self): + with self.assertRaisesRegex(PKINITError, 'Could not parse the AS-REP'): + self.getTGT(lambda kdc, response: b'\x30\x03\x02\x01\x01') + + def test_unknownReplyEnctypeIsReported(self): + def mutate(kdc, response): + asRep = decoder.decode(response, asn1Spec=AS_REP())[0] + asRep['enc-part']['etype'] = 999 + return encoder.encode(asRep) + with self.assertRaisesRegex(PKINITError, 'unsupported encryption type 999'): + self.getTGT(mutate) + + def test_garbagePaPkAsRepIsReported(self): + def mutate(kdc, response): + return self.setPaPkAsRep(decoder.decode(response, asn1Spec=AS_REP())[0], b'\x04\x02\xff\xff') + with self.assertRaisesRegex(PKINITError, 'Could not parse the PA-PK-AS-REP'): + self.getTGT(mutate) + + def test_emptySignedDataIsReported(self): + def mutate(kdc, response): + paPkAsRep = PA_PK_AS_REP() + dhRepInfo = paPkAsRep.setComponentByName('dhInfo').getComponentByName('dhInfo') + dhRepInfo['dhSignedData'] = b'' + return self.setPaPkAsRep(decoder.decode(response, asn1Spec=AS_REP())[0], encoder.encode(paPkAsRep)) + with self.assertRaisesRegex(PKINITError, 'Could not parse the CMS ContentInfo'): + self.getTGT(mutate) + + def test_signedDataWithoutContentIsReported(self): + def mutate(kdc, response): + signedData = rfc5652.SignedData() + signedData['version'] = 3 + signedData['encapContentInfo']['eContentType'] = univ.ObjectIdentifier(ID_PKINIT_DHKEYDATA) + paPkAsRep = PA_PK_AS_REP() + dhRepInfo = paPkAsRep.setComponentByName('dhInfo').getComponentByName('dhInfo') + dhRepInfo['dhSignedData'] = buildContentInfo('1.2.840.113549.1.7.2', encoder.encode(signedData)) + return self.setPaPkAsRep(decoder.decode(response, asn1Spec=AS_REP())[0], encoder.encode(paPkAsRep)) + with self.assertRaisesRegex(PKINITError, 'carries no content'): + self.getTGT(mutate) + + def test_degenerateDiffieHellmanPublicValuesAreRejected(self): + prime = DH_GROUPS[14][0] + for value in (0, 1, prime - 1, prime, prime + 1): + def mutate(kdc, response, value=value): + return self.setPaPkAsRep(decoder.decode(response, asn1Spec=AS_REP())[0], + self.signedDHKeyInfo(kdc, encoder.encode(univ.Integer(value)))) + with self.assertRaisesRegex(PKINITError, 'invalid Diffie-Hellman public value'): + self.getTGT(mutate) + + def test_malformedDiffieHellmanPublicValueIsReported(self): + def mutate(kdc, response): + return self.setPaPkAsRep(decoder.decode(response, asn1Spec=AS_REP())[0], + self.signedDHKeyInfo(kdc, b'\xff\xff')) + with self.assertRaisesRegex(PKINITError, 'Could not parse the Diffie-Hellman public value'): + self.getTGT(mutate) + + def test_pointNotOnTheCurveIsRejected(self): + def mutate(kdc, response): + return self.setPaPkAsRep(decoder.decode(response, asn1Spec=AS_REP())[0], + self.signedDHKeyInfo(kdc, b'\x04' + b'\x01' * 64)) + with self.assertRaisesRegex(PKINITError, 'invalid P-256 public value'): + self.getTGT(mutate, keyExchange='ecdh') + + def test_malformedOCSPResponseIsIgnored(self): + def mutate(kdc, response): + asRep = decoder.decode(response, asn1Spec=AS_REP())[0] + position = len(asRep['padata']) + asRep['padata'][position] = univ.noValue + asRep['padata'][position]['padata-type'] = int( + constants.PreAuthenticationDataTypes.PA_PK_OCSP_RESPONSE.value) + asRep['padata'][position]['padata-value'] = b'\xff\xff\xff' + return encoder.encode(asRep) + self.getTGT(mutate, requestOCSP=True) + + def test_signedDataWithoutSignedAttributesIsRejected(self): + # RFC 4556 3.2.3.1: the content-type signed attribute must be present + def mutate(kdc, response): + asRep = decoder.decode(response, asn1Spec=AS_REP())[0] + keyInfo = KDCDHKeyInfo() + setComponent(keyInfo, 'subjectPublicKey', hexValue=hexlify(encoder.encode(univ.Integer(2))).decode()) + keyInfo['nonce'] = kdc.lastNonce + content = encoder.encode(keyInfo) + + signerInfo = rfc5652.SignerInfo() + signerInfo['version'] = 1 + signerInfo['sid'] = buildSignerIdentifier(self.pki.kdcCertificate) + signerInfo['digestAlgorithm'] = buildAlgorithmIdentifier('2.16.840.1.101.3.4.2.1') + signerInfo['signatureAlgorithm'] = getSignatureAlgorithm(self.pki.kdcKey, 'sha256') + signerInfo['signature'] = signData(self.pki.kdcKey, content, 'sha256') + + signedData = rfc5652.SignedData() + signedData['version'] = 3 + signedData['digestAlgorithms'].setComponentByPosition( + 0, buildAlgorithmIdentifier('2.16.840.1.101.3.4.2.1')) + signedData['encapContentInfo']['eContentType'] = univ.ObjectIdentifier(ID_PKINIT_DHKEYDATA) + signedData['encapContentInfo']['eContent'] = content + signedData['certificates'] = buildCertificateSet([self.pki.kdcCertificate]) + signedData['signerInfos'].setComponentByPosition(0, signerInfo) + + paPkAsRep = PA_PK_AS_REP() + dhRepInfo = paPkAsRep.setComponentByName('dhInfo').getComponentByName('dhInfo') + dhRepInfo['dhSignedData'] = buildContentInfo('1.2.840.113549.1.7.2', encoder.encode(signedData)) + return self.setPaPkAsRep(asRep, encoder.encode(paPkAsRep)) + with self.assertRaisesRegex(PKINITError, 'no signed attributes'): + self.getTGT(mutate) + + def patchEnvelopedData(self, patch): + """Return a mutation that rewrites the EnvelopedData of an encKeyPack reply.""" + def mutate(kdc, response): + asRep = decoder.decode(response, asn1Spec=AS_REP())[0] + for padata in asRep['padata']: + if int(padata['padata-type']) != constants.PreAuthenticationDataTypes.PA_PK_AS_REP.value: + continue + paPkAsRep = decoder.decode(padata['padata-value'], asn1Spec=PA_PK_AS_REP())[0] + contentInfo = decoder.decode(bytes(paPkAsRep.getComponent()), asn1Spec=rfc5652.ContentInfo())[0] + enveloped = decoder.decode(bytes(contentInfo['content']), asn1Spec=rfc5652.EnvelopedData())[0] + patch(enveloped) + newPack = PA_PK_AS_REP() + newPack['encKeyPack'] = buildContentInfo(ID_ENVELOPED_DATA, encoder.encode(enveloped)) + padata['padata-value'] = encoder.encode(newPack) + return encoder.encode(asRep) + return mutate + + def test_truncatedEnvelopedContentIsReported(self): + def patch(enveloped): + enveloped['encryptedContentInfo']['encryptedContent'] = b'\x01\x02\x03' + with self.assertRaisesRegex(PKINITError, 'Could not decrypt the enveloped content'): + self.getTGT(self.patchEnvelopedData(patch), {'useEncKeyPack': True}, keyExchange='rsa') + + def test_corruptedEncryptedKeyIsReported(self): + def patch(enveloped): + enveloped['recipientInfos'][0]['ktri']['encryptedKey'] = b'\x00' * 256 + with self.assertRaises(PKINITError): + self.getTGT(self.patchEnvelopedData(patch), {'useEncKeyPack': True}, keyExchange='rsa') + + def test_badInitializationVectorIsReported(self): + def patch(enveloped): + algorithm = enveloped['encryptedContentInfo']['contentEncryptionAlgorithm'] + algorithm['parameters'] = univ.Any(encoder.encode(univ.OctetString(b'\x00' * 3))) + with self.assertRaisesRegex(PKINITError, 'Could not decrypt the enveloped content'): + self.getTGT(self.patchEnvelopedData(patch), {'useEncKeyPack': True}, keyExchange='rsa') + + def test_envelopedDataWithoutRecipientIsReported(self): + def tlv(tag, payload): + return bytes([tag, len(payload)]) + payload + algorithm = tlv(0x30, bytes.fromhex('0609608648016503040102')) + encryptedContentInfo = tlv(0x30, bytes.fromhex('06092A864886F70D010701') + algorithm) + enveloped = tlv(0x30, tlv(0x02, b'\x00') + tlv(0x31, b'') + encryptedContentInfo) + with self.assertRaisesRegex(PKINITError, 'single recipientInfo'): + decryptEnvelopedData(buildContentInfo(ID_ENVELOPED_DATA, enveloped), self.pki.clientKey) + + def test_undecryptableReplyIsReported(self): + def mutate(kdc, response): + asRep = decoder.decode(response, asn1Spec=AS_REP())[0] + asRep['enc-part']['cipher'] = b'\x00' * 64 + return encoder.encode(asRep) + with self.assertRaisesRegex(PKINITError, 'does not decrypt the AS-REP'): + self.getTGT(mutate) + + +class FuzzedReplyTests(unittest.TestCase): + """Corrupting the bytes of a valid reply must never escape as an unrelated exception.""" + + @classmethod + def setUpClass(cls): + cls.pki = PKI() + + def setUp(self): + self.sendReceive = kerberosv5.sendReceive + + def tearDown(self): + kerberosv5.sendReceive = self.sendReceive + + def fuzz(self, keyExchange, kdcKwargs, iterations=150): + import random + random.seed('%s-pkinit' % keyExchange) + clientName = Principal(CLIENT, type=constants.PrincipalNameType.NT_PRINCIPAL.value) + for _ in range(iterations): + kdc = KDC(self.pki, **kdcKwargs) + original = kdc.sendReceive + + def sendReceive(data, host, kdcHost, port=88, timeout=None, original=original): + response = bytearray(original(data, host, kdcHost, port)) + for _ in range(random.randint(1, 12)): + response[random.randrange(len(response))] = random.randrange(256) + return bytes(response) + + kerberosv5.sendReceive = sendReceive + credentials = PKINITCredentials(self.pki.clientKey, self.pki.clientCertificate, [], + keyExchange=keyExchange, requestOCSP=True) + try: + PKINIT(clientName, REALM, credentials).getTGT() + except (PKINITError, kerberosv5.KerberosError): + pass + except Exception as e: + self.fail('a corrupted %s reply escaped as %s: %s' % (keyExchange, type(e).__name__, e)) + + def test_fuzzedDiffieHellmanReplies(self): + self.fuzz('dh', {}) + + def test_fuzzedEllipticCurveReplies(self): + self.fuzz('ecdh', {}) + + def test_fuzzedKeyTransportReplies(self): + self.fuzz('rsa', {'useEncKeyPack': True}) + + +if __name__ == '__main__': + unittest.main(verbosity=1) From 6fec50f8a7969e44d5d09e41f5648321979ec00e Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:11:43 +0200 Subject: [PATCH 02/10] Fix DiffieHellman ignoring an explicitly supplied generator --- impacket/krb5/pkinit.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/impacket/krb5/pkinit.py b/impacket/krb5/pkinit.py index 09901744e1..303c8af864 100644 --- a/impacket/krb5/pkinit.py +++ b/impacket/krb5/pkinit.py @@ -237,11 +237,16 @@ def octetstring2key(x, cipher): class DiffieHellman: """MODP Diffie-Hellman key agreement (RFC 4556 3.2.3.1).""" - def __init__(self, group=14, prime=None, generator=2): + def __init__(self, group=14, prime=None, generator=None): if prime is None: if group not in DH_GROUPS: raise PKINITError('Unsupported Diffie-Hellman group %s' % group) - prime, generator = DH_GROUPS[group] + # an explicit generator still takes precedence over the one of the group + prime, groupGenerator = DH_GROUPS[group] + if generator is None: + generator = groupGenerator + elif generator is None: + generator = 2 self.group = group self.prime = prime self.generator = generator From 784a3d8b6799864d6bbadcebeb0169681f8fa99f Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Sat, 17 Oct 2026 15:21:21 +0200 Subject: [PATCH 03/10] Send paChecksum2 so KDCs with SHA-1 disabled accept the AS-REQ --- impacket/krb5/asn1.py | 10 +++++++++- impacket/krb5/pkinit.py | 11 ++++++++++- tests/misc/test_pkinit.py | 30 ++++++++++++++++++++++++++---- 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/impacket/krb5/asn1.py b/impacket/krb5/asn1.py index 54360e7adb..f7d47616e2 100644 --- a/impacket/krb5/asn1.py +++ b/impacket/krb5/asn1.py @@ -600,12 +600,20 @@ class KRB5PrincipalName(univ.Sequence): _sequence_component('principalName', 1, PrincipalName()) ) +# draft-rische-kitten-pkinit-crypto-deprec: the checksum KDCs ask for once SHA-1 is disabled +class PAChecksum2(univ.Sequence): + componentType = namedtype.NamedTypes( + _sequence_component('checksum', 0, univ.OctetString()), + _sequence_component('algorithmIdentifier', 1, AlgorithmIdentifier()) + ) + class PKAuthenticator(univ.Sequence): componentType = namedtype.NamedTypes( _sequence_component('cusec', 0, Microseconds()), _sequence_component('ctime', 1, KerberosTime()), _sequence_component('nonce', 2, UInt32()), - _sequence_optional_component('paChecksum', 3, univ.OctetString()) + _sequence_optional_component('paChecksum', 3, univ.OctetString()), + _sequence_optional_component('paChecksum2', 5, PAChecksum2()) ) class AuthPack(univ.Sequence): diff --git a/impacket/krb5/pkinit.py b/impacket/krb5/pkinit.py index 303c8af864..c96d5dfb3a 100644 --- a/impacket/krb5/pkinit.py +++ b/impacket/krb5/pkinit.py @@ -94,6 +94,9 @@ SIGNATURE_OIDS[values[2]] = name SIGNATURE_OIDS[ID_RSA_ENCRYPTION] = None # digest carried by digestAlgorithm +# The draft mandates SHA-2 for paChecksum2, SHA-256 being the only digest every KDC has to support +PA_CHECKSUM2_DIGEST = 'sha256' + # MODP groups usable for the Diffie-Hellman key agreement method (RFC 4556 3.2.1), as (prime, generator) DH_GROUPS = { 2: (int( @@ -960,7 +963,13 @@ def buildAuthPack(self, reqBody): pkAuthenticator['ctime'] = KerberosTime.to_asn1(now) # Windows KDCs echo this nonce back as the AS-REP nonce, so it must match the KDC-REQ-BODY one pkAuthenticator['nonce'] = self.nonce - pkAuthenticator['paChecksum'] = sha1(getReqBodyBytes(reqBody)).digest() + reqBodyBytes = getReqBodyBytes(reqBody) + pkAuthenticator['paChecksum'] = sha1(reqBodyBytes).digest() + # KDCs with SHA-1 disabled reject the paChecksum alone with KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED + paChecksum2 = pkAuthenticator['paChecksum2'] + paChecksum2['checksum'] = DIGEST_ALGORITHMS[PA_CHECKSUM2_DIGEST][3](reqBodyBytes).digest() + # Filled in place: the component is context tagged, a plain AlgorithmIdentifier does not fit it + paChecksum2['algorithmIdentifier']['algorithm'] = univ.ObjectIdentifier(DIGEST_ALGORITHMS[PA_CHECKSUM2_DIGEST][0]) if self.keyExchange is not None: publicKeyInfo = self.keyExchange.getSubjectPublicKeyInfo() diff --git a/tests/misc/test_pkinit.py b/tests/misc/test_pkinit.py index ae0abc4f90..38fdf6185e 100644 --- a/tests/misc/test_pkinit.py +++ b/tests/misc/test_pkinit.py @@ -20,7 +20,7 @@ import datetime import unittest from binascii import hexlify, unhexlify -from hashlib import sha1 +from hashlib import sha1, sha256 from Cryptodome.Cipher import AES, DES3 from cryptography import x509 @@ -38,7 +38,7 @@ from impacket.krb5.asn1 import AS_REP, AS_REQ, AuthPack, EncASRepPart, KDCDHKeyInfo, METHOD_DATA, \ PA_PK_AS_REP, PA_PK_AS_REQ, PKOcspData, ReplyKeyPack, TD_DH_PARAMETERS, TYPED_DATA, seq_set, seq_set_iter from impacket.krb5.crypto import Cksumtype, Enctype, Key, _enctype_table, make_checksum -from impacket.krb5.pkinit import DH_GROUPS, DIGEST_ALGORITHMS, EC_CURVES, EC_CURVE_OIDS, ID_AES256_CBC, ID_DES_EDE3_CBC, \ +from impacket.krb5.pkinit import DH_GROUPS, DIGEST_ALGORITHMS, DIGEST_OIDS, EC_CURVES, EC_CURVE_OIDS, ID_AES256_CBC, ID_DES_EDE3_CBC, \ ID_ENVELOPED_DATA, decryptEnvelopedData, \ ID_DH_PUBLIC_NUMBER, ID_EC_PUBLIC_KEY, ID_MS_SAN_SC_LOGON_UPN, ID_PKINIT_AUTHDATA, \ ID_PKINIT_DHKEYDATA, ID_PKINIT_KP_KDC, ID_PKINIT_RKEYDATA, ID_PKINIT_SAN, ID_RSA_ENCRYPTION, DiffieHellman, \ @@ -170,8 +170,15 @@ def verifyRequest(self, asReq): content, certificate, _ = verifySignedData(bytes(paPkAsReq['signedAuthPack']), ID_PKINIT_AUTHDATA) authPack = decoder.decode(content, asn1Spec=AuthPack())[0] - expected = sha1(getReqBodyBytes(asReq['req-body'])).digest() - assert bytes(authPack['pkAuthenticator']['paChecksum']) == expected, 'bad paChecksum' + reqBodyBytes = getReqBodyBytes(asReq['req-body']) + assert bytes(authPack['pkAuthenticator']['paChecksum']) == sha1(reqBodyBytes).digest(), 'bad paChecksum' + + paChecksum2 = authPack['pkAuthenticator']['paChecksum2'] + assert paChecksum2.hasValue(), 'no paChecksum2 in the PKAuthenticator' + algorithm = paChecksum2['algorithmIdentifier'] + assert not algorithm['parameters'].hasValue(), 'the paChecksum2 digest carries parameters' + digest = DIGEST_OIDS[str(algorithm['algorithm'])] + assert bytes(paChecksum2['checksum']) == DIGEST_ALGORITHMS[digest][3](reqBodyBytes).digest(), 'bad paChecksum2' return authPack, certificate def buildDHInfo(self, authPack): @@ -794,6 +801,21 @@ def test_kdcVerificationCanBeDisabled(self): _, _, replyKey, _ = self.getTGT(kdc, self.credentials(verifyKDC=False)) self.assertEqual(replyKey.contents, kdc.replyKey.contents) + def test_paChecksum2IsASha256DigestOfTheRequestBody(self): + pkinit = PKINIT(Principal(CLIENT, type=constants.PrincipalNameType.NT_PRINCIPAL.value), REALM, + self.credentials()) + pkinit.keyExchange = pkinit.newKeyExchange() + asReq = decoder.decode(pkinit.buildAsReq(), asn1Spec=AS_REQ())[0] + padata = {int(entry['padata-type']): entry['padata-value'] for entry in asReq['padata']} + paPkAsReq = decoder.decode(padata[constants.PreAuthenticationDataTypes.PA_PK_AS_REQ.value], + asn1Spec=PA_PK_AS_REQ())[0] + content, _, _ = verifySignedData(bytes(paPkAsReq['signedAuthPack']), ID_PKINIT_AUTHDATA) + paChecksum2 = decoder.decode(content, asn1Spec=AuthPack())[0]['pkAuthenticator']['paChecksum2'] + + self.assertEqual(bytes(paChecksum2['checksum']), sha256(getReqBodyBytes(asReq['req-body'])).digest()) + self.assertEqual(str(paChecksum2['algorithmIdentifier']['algorithm']), DIGEST_ALGORITHMS['sha256'][0]) + self.assertFalse(paChecksum2['algorithmIdentifier']['parameters'].hasValue()) + class CredentialsTests(unittest.TestCase): @classmethod From 9a1d112a8f9c63763e91bf1f3cd6551a7d62d084 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Sat, 17 Oct 2026 15:58:00 +0200 Subject: [PATCH 04/10] Support the RFC 8070 PKINIT freshness extension --- impacket/krb5/asn1.py | 1 + impacket/krb5/constants.py | 1 + impacket/krb5/pkinit.py | 74 ++++++++++++++++++++++++++++---------- tests/misc/test_pkinit.py | 56 +++++++++++++++++++++++++++-- 4 files changed, 111 insertions(+), 21 deletions(-) diff --git a/impacket/krb5/asn1.py b/impacket/krb5/asn1.py index f7d47616e2..47f1dd43f3 100644 --- a/impacket/krb5/asn1.py +++ b/impacket/krb5/asn1.py @@ -613,6 +613,7 @@ class PKAuthenticator(univ.Sequence): _sequence_component('ctime', 1, KerberosTime()), _sequence_component('nonce', 2, UInt32()), _sequence_optional_component('paChecksum', 3, univ.OctetString()), + _sequence_optional_component('freshnessToken', 4, univ.OctetString()), _sequence_optional_component('paChecksum2', 5, PAChecksum2()) ) diff --git a/impacket/krb5/constants.py b/impacket/krb5/constants.py index d455e33431..3c76a45123 100644 --- a/impacket/krb5/constants.py +++ b/impacket/krb5/constants.py @@ -111,6 +111,7 @@ class PreAuthenticationDataTypes(Enum): PA_FX_FAST = 136 PA_FX_ERROR = 137 PA_ENCRYPTED_CHALLENGE = 138 + PA_AS_FRESHNESS = 150 KERB_KEY_LIST_REQ = 161 KERB_KEY_LIST_REP = 162 PA_SUPPORTED_ENCTYPES = 165 diff --git a/impacket/krb5/pkinit.py b/impacket/krb5/pkinit.py index c96d5dfb3a..c0a8388c38 100644 --- a/impacket/krb5/pkinit.py +++ b/impacket/krb5/pkinit.py @@ -44,7 +44,7 @@ from impacket import LOG from impacket.krb5 import constants from impacket.krb5.asn1 import AS_REP, AS_REQ, AuthPack, EncASRepPart, KDCDHKeyInfo, KERB_PA_PAC_REQUEST, \ - KRB5PrincipalName, METHOD_DATA, PA_PK_AS_REP, PA_PK_AS_REQ, PKOcspData, ReplyKeyPack, \ + KRB5PrincipalName, KRB_ERROR, METHOD_DATA, PA_PK_AS_REP, PA_PK_AS_REQ, PKOcspData, ReplyKeyPack, \ TD_DH_PARAMETERS, TYPED_DATA, seq_set, seq_set_iter from impacket.krb5.crypto import Cksumtype, Enctype, InvalidChecksum, Key, _enctype_table, verify_checksum from impacket.krb5.types import KerberosTime, Principal @@ -945,6 +945,7 @@ def __init__(self, clientName, domain, credentials, kdcHost=None, requestPAC=Tru self.digest = credentials.digest self.keyExchange = None self.nonce = 0 + self.freshnessToken = b'' self.asReq = b'' self.ocspResponses = [] @@ -963,6 +964,8 @@ def buildAuthPack(self, reqBody): pkAuthenticator['ctime'] = KerberosTime.to_asn1(now) # Windows KDCs echo this nonce back as the AS-REP nonce, so it must match the KDC-REQ-BODY one pkAuthenticator['nonce'] = self.nonce + if self.freshnessToken: + pkAuthenticator['freshnessToken'] = self.freshnessToken reqBodyBytes = getReqBodyBytes(reqBody) pkAuthenticator['paChecksum'] = sha1(reqBodyBytes).digest() # KDCs with SHA-1 disabled reject the paChecksum alone with KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED @@ -1023,19 +1026,17 @@ def buildAsReq(self): pacRequest = KERB_PA_PAC_REQUEST() pacRequest['include-pac'] = self.requestPAC - asReq['padata'] = univ.noValue - asReq['padata'][0] = univ.noValue - asReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PK_AS_REQ.value) - asReq['padata'][0]['padata-value'] = encoder.encode(paPkAsReq) - asReq['padata'][1] = univ.noValue - asReq['padata'][1]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value) - asReq['padata'][1]['padata-value'] = encoder.encode(pacRequest) - + padata = [(constants.PreAuthenticationDataTypes.PA_PK_AS_REQ.value, encoder.encode(paPkAsReq)), + (constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value, encoder.encode(pacRequest)), + (constants.PreAuthenticationDataTypes.PA_AS_FRESHNESS.value, b'')] # RFC 8070 2.1: an empty value advertises support if self.credentials.requestOCSP: - asReq['padata'][2] = univ.noValue - asReq['padata'][2]['padata-type'] = int( - constants.PreAuthenticationDataTypes.PA_PK_OCSP_RESPONSE.value) - asReq['padata'][2]['padata-value'] = encoder.encode(PKOcspData()) + padata.append((constants.PreAuthenticationDataTypes.PA_PK_OCSP_RESPONSE.value, encoder.encode(PKOcspData()))) + + asReq['padata'] = univ.noValue + for index, (padataType, padataValue) in enumerate(padata): + asReq['padata'][index] = univ.noValue + asReq['padata'][index]['padata-type'] = int(padataType) + asReq['padata'][index]['padata-value'] = padataValue return encoder.encode(asReq) @@ -1044,14 +1045,18 @@ def getTGT(self): from impacket.krb5.kerberosv5 import KerberosError, sendReceive self.keyExchange = self.newKeyExchange() - # One retry per recoverable error: rejected domain parameters and rejected digest (RFC 4556 3.2.2) - for attempt in range(3): + # One retry per recoverable error: rejected domain parameters, rejected digest (RFC 4556 3.2.2) + # and the freshness token a realm that requires it only hands out in an error (RFC 8070 2.4) + for attempt in range(4): self.asReq = self.buildAsReq() try: response = sendReceive(self.asReq, self.domain, self.kdcHost, timeout=self.timeout) - break + krbError = self.asKerberosError(response) + if krbError is None: + break + raise krbError except KerberosError as e: - if attempt == 2: + if attempt == 3: raise self.handleError(e) @@ -1072,8 +1077,22 @@ def getTGT(self): sessionKey = Key(sessionCipher.enctype, encASRepPart['key']['keyvalue'].asOctets()) return response, sessionCipher, replyKey, sessionKey + def asKerberosError(self, response): + """Return the KRB-ERROR a KDC reply holds, or None if the reply is an AS-REP. + + sendReceive hands KDC_ERR_PREAUTH_REQUIRED back instead of raising it, because the + password flow reads the salt from it. A realm that requires freshness answers our + AS-REQ with that very error, so the PKINIT client has to recognise it too. + """ + from impacket.krb5.kerberosv5 import KerberosError + try: + packet = decoder.decode(response, asn1Spec=KRB_ERROR())[0] + except PyAsn1Error: + return None + return KerberosError(packet=packet) + def handleError(self, error): - """Recover from the errors RFC 4556 3.2.2 lets the client retry after.""" + """Recover from the errors the client may retry after (RFC 4556 3.2.2, RFC 8070 2.4).""" errorCode = error.getErrorCode() if errorCode == constants.ErrorCodes.KDC_ERR_KEY_TOO_WEAK.value: # 65 is KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED in RFC 4556 3.1.3, not KDC_ERR_KEY_TOO_WEAK @@ -1084,6 +1103,15 @@ def handleError(self, error): raise error LOG.debug('KDC rejected the %s digest, retrying with sha1' % self.digest) self.digest = 'sha1' + elif errorCode in (constants.ErrorCodes.KDC_ERR_PREAUTH_REQUIRED.value, + constants.ErrorCodes.KDC_ERR_PREAUTH_FAILED.value, + constants.ErrorCodes.KDC_ERR_PREAUTH_EXPIRED.value): + # Windows answers KDC_ERR_PREAUTH_REQUIRED where RFC 8070 2.4 asks for KDC_ERR_PREAUTH_FAILED + freshnessToken = self.getFreshnessToken(error) + if not freshnessToken: + raise error + LOG.debug('The KDC requires a freshness token, retrying with the one it sent') + self.freshnessToken = freshnessToken elif errorCode in (constants.ErrorCodes.KDC_ERR_PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED.value, constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value) and self.credentials.keyExchange == 'rsa': # Windows KDCs implement no CMS algorithm for this method and answer KDC_ERR_ETYPE_NOSUPP @@ -1092,6 +1120,16 @@ def handleError(self, error): else: raise error + def getFreshnessToken(self, error): + """Return the freshness token of a KRB-ERROR, if it carries one (RFC 8070 2.4).""" + eData = error.getErrorPacket()['e-data'] + if not eData.hasValue(): + return b'' + for dataType, dataValue in self.parseErrorData(eData.asOctets()): + if dataType == constants.PreAuthenticationDataTypes.PA_AS_FRESHNESS.value: + return dataValue + return b'' + def getAcceptedKeyExchange(self, error): """Pick a key exchange from the domain parameters the KDC proposed. diff --git a/tests/misc/test_pkinit.py b/tests/misc/test_pkinit.py index 38fdf6185e..20ca5c8636 100644 --- a/tests/misc/test_pkinit.py +++ b/tests/misc/test_pkinit.py @@ -124,7 +124,8 @@ class KDC: def __init__(self, pki, enctype=Enctype.AES256, useEncKeyPack=False, rejectDHGroup=None, nonceOverride=None, rejectDigest=None, ocspStatus=None, contentEncryption='aes256-CBC', reuseDHKeys=False, dhKeyLifetime=3600, serverDHNonce=None, rejectCurve=None, proposeCurve=None, useTypedData=False, - ocspResponder=None, ocspExpired=False, answerDHWithoutRequest=False): + ocspResponder=None, ocspExpired=False, answerDHWithoutRequest=False, freshnessToken=None, + withholdFreshnessToken=False): self.pki = pki self.cipher = _enctype_table[enctype] self.useEncKeyPack = useEncKeyPack @@ -142,12 +143,17 @@ def __init__(self, pki, enctype=Enctype.AES256, useEncKeyPack=False, rejectDHGro self.ocspResponder = ocspResponder self.ocspExpired = ocspExpired self.answerDHWithoutRequest = answerDHWithoutRequest + self.freshnessToken = freshnessToken + self.withholdFreshnessToken = withholdFreshnessToken self.replyKey = None self.ocspRequested = False self.sessionKey = Key(enctype, b'S' * self.cipher.keysize) def sendReceive(self, data, host, kdcHost, port=88, timeout=None): asReq = decoder.decode(data, asn1Spec=AS_REQ())[0] + if self.freshnessToken is not None and not self.sentFreshnessToken(asReq): + # Windows returns this error instead of raising it, as sendReceive does for the password flow + return self.buildFreshnessError() authPack, clientCertificate = self.verifyRequest(asReq) if self.useEncKeyPack: @@ -329,7 +335,27 @@ def raiseDHParametersNotAccepted(self): errorData[0]['padata-value'] = accepted self.raiseError(constants.ErrorCodes.KDC_ERR_KEY_TOO_WEAK.value, encoder.encode(errorData)) - def raiseError(self, errorCode, eData=None): + def sentFreshnessToken(self, asReq): + padata = {int(entry['padata-type']): entry['padata-value'] for entry in asReq['padata']} + request = padata.get(constants.PreAuthenticationDataTypes.PA_PK_AS_REQ.value) + if request is None: + return False + paPkAsReq = decoder.decode(request, asn1Spec=PA_PK_AS_REQ())[0] + content, _, _ = verifySignedData(bytes(paPkAsReq['signedAuthPack']), ID_PKINIT_AUTHDATA) + authPack = decoder.decode(content, asn1Spec=AuthPack())[0] + freshnessToken = authPack['pkAuthenticator']['freshnessToken'] + return freshnessToken.hasValue() and bytes(freshnessToken) == self.freshnessToken + + def buildFreshnessError(self): + """Hand out a freshness token the way a realm that requires one does (RFC 8070 2.4).""" + errorData = METHOD_DATA() + errorData.setComponentByPosition(0, univ.noValue) + errorData[0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_AS_FRESHNESS.value) + errorData[0]['padata-value'] = b'' if self.withholdFreshnessToken else self.freshnessToken + return encoder.encode(self.buildError(constants.ErrorCodes.KDC_ERR_PREAUTH_REQUIRED.value, + encoder.encode(errorData))) + + def buildError(self, errorCode, eData=None): from impacket.krb5.asn1 import KRB_ERROR krbError = KRB_ERROR() @@ -343,7 +369,10 @@ def raiseError(self, errorCode, eData=None): Principal('krbtgt/%s' % REALM, type=constants.PrincipalNameType.NT_SRV_INST.value).components_to_asn1) if eData is not None: krbError['e-data'] = eData - raise kerberosv5.KerberosError(packet=krbError) + return krbError + + def raiseError(self, errorCode, eData=None): + raise kerberosv5.KerberosError(packet=self.buildError(errorCode, eData)) def buildOCSPResponse(self): """Build the OCSP response for the KDC certificate, as RFC 4557 3 allows.""" @@ -801,6 +830,27 @@ def test_kdcVerificationCanBeDisabled(self): _, _, replyKey, _ = self.getTGT(kdc, self.credentials(verifyKDC=False)) self.assertEqual(replyKey.contents, kdc.replyKey.contents) + def test_freshnessTokenIsSignedIntoTheRetriedRequest(self): + kdc = KDC(self.pki, freshnessToken=b'FRESH' * 8) + _, _, replyKey, _ = self.getTGT(kdc, self.credentials()) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_freshnessErrorWithoutATokenIsReported(self): + kdc = KDC(self.pki, freshnessToken=b'FRESH' * 8, withholdFreshnessToken=True) + with self.assertRaises(kerberosv5.KerberosError) as raised: + self.getTGT(kdc, self.credentials()) + self.assertEqual(raised.exception.getErrorCode(), constants.ErrorCodes.KDC_ERR_PREAUTH_REQUIRED.value) + + def test_freshnessSupportIsAdvertised(self): + pkinit = PKINIT(Principal(CLIENT, type=constants.PrincipalNameType.NT_PRINCIPAL.value), REALM, + self.credentials()) + pkinit.keyExchange = pkinit.newKeyExchange() + asReq = decoder.decode(pkinit.buildAsReq(), asn1Spec=AS_REQ())[0] + padata = {int(entry['padata-type']): entry['padata-value'] for entry in asReq['padata']} + + self.assertIn(constants.PreAuthenticationDataTypes.PA_AS_FRESHNESS.value, padata) + self.assertEqual(bytes(padata[constants.PreAuthenticationDataTypes.PA_AS_FRESHNESS.value]), b'') + def test_paChecksum2IsASha256DigestOfTheRequestBody(self): pkinit = PKINIT(Principal(CLIENT, type=constants.PrincipalNameType.NT_PRINCIPAL.value), REALM, self.credentials()) From 7e15a2f1e63c477dd1be729185b7034c769962ff Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:16:54 +0200 Subject: [PATCH 05/10] Report a wrong PFX password as such instead of blaming legacy algorithms --- examples/getTGT.py | 9 +++++++-- impacket/krb5/pkinit.py | 5 +++-- tests/misc/test_pkinit.py | 4 +++- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/examples/getTGT.py b/examples/getTGT.py index 2c786b323f..71ceda62f0 100755 --- a/examples/getTGT.py +++ b/examples/getTGT.py @@ -30,7 +30,7 @@ from impacket.examples.utils import parse_identity from impacket.krb5.kerberosv5 import getKerberosTGT from impacket.krb5 import constants -from impacket.krb5.pkinit import DH_GROUPS, EC_CURVES, PKINITCredentials, readPEMCertificates +from impacket.krb5.pkinit import DH_GROUPS, EC_CURVES, PKINITCredentials, PKINITError, readPEMCertificates from impacket.krb5.types import Principal @@ -149,7 +149,12 @@ def run(self): # Init the example's logger theme logger.init(options.ts, options.debug) - certificate = GETTGT.loadCertificate(options) + try: + certificate = GETTGT.loadCertificate(options) + except (PKINITError, OSError) as e: + logging.critical('Could not load the certificate: %s' % e) + sys.exit(1) + if certificate is not None: options.no_pass = True diff --git a/impacket/krb5/pkinit.py b/impacket/krb5/pkinit.py index c0a8388c38..1cf48ff963 100644 --- a/impacket/krb5/pkinit.py +++ b/impacket/krb5/pkinit.py @@ -874,8 +874,9 @@ def fromPFXData(cls, data, password=None, source='the PFX data', **kwargs): try: privateKey, certificate, chain = pkcs12.load_key_and_certificates(data, password or None) except ValueError as e: - raise PKINITError('Could not load %s: %s. Certificates encrypted with legacy algorithms must be ' - 'converted first, e.g. openssl pkcs12 -in old.pfx -out new.pfx -legacy' % (source, e)) + # cryptography reports a wrong password and an unsupported encryption algorithm with the same error + raise PKINITError('Could not load %s: %s. Check the password, a file using legacy algorithms has to be ' + 'converted, e.g. openssl pkcs12 -in old.pfx -legacy -nodes -out new.pem' % (source, e)) if privateKey is None or certificate is None: raise PKINITError('%s does not hold both a certificate and its private key' % source.capitalize()) return cls(privateKey, certificate, chain, **kwargs) diff --git a/tests/misc/test_pkinit.py b/tests/misc/test_pkinit.py index 20ca5c8636..f04624eb04 100644 --- a/tests/misc/test_pkinit.py +++ b/tests/misc/test_pkinit.py @@ -933,7 +933,9 @@ def test_pfxWithTheWrongPasswordIsReported(self): data = serialization.pkcs12.serialize_key_and_certificates( b'client', self.pki.clientKey, self.pki.clientCertificate, None, serialization.BestAvailableEncryption(b'Passw0rd!')) - self.assertRaisesRegex(PKINITError, 'Could not load', PKINITCredentials.fromPFXData, data, 'wrong') + # A legacy encryption algorithm raises the very same ValueError, so the message must not blame one + self.assertRaisesRegex(PKINITError, 'Could not load.*Check the password', + PKINITCredentials.fromPFXData, data, 'wrong') def test_pfxRoundTrip(self): import os From e9317805de7325258e4870a14562cdf332e4f9c4 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:22:03 +0200 Subject: [PATCH 06/10] Point the shadow credentials attack at getTGT.py for the TGT --- impacket/examples/ntlmrelayx/attacks/ldapattack.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/impacket/examples/ntlmrelayx/attacks/ldapattack.py b/impacket/examples/ntlmrelayx/attacks/ldapattack.py index 7c50ba7ca2..c8ca61b347 100644 --- a/impacket/examples/ntlmrelayx/attacks/ldapattack.py +++ b/impacket/examples/ntlmrelayx/attacks/ldapattack.py @@ -353,9 +353,8 @@ def shadowCredentialsAttack(self, domainDumper): shadow_credentials.exportPEM(certificate,key,path_to_files=path) LOG.info("Saved PEM certificate at path: %s" % path + "_cert.pem") LOG.info("Saved PEM private key at path: %s" % path + "_priv.pem") - LOG.info("A TGT can now be obtained with https://github.com/dirkjanm/PKINITtools") LOG.info("Run the following command to obtain a TGT") - LOG.info("python3 PKINITtools/gettgtpkinit.py -cert-pem %s_cert.pem -key-pem %s_priv.pem %s/%s %s.ccache" % (path, path, domain, currentShadowCredentialsTarget, path)) + LOG.info("python3 getTGT.py -cert-pem %s_cert.pem -key-pem %s_priv.pem %s/%s" % (path, path, domain, currentShadowCredentialsTarget)) elif self.config.ShadowCredentialsExportType == "PFX": if self.config.ShadowCredentialsPFXPassword is None: password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(20)) @@ -365,9 +364,8 @@ def shadowCredentialsAttack(self, domainDumper): shadow_credentials.exportPFX(certificate,key,password=password, path_to_file=path) LOG.info("Saved PFX (#PKCS12) certificate & key at path: %s" % path + ".pfx") LOG.info("Must be used with password: %s" % password) - LOG.info("A TGT can now be obtained with https://github.com/dirkjanm/PKINITtools") LOG.info("Run the following command to obtain a TGT") - LOG.info("python3 PKINITtools/gettgtpkinit.py -cert-pfx %s.pfx -pfx-pass %s %s/%s %s.ccache" % (path, password, domain, currentShadowCredentialsTarget, path)) + LOG.info("python3 getTGT.py -cert-pfx %s.pfx -pfx-pass %s %s/%s" % (path, password, domain, currentShadowCredentialsTarget)) delegatePerformed.append(currentShadowCredentialsTarget) else: self._handleShadowCredentialModifyError() From 3e62768ac04d3d9d797a820ea36e462eb80675c5 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:06:19 +0200 Subject: [PATCH 07/10] Validate the KDC path when -ca-cert holds a DER certificate --- examples/getTGT.py | 7 +++++-- impacket/krb5/pkinit.py | 11 +++++++++++ tests/misc/test_pkinit.py | 17 ++++++++++++++++- 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/examples/getTGT.py b/examples/getTGT.py index 71ceda62f0..c7329afe8b 100755 --- a/examples/getTGT.py +++ b/examples/getTGT.py @@ -30,7 +30,7 @@ from impacket.examples.utils import parse_identity from impacket.krb5.kerberosv5 import getKerberosTGT from impacket.krb5 import constants -from impacket.krb5.pkinit import DH_GROUPS, EC_CURVES, PKINITCredentials, PKINITError, readPEMCertificates +from impacket.krb5.pkinit import DH_GROUPS, EC_CURVES, PKINITCredentials, PKINITError, readCertificates from impacket.krb5.types import Principal @@ -44,7 +44,10 @@ def loadCertificate(options): trustedCAs = [] if options.ca_cert is not None: with open(options.ca_cert, 'rb') as fd: - trustedCAs = readPEMCertificates(fd.read()) + trustedCAs = readCertificates(fd.read()) + # Without this the KDC certification path would silently go unchecked, as if -ca-cert was not given + if not trustedCAs: + raise PKINITError('No PEM or DER certificate found in the CA file %s' % options.ca_cert) settings = {'keyExchange': options.key_exchange, 'dhGroup': options.dh_group, 'curve': options.curve, 'trustedCAs': trustedCAs, 'verifyKDC': not options.no_verify_kdc, diff --git a/impacket/krb5/pkinit.py b/impacket/krb5/pkinit.py index 1cf48ff963..6e3108147e 100644 --- a/impacket/krb5/pkinit.py +++ b/impacket/krb5/pkinit.py @@ -915,6 +915,17 @@ def getPrincipal(self): return self.getUPN() +def readCertificates(data): + """Read a PEM certificate bundle, or the single DER certificate AD CS publishes for its CAs.""" + certificates = readPEMCertificates(data) + if certificates: + return certificates + try: + return [x509.load_der_x509_certificate(data)] + except ValueError: + return [] + + def readPEMCertificates(data): certificates = [] marker = b'-----BEGIN CERTIFICATE-----' diff --git a/tests/misc/test_pkinit.py b/tests/misc/test_pkinit.py index f04624eb04..ddb37a3cd6 100644 --- a/tests/misc/test_pkinit.py +++ b/tests/misc/test_pkinit.py @@ -44,7 +44,8 @@ ID_PKINIT_DHKEYDATA, ID_PKINIT_KP_KDC, ID_PKINIT_RKEYDATA, ID_PKINIT_SAN, ID_RSA_ENCRYPTION, DiffieHellman, \ EllipticCurveDiffieHellman, KDCCertificateError, PKINIT, PKINITCredentials, PKINITError, buildAlgorithmIdentifier, \ buildCertificateSet, buildContentInfo, buildSignedData, getReqBodyBytes, getSignatureAlgorithm,\ - buildSignerIdentifier, signData, octetstring2key, parseSignedData, verifyKDCCertificate, verifySignedData + buildSignerIdentifier, signData, octetstring2key, parseSignedData, readCertificates, verifyKDCCertificate, \ + verifySignedData from impacket.krb5.types import KerberosTime, Principal REALM = 'CONTOSO.COM' @@ -954,6 +955,20 @@ def test_pfxRoundTrip(self): os.unlink(path) + def test_derCertificateIsRead(self): + # AD CS publishes its CA certificate in DER, giving an empty bundle before it was handled + der = self.pki.caCertificate.public_bytes(serialization.Encoding.DER) + self.assertEqual(readCertificates(der), [self.pki.caCertificate]) + + def test_pemBundleIsRead(self): + pem = b''.join(certificate.public_bytes(serialization.Encoding.PEM) + for certificate in (self.pki.caCertificate, self.pki.clientCertificate)) + self.assertEqual(readCertificates(pem), [self.pki.caCertificate, self.pki.clientCertificate]) + + def test_fileHoldingNoCertificateIsReadAsEmpty(self): + self.assertEqual(readCertificates(b'not a certificate at all'), []) + + class HostileKDCTests(unittest.TestCase): """A KDC that answers malformed or degenerate replies must get a clean error, never a traceback.""" From 54269e18bc6049b84370058eed8d8583f5dfbc6f Mon Sep 17 00:00:00 2001 From: Kali Date: Wed, 28 Oct 2026 02:07:31 -0300 Subject: [PATCH 08/10] Fix PKINIT parsing of oversized ASN.1 lengths --- impacket/krb5/pkinit.py | 2 +- tests/misc/test_pkinit.py | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/impacket/krb5/pkinit.py b/impacket/krb5/pkinit.py index 6e3108147e..b0519ae90b 100644 --- a/impacket/krb5/pkinit.py +++ b/impacket/krb5/pkinit.py @@ -185,7 +185,7 @@ class KDCCertificateError(PKINITError): # Malformed input does not consistently raise PyAsn1Error: pyasn1 lets plain builtin errors through PARSE_ERRORS = (PyAsn1Error, x509.InvalidVersion, x509.DuplicateExtension, x509.UnsupportedGeneralNameType, - UnsupportedAlgorithm, KeyError, IndexError, TypeError, ValueError) + UnsupportedAlgorithm, KeyError, IndexError, TypeError, ValueError, OverflowError) def decodeASN1(data, asn1Spec, description): diff --git a/tests/misc/test_pkinit.py b/tests/misc/test_pkinit.py index ddb37a3cd6..1e0f42b9bc 100644 --- a/tests/misc/test_pkinit.py +++ b/tests/misc/test_pkinit.py @@ -39,7 +39,7 @@ PA_PK_AS_REP, PA_PK_AS_REQ, PKOcspData, ReplyKeyPack, TD_DH_PARAMETERS, TYPED_DATA, seq_set, seq_set_iter from impacket.krb5.crypto import Cksumtype, Enctype, Key, _enctype_table, make_checksum from impacket.krb5.pkinit import DH_GROUPS, DIGEST_ALGORITHMS, DIGEST_OIDS, EC_CURVES, EC_CURVE_OIDS, ID_AES256_CBC, ID_DES_EDE3_CBC, \ - ID_ENVELOPED_DATA, decryptEnvelopedData, \ + ID_ENVELOPED_DATA, decodeASN1, decryptEnvelopedData, \ ID_DH_PUBLIC_NUMBER, ID_EC_PUBLIC_KEY, ID_MS_SAN_SC_LOGON_UPN, ID_PKINIT_AUTHDATA, \ ID_PKINIT_DHKEYDATA, ID_PKINIT_KP_KDC, ID_PKINIT_RKEYDATA, ID_PKINIT_SAN, ID_RSA_ENCRYPTION, DiffieHellman, \ EllipticCurveDiffieHellman, KDCCertificateError, PKINIT, PKINITCredentials, PKINITError, buildAlgorithmIdentifier, \ @@ -1174,6 +1174,13 @@ def mutate(kdc, response): self.getTGT(mutate) +class ASN1DecodingTests(unittest.TestCase): + def test_oversizedLengthRaisesPKINITError(self): + payload = b'\x04\x89' + b'\xff' * 9 + with self.assertRaisesRegex(PKINITError, 'Could not parse the oversized length'): + decodeASN1(payload, univ.OctetString(), 'oversized length') + + class FuzzedReplyTests(unittest.TestCase): """Corrupting the bytes of a valid reply must never escape as an unrelated exception.""" From b1f0ec6698f877c1bd7712ed2a72ed74a5a10757 Mon Sep 17 00:00:00 2001 From: Kali Date: Wed, 28 Oct 2026 10:37:58 -0300 Subject: [PATCH 09/10] Fix RSA PKINIT interoperability with Windows --- examples/getTGT.py | 2 +- impacket/krb5/pkinit.py | 36 +++++++++++++++++++---- tests/misc/test_pkinit.py | 60 ++++++++++++++++++++++++++++++++------- 3 files changed, 82 insertions(+), 16 deletions(-) diff --git a/examples/getTGT.py b/examples/getTGT.py index c7329afe8b..7968d5db65 100755 --- a/examples/getTGT.py +++ b/examples/getTGT.py @@ -126,7 +126,7 @@ def run(self): group.add_argument('-key-pem', action='store', metavar="FILE", help='Client private key in PEM format') group.add_argument('-key-exchange', action='store', choices=['dh', 'ecdh', 'rsa'], default='dh', help='AS reply key delivery method: Diffie-Hellman (default), its elliptic curve variant ' - '(RFC 5349) or public key encryption') + '(RFC 5349) or RSA/CMS public key encryption') group.add_argument('-dh-group', action='store', type=int, choices=sorted(DH_GROUPS), default=14, help='MODP group to use for the Diffie-Hellman key agreement, default is 14 (2048 bits)') group.add_argument('-curve', action='store', choices=sorted(EC_CURVES), default='P-256', diff --git a/impacket/krb5/pkinit.py b/impacket/krb5/pkinit.py index b0519ae90b..b75da909c5 100644 --- a/impacket/krb5/pkinit.py +++ b/impacket/krb5/pkinit.py @@ -28,6 +28,7 @@ import os from binascii import hexlify from hashlib import sha1, sha256, sha384, sha512 +from hmac import compare_digest from Cryptodome.Cipher import AES, DES3 from cryptography import x509 @@ -97,6 +98,10 @@ # The draft mandates SHA-2 for paChecksum2, SHA-256 being the only digest every KDC has to support PA_CHECKSUM2_DIGEST = 'sha256' +# RFC 4556 3.1.4 CMS capability identifiers carried in the AS-REQ etype field. They advertise CMS +# algorithms and must not be used as EncryptedData encryption types. +PKINIT_RSA_CMS_ETYPES = (13, 15, 11) # rsaEncryption, des-ede3-cbc, sha-1WithRSAEncryption + # MODP groups usable for the Diffie-Hellman key agreement method (RFC 4556 3.2.1), as (prime, generator) DH_GROUPS = { 2: (int( @@ -173,6 +178,7 @@ } KEY_USAGE_AS_REQ_CHECKSUM = 6 +CKSUMTYPE_SHA1 = 14 # sha1 (unkeyed), used by Windows for ReplyKeyPack.asChecksum class PKINITError(Exception): @@ -552,6 +558,13 @@ def verifySignedData(data, expectedContentType): return content, certificate, certificates +def wrapDERSequenceContents(contents): + """Restore a DER SEQUENCE around its already encoded value octets.""" + sequence = univ.Sequence() + sequence.setComponentByPosition(0, univ.Any(contents)) + return encoder.encode(sequence) + + def getCertificateValidity(certificate): try: return certificate.not_valid_before_utc, certificate.not_valid_after_utc @@ -954,6 +967,9 @@ def __init__(self, clientName, domain, credentials, kdcHost=None, requestPAC=Tru int(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value), int(constants.EncryptionTypes.rc4_hmac.value), ) + if credentials.keyExchange == 'rsa': + self.supportedCiphers = tuple(self.supportedCiphers) + tuple( + value for value in PKINIT_RSA_CMS_ETYPES if value not in self.supportedCiphers) self.digest = credentials.digest self.keyExchange = None self.nonce = 0 @@ -1258,8 +1274,12 @@ def getReplyKeyFromEncKeyPack(self, encKeyPack, cipher): if self.keyExchange is not None: raise PKINITError('The KDC answered with an encrypted key pack to a Diffie-Hellman request') - content, certificate, certificates = verifySignedData( - decryptEnvelopedData(encKeyPack, self.credentials.privateKey), ID_PKINIT_RKEYDATA) + # EncryptedContentInfo.contentType is id-signedData, so its plaintext holds the value octets of + # SignedData: neither its SEQUENCE tag and length nor an outer ContentInfo are encrypted. + signedDataContents = decryptEnvelopedData(encKeyPack, self.credentials.privateKey) + signedData = wrapDERSequenceContents(signedDataContents) + contentInfo = buildContentInfo(ID_SIGNED_DATA, signedData) + content, certificate, certificates = verifySignedData(contentInfo, ID_PKINIT_RKEYDATA) self.checkKDCCertificate(certificate, certificates) replyKeyPack = decodeASN1(content, ReplyKeyPack(), 'ReplyKeyPack') @@ -1271,12 +1291,18 @@ def getReplyKeyFromEncKeyPack(self, encKeyPack, cipher): checksum = replyKeyPack['asChecksum'] cksumtype = int(checksum['cksumtype']) + checksumValue = checksum['checksum'].asOctets() + if cksumtype == CKSUMTYPE_SHA1: + # Windows uses the unkeyed SHA-1 checksum here. It is still verified and is covered by the + # KDC signature over ReplyKeyPack. + if not compare_digest(checksumValue, sha1(self.asReq).digest()): + raise PKINITError('The SHA-1 asChecksum of the ReplyKeyPack does not match our AS-REQ') + return replyKey if cksumtype != CHECKSUM_FOR_ENCTYPE.get(enctype): raise PKINITError('The asChecksum uses checksum type %d, which is not the required one for the reply key' % cksumtype) try: - verify_checksum(cksumtype, replyKey, KEY_USAGE_AS_REQ_CHECKSUM, self.asReq, - checksum['checksum'].asOctets()) + verify_checksum(cksumtype, replyKey, KEY_USAGE_AS_REQ_CHECKSUM, self.asReq, checksumValue) except InvalidChecksum: raise PKINITError('The asChecksum of the ReplyKeyPack does not match our AS-REQ') return replyKey @@ -1326,4 +1352,4 @@ def getKerberosTGTPKINIT(clientName, domain, credentials, kdcHost=None, requestP """ pkinit = PKINIT(clientName, domain, credentials, kdcHost=kdcHost, requestPAC=requestPAC, serverName=serverName, supportedCiphers=supportedCiphers, timeout=timeout) - return pkinit.getTGT() \ No newline at end of file + return pkinit.getTGT() diff --git a/tests/misc/test_pkinit.py b/tests/misc/test_pkinit.py index 1e0f42b9bc..885c8521f8 100644 --- a/tests/misc/test_pkinit.py +++ b/tests/misc/test_pkinit.py @@ -38,11 +38,11 @@ from impacket.krb5.asn1 import AS_REP, AS_REQ, AuthPack, EncASRepPart, KDCDHKeyInfo, METHOD_DATA, \ PA_PK_AS_REP, PA_PK_AS_REQ, PKOcspData, ReplyKeyPack, TD_DH_PARAMETERS, TYPED_DATA, seq_set, seq_set_iter from impacket.krb5.crypto import Cksumtype, Enctype, Key, _enctype_table, make_checksum -from impacket.krb5.pkinit import DH_GROUPS, DIGEST_ALGORITHMS, DIGEST_OIDS, EC_CURVES, EC_CURVE_OIDS, ID_AES256_CBC, ID_DES_EDE3_CBC, \ +from impacket.krb5.pkinit import CKSUMTYPE_SHA1, DH_GROUPS, DIGEST_ALGORITHMS, DIGEST_OIDS, EC_CURVES, EC_CURVE_OIDS, ID_AES256_CBC, ID_DES_EDE3_CBC, \ ID_ENVELOPED_DATA, decodeASN1, decryptEnvelopedData, \ ID_DH_PUBLIC_NUMBER, ID_EC_PUBLIC_KEY, ID_MS_SAN_SC_LOGON_UPN, ID_PKINIT_AUTHDATA, \ ID_PKINIT_DHKEYDATA, ID_PKINIT_KP_KDC, ID_PKINIT_RKEYDATA, ID_PKINIT_SAN, ID_RSA_ENCRYPTION, DiffieHellman, \ - EllipticCurveDiffieHellman, KDCCertificateError, PKINIT, PKINITCredentials, PKINITError, buildAlgorithmIdentifier, \ + EllipticCurveDiffieHellman, KDCCertificateError, PKINIT, PKINITCredentials, PKINITError, PKINIT_RSA_CMS_ETYPES, buildAlgorithmIdentifier, \ buildCertificateSet, buildContentInfo, buildSignedData, getReqBodyBytes, getSignatureAlgorithm,\ buildSignerIdentifier, signData, octetstring2key, parseSignedData, readCertificates, verifyKDCCertificate, \ verifySignedData @@ -61,6 +61,21 @@ def setComponent(sequence, name, **kwargs): sequence[name] = sequence[name].clone(**kwargs) +def getDERContents(value): + """Return the value octets of one definite-length DER value.""" + assert len(value) >= 2, 'truncated DER value' + lengthOctet = value[1] + if lengthOctet < 128: + headerLength, length = 2, lengthOctet + else: + lengthOctets = lengthOctet & 0x7f + assert lengthOctets and len(value) >= 2 + lengthOctets, 'invalid DER length' + headerLength = 2 + lengthOctets + length = int.from_bytes(value[2:headerLength], 'big') + assert headerLength + length == len(value), 'invalid DER size' + return value[headerLength:] + + def makeKerberosPrincipalName(realm, components): from impacket.krb5.asn1 import KRB5PrincipalName principalName = KRB5PrincipalName() @@ -126,7 +141,7 @@ def __init__(self, pki, enctype=Enctype.AES256, useEncKeyPack=False, rejectDHGro rejectDigest=None, ocspStatus=None, contentEncryption='aes256-CBC', reuseDHKeys=False, dhKeyLifetime=3600, serverDHNonce=None, rejectCurve=None, proposeCurve=None, useTypedData=False, ocspResponder=None, ocspExpired=False, answerDHWithoutRequest=False, freshnessToken=None, - withholdFreshnessToken=False): + withholdFreshnessToken=False, unkeyedReplyChecksum=False, invalidReplyChecksum=False): self.pki = pki self.cipher = _enctype_table[enctype] self.useEncKeyPack = useEncKeyPack @@ -146,12 +161,16 @@ def __init__(self, pki, enctype=Enctype.AES256, useEncKeyPack=False, rejectDHGro self.answerDHWithoutRequest = answerDHWithoutRequest self.freshnessToken = freshnessToken self.withholdFreshnessToken = withholdFreshnessToken + self.unkeyedReplyChecksum = unkeyedReplyChecksum + self.invalidReplyChecksum = invalidReplyChecksum self.replyKey = None self.ocspRequested = False + self.requestedEtypes = [] self.sessionKey = Key(enctype, b'S' * self.cipher.keysize) def sendReceive(self, data, host, kdcHost, port=88, timeout=None): asReq = decoder.decode(data, asn1Spec=AS_REQ())[0] + self.requestedEtypes = [int(value) for value in asReq['req-body']['etype']] if self.freshnessToken is not None and not self.sentFreshnessToken(asReq): # Windows returns this error instead of raising it, as sendReceive does for the password flow return self.buildFreshnessError() @@ -255,13 +274,22 @@ def buildEncKeyPack(self, asReq, clientCertificate): replyKeyPack['replyKey']['keytype'] = self.replyKey.enctype replyKeyPack['replyKey']['keyvalue'] = self.replyKey.contents # key usage 6 - cksumtype = {Enctype.AES256: Cksumtype.SHA1_AES256, Enctype.AES128: Cksumtype.SHA1_AES128, - Enctype.RC4: Cksumtype.HMAC_MD5}[self.cipher.enctype] + if self.unkeyedReplyChecksum: + cksumtype = CKSUMTYPE_SHA1 + checksum = sha1(asReq).digest() + else: + cksumtype = {Enctype.AES256: Cksumtype.SHA1_AES256, Enctype.AES128: Cksumtype.SHA1_AES128, + Enctype.RC4: Cksumtype.HMAC_MD5}[self.cipher.enctype] + checksum = make_checksum(cksumtype, self.replyKey, 6, asReq) + if self.invalidReplyChecksum: + checksum = bytes([checksum[0] ^ 1]) + checksum[1:] replyKeyPack['asChecksum']['cksumtype'] = cksumtype - replyKeyPack['asChecksum']['checksum'] = make_checksum(cksumtype, self.replyKey, 6, asReq) + replyKeyPack['asChecksum']['checksum'] = checksum - signedData = buildSignedData(self.pki.kdcKey, self.pki.kdcCertificate, [], ID_PKINIT_RKEYDATA, - encoder.encode(replyKeyPack), 'sha256') + signedDataInfo = buildSignedData(self.pki.kdcKey, self.pki.kdcCertificate, [], ID_PKINIT_RKEYDATA, + encoder.encode(replyKeyPack), 'sha256') + contentInfo = decoder.decode(signedDataInfo, asn1Spec=rfc5652.ContentInfo())[0] + signedDataContents = getDERContents(bytes(contentInfo['content'])) if self.contentEncryption == 'des-ede3-cbc': contentEncryptionKey, initializationVector, blockSize = b'KEY' * 8, b'IV' * 4, 8 @@ -271,8 +299,8 @@ def buildEncKeyPack(self, asReq, clientCertificate): contentEncryptionKey, initializationVector, blockSize = b'K' * 32, b'I' * 16, 16 algorithm = AES.new(contentEncryptionKey, AES.MODE_CBC, initializationVector) algorithmOid = ID_AES256_CBC - padLength = blockSize - len(signedData) % blockSize - encryptedContent = algorithm.encrypt(signedData + bytes([padLength]) * padLength) + padLength = blockSize - len(signedDataContents) % blockSize + encryptedContent = algorithm.encrypt(signedDataContents + bytes([padLength]) * padLength) recipientInfo = rfc5652.KeyTransRecipientInfo() recipientInfo['version'] = 0 @@ -654,6 +682,7 @@ def test_diffieHellmanKeyDelivery(self): self.assertEqual(sessionKey.contents, kdc.sessionKey.contents) self.assertEqual(cipher.enctype, Enctype.AES256) self.assertEqual(decoder.decode(tgt, asn1Spec=AS_REP())[0]['crealm'], REALM) + self.assertFalse(set(PKINIT_RSA_CMS_ETYPES) & set(kdc.requestedEtypes)) def test_diffieHellmanWithGroup2(self): kdc = KDC(self.pki) @@ -691,6 +720,17 @@ def test_publicKeyEncryptionKeyDelivery(self): _, _, replyKey, sessionKey = self.getTGT(kdc, self.credentials(keyExchange='rsa')) self.assertEqual(replyKey.contents, kdc.replyKey.contents) self.assertEqual(sessionKey.contents, kdc.sessionKey.contents) + self.assertEqual(kdc.requestedEtypes[-len(PKINIT_RSA_CMS_ETYPES):], list(PKINIT_RSA_CMS_ETYPES)) + + def test_publicKeyEncryptionWithWindowsChecksum(self): + kdc = KDC(self.pki, useEncKeyPack=True, unkeyedReplyChecksum=True) + _, _, replyKey, _ = self.getTGT(kdc, self.credentials(keyExchange='rsa')) + self.assertEqual(replyKey.contents, kdc.replyKey.contents) + + def test_invalidWindowsChecksumIsRejected(self): + kdc = KDC(self.pki, useEncKeyPack=True, unkeyedReplyChecksum=True, invalidReplyChecksum=True) + with self.assertRaisesRegex(PKINITError, 'SHA-1 asChecksum'): + self.getTGT(kdc, self.credentials(keyExchange='rsa')) def test_publicKeyEncryptionWithTripleDES(self): kdc = KDC(self.pki, useEncKeyPack=True, contentEncryption='des-ede3-cbc') From 7adb664c0e64924484956fb52b1d29b18e936195 Mon Sep 17 00:00:00 2001 From: Kali Date: Wed, 28 Oct 2026 15:59:19 -0300 Subject: [PATCH 10/10] Fix PKINIT certificate issuer selection --- impacket/krb5/pkinit.py | 36 ++++++++++++++++++++++++++---------- tests/misc/test_pkinit.py | 13 +++++++++++++ 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/impacket/krb5/pkinit.py b/impacket/krb5/pkinit.py index b75da909c5..c41c3a1967 100644 --- a/impacket/krb5/pkinit.py +++ b/impacket/krb5/pkinit.py @@ -728,19 +728,35 @@ def verifyCertificateChain(certificate, intermediates, anchors): if not notBefore <= now <= notAfter: raise KDCCertificateError('Certificate "%s" is not valid at this time' % getCertificateName(current)) - issuers = [anchor for anchor in anchors if anchor.subject == current.issuer] - if issuers: - verifyCertificateAuthority(issuers[0], pathLength) - verifyCertificateSignature(current, issuers[0]) + candidateError = None + for issuer in anchors: + if issuer.subject != current.issuer: + continue + try: + verifyCertificateAuthority(issuer, pathLength) + verifyCertificateSignature(current, issuer) + except KDCCertificateError as e: + candidateError = e + continue return - issuers = [intermediate for intermediate in intermediates if intermediate.subject == current.issuer] - if not issuers: + + for issuer in intermediates: + if issuer.subject != current.issuer: + continue + try: + verifyCertificateAuthority(issuer, pathLength) + verifyCertificateSignature(current, issuer) + except KDCCertificateError as e: + candidateError = e + continue + current = issuer + pathLength += 1 + break + else: + if candidateError is not None: + raise candidateError raise KDCCertificateError('Cannot build a certification path for "%s", issuer "%s" is unknown' % (getCertificateName(current), current.issuer.rfc4514_string())) - verifyCertificateAuthority(issuers[0], pathLength) - verifyCertificateSignature(current, issuers[0]) - current = issuers[0] - pathLength += 1 raise KDCCertificateError('Certification path for "%s" is looping' % getCertificateName(certificate)) diff --git a/tests/misc/test_pkinit.py b/tests/misc/test_pkinit.py index 885c8521f8..57e2ddf07a 100644 --- a/tests/misc/test_pkinit.py +++ b/tests/misc/test_pkinit.py @@ -613,6 +613,19 @@ def test_untrustedIssuerIsRejected(self): def test_pathIsNotValidatedWithoutAnchor(self): verifyKDCCertificate(self.pki.kdcCertificate, [], REALM, []) + def test_allMatchingTrustAnchorsAreTried(self): + _, wrongAnchor = makeCertificate('Contoso Root CA', isCA=True) + verifyKDCCertificate(self.pki.kdcCertificate, [], REALM, + [wrongAnchor, self.pki.caCertificate]) + + def test_allMatchingIntermediatesAreTried(self): + rootKey, rootCertificate = makeCertificate('Contoso Root CA', isCA=True) + _, wrongIntermediate = makeCertificate('Contoso Issuing CA', rootCertificate, rootKey, isCA=True) + intermediateKey, intermediateCertificate = makeCertificate( + 'Contoso Issuing CA', rootCertificate, rootKey, isCA=True) + certificate = self.makeKDCCertificate(intermediateCertificate, intermediateKey) + verifyKDCCertificate(certificate, [wrongIntermediate, intermediateCertificate], REALM, [rootCertificate]) + def makeKDCCertificate(self, issuerCertificate, issuerKey): return makeCertificate('dc01.contoso.com', issuerCertificate, issuerKey, otherName=x509.OtherName(x509.ObjectIdentifier(ID_PKINIT_SAN),