from impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS
from impacket.krb5.types import Principal
from impacket.krb5 import constants
from binascii import unhexlify
def authenticate_kerberos(username, domain, password=None, nthash=None):
"""
Authenticate using Kerberos and obtain service ticket.
Args:
username: User principal name
domain: Kerberos realm
password: Cleartext password (optional)
nthash: NTLM hash (optional)
Returns:
Tuple of (tgt, tgs, sessionKey)
"""
# Create client principal
clientName = Principal(
username,
type=constants.PrincipalNameType.NT_PRINCIPAL.value
)
# Convert hash if provided
if nthash and isinstance(nthash, str):
nthash = unhexlify(nthash)
# Request TGT
tgt, cipher, oldKey, tgtSessionKey = getKerberosTGT(
clientName=clientName,
password=password or '',
domain=domain,
lmhash=b'',
nthash=nthash or b'',
kdcHost=f'dc.{domain.lower()}'
)
# Request service ticket
serverName = Principal(
f'cifs/server.{domain.lower()}',
type=constants.PrincipalNameType.NT_SRV_INST.value
)
tgs, cipher, oldKey, tgsSessionKey = getKerberosTGS(
serverName=serverName,
domain=domain,
kdcHost=f'dc.{domain.lower()}',
tgt=tgt,
cipher=cipher,
sessionKey=tgtSessionKey
)
return tgt, tgs, tgsSessionKey
# Usage
tgt, tgs, sessionKey = authenticate_kerberos(
username='jdoe',
domain='CORP.LOCAL',
password='SecurePass123'
)