Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 75 additions & 5 deletions examples/getTGT.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -29,11 +30,37 @@
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, readCertificates
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 = 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,
'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
Expand All @@ -43,6 +70,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(':')

Expand All @@ -63,7 +91,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__':
Expand All @@ -89,29 +118,70 @@ 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 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',
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)

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

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:
Expand Down
6 changes: 2 additions & 4 deletions impacket/examples/ntlmrelayx/attacks/ldapattack.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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()
Expand Down
111 changes: 108 additions & 3 deletions impacket/krb5/asn1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -556,4 +569,96 @@ 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())
)
)

# 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())
)

# 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('freshnessToken', 4, univ.OctetString()),
_sequence_optional_component('paChecksum2', 5, PAChecksum2())
)

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()
6 changes: 5 additions & 1 deletion impacket/krb5/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -102,13 +103,15 @@ 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
PA_FX_COOKIE = 133
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
Expand Down Expand Up @@ -141,7 +144,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
Expand Down
7 changes: 6 additions & 1 deletion impacket/krb5/kerberosv5.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading
Loading