How to use the impacket.LOG function in impacket

To help you get started, we’ve selected a few impacket examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ropnop / impacket_static_binaries / impacket / krb5 / keytab.py View on Github external
def getKey(self, principal, specificEncType=None, ignoreRealm=True):
        principal = b(principal.upper())
        if ignoreRealm:
            principal = principal.split(b'@')[0]
        matching_keys = {}
        for entry in self.entries:
            entry_principal = entry.main_part['principal'].prettyPrint().upper()
            if entry_principal == principal or (ignoreRealm and entry_principal.split(b'@')[0] == principal):
                keytype = entry.main_part["keyblock"]["keytype"]
                if keytype == specificEncType:
                    LOG.debug('Returning %s key for %s' % (entry.main_part['keyblock'].prettyKeytype(),
                                                           entry.main_part['principal'].prettyPrint()))
                    return entry.main_part["keyblock"]
                elif specificEncType is None:
                    matching_keys[keytype] = entry

        if specificEncType is None and matching_keys:
            for preference in self.GetkeyEnctypePreference:
                if preference in matching_keys:
                    entry = matching_keys[preference]
                    LOG.debug('Returning %s key for %s' % (entry.main_part['keyblock'].prettyKeytype(),
                                                           entry.main_part['principal'].prettyPrint()))
                    return entry.main_part["keyblock"]

        LOG.debug('Principal %s not found in keytab' % principal)
        return None
github Coalfire-Research / Slackor / impacket / impacket / examples / ntlmrelayx / servers / httprelayserver.py View on Github external
def do_GET(self):
            messageType = 0
            if self.server.config.mode == 'REDIRECT':
                self.do_SMBREDIRECT()
                return

            LOG.info('HTTPD: Client requested path: %s' % self.path.lower())

            # Serve WPAD if:
            # - The client requests it
            # - A WPAD host was provided in the command line options
            # - The client has not exceeded the wpad_auth_num threshold yet
            if self.path.lower() == '/wpad.dat' and self.server.config.serve_wpad and self.should_serve_wpad(self.client_address[0]):
                LOG.info('HTTPD: Serving PAC file to client %s' % self.client_address[0])
                self.serve_wpad()
                return

            # Determine if the user is connecting to our server directly or attempts to use it as a proxy
            if self.command == 'CONNECT' or (len(self.path) > 4 and self.path[:4].lower() == 'http'):
                proxy = True
            else:
                proxy = False

            if PY2:
                proxyAuthHeader = self.headers.getheader('Proxy-Authorization')
                autorizationHeader = self.headers.getheader('Authorization')
            else:
                proxyAuthHeader = self.headers.get('Proxy-Authorization')
                autorizationHeader = self.headers.get('Authorization')
github SecureAuthCorp / impacket / impacket / crypto.py View on Github external
#   RFC 4615 implementation (https://www.ietf.org/rfc/rfc4615.txt)
#
#   NIST SP 800-108 Section 5.1, with PRF HMAC-SHA256 implementation
#   (https://tools.ietf.org/html/draft-irtf-cfrg-kdf-uses-00#ref-SP800-108)
#
#   [MS-LSAD] Section 5.1.2
#   [MS-SAMR] Section 2.2.11.1.1

from __future__ import division
from __future__ import print_function
from impacket import LOG
try:
    from Cryptodome.Cipher import DES, AES
except Exception:
    LOG.error("Warning: You don't have any crypto installed. You need pycryptodomex")
    LOG.error("See https://pypi.org/project/pycryptodomex/")
from struct import pack, unpack
from impacket.structure import Structure
import hmac, hashlib
from six import b

def Generate_Subkey(K):

#   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   +                    Algorithm Generate_Subkey                      +
#   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   +                                                                   +
#   +   Input    : K (128-bit key)                                      +
#   +   Output   : K1 (128-bit first subkey)                            +
#   +              K2 (128-bit second subkey)                           +
#   +-------------------------------------------------------------------+
#   +                                                                   +
github Coalfire-Research / Slackor / impacket / impacket / examples / os_ident.py View on Github external
if self.seq_num_responses < 2:
            return nmap1_seq.TS_SEQ_UNKNOWN

        # Battle plan:
        # 1) Compute average increments per second, and variance in incr. per second.
        # 2) If any are 0, set to constant.
        # 3) If variance is high, set to random incr. [ skip for now ]
        # 4) if ~10/second, set to appropriate thing.
        # 5) Same with ~100/s.

        avg_freq = 0.0
        for i in xrange(0, self.seq_num_responses - 1):
            dhz = self.ts_diffs[i] / self.time_diffs[i]
            avg_freq += dhz / (self.seq_num_responses - 1)

        LOG.info("The avg TCP TS HZ is: %f" % avg_freq)

        if 0 < avg_freq < 3.9:
            return nmap1_seq.TS_SEQ_2HZ
        if 85 < avg_freq < 115:
            return nmap1_seq.TS_SEQ_100HZ
        if 900 < avg_freq < 1100:
            return nmap1_seq.TS_SEQ_1000HZ

        return nmap1_seq.TS_SEQ_UNKNOWN
github SecureAuthCorp / impacket / impacket / tds.py View on Github external
record = TDS_ENVCHANGE_VARCHAR(key['Data'])
                        if record['OldValue'] == '':
                            record['OldValue'] = 'None'.encode('utf-16le')
                        elif record['NewValue'] == '':
                            record['NewValue'] = 'None'.encode('utf-16le')
                        if key['Type'] == TDS_ENVCHANGE_DATABASE:
                            _type = 'DATABASE'
                        elif key['Type'] == TDS_ENVCHANGE_LANGUAGE:
                            _type = 'LANGUAGE'
                        elif key['Type'] == TDS_ENVCHANGE_CHARSET:
                            _type = 'CHARSET'
                        elif key['Type'] == TDS_ENVCHANGE_PACKETSIZE:
                            _type = 'PACKETSIZE'
                        else:
                            _type = "%d" % key['Type']                 
                        LOG.info("ENVCHANGE(%s): Old Value: %s, New Value: %s" % (_type,record['OldValue'].decode('utf-16le'), record['NewValue'].decode('utf-16le')))
github dirkjanm / krbrelayx / lib / clients / __init__.py View on Github external
pluginClasses = set()
        try:
            if hasattr(module,'PROTOCOL_CLIENT_CLASSES'):
                for pluginClass in module.PROTOCOL_CLIENT_CLASSES:
                    pluginClasses.add(getattr(module, pluginClass))
            else:
                pluginClasses.add(getattr(module, getattr(module, 'PROTOCOL_CLIENT_CLASS')))
        except Exception as e:
            LOG.debug(e)
            pass

        for pluginClass in pluginClasses:
            LOG.info('Protocol Client %s loaded..' % pluginClass.PLUGIN_NAME)
            PROTOCOL_CLIENTS[pluginClass.PLUGIN_NAME] = pluginClass
    except Exception as e:
        LOG.debug(str(e))
github SecureAuthCorp / impacket / impacket / winregistry.py View on Github external
def __init__(self, hive, isRemote = False):
        self.__hive = hive
        if isRemote is True:
            self.fd = self.__hive
            self.__hive.open()
        else:
            self.fd = open(hive,'rb')
        data = self.fd.read(4096)
        self.__regf = REG_REGF(data)
        self.indent = ''
        self.rootKey = self.__findRootKey()
        if self.rootKey is None:
            LOG.error("Can't find root key!")
        elif self.__regf['MajorVersion'] != 1 and self.__regf['MinorVersion'] > 5:
            LOG.warning("Unsupported version (%d.%d) - things might not work!" % (self.__regf['MajorVersion'], self.__regf['MinorVersion']))
github SecureAuthCorp / impacket / impacket / smbconnection.py View on Github external
from impacket.krb5 import constants

        self._kdcHost = kdcHost
        self._useCache = useCache

        if TGT is not None or TGS is not None:
            useCache = False

        if useCache is True:
            try:
                ccache = CCache.loadFile(os.getenv('KRB5CCNAME'))
            except:
                # No cache present
                pass
            else:
                LOG.debug("Using Kerberos Cache: %s" % os.getenv('KRB5CCNAME'))
                # retrieve domain information from CCache file if needed
                if domain == '':
                    domain = ccache.principal.realm['data'].decode('utf-8')
                    LOG.debug('Domain retrieved from CCache: %s' % domain)

                principal = 'cifs/%s@%s' % (self.getRemoteName().upper(), domain.upper())
                creds = ccache.getCredential(principal)
                if creds is None:
                    # Let's try for the TGT and go from there
                    principal = 'krbtgt/%s@%s' % (domain.upper(),domain.upper())
                    creds =  ccache.getCredential(principal)
                    if creds is not None:
                        TGT = creds.toTGT()
                        LOG.debug('Using TGT from cache')
                    else:
                        LOG.debug("No valid credentials found in cache. ")
github ropnop / impacket_static_binaries / impacket / examples / secretsdump.py View on Github external
def __printSecret(self, name, secretItem):
        # Based on [MS-LSAD] section 3.1.1.4

        # First off, let's discard NULL secrets.
        if len(secretItem) == 0:
            LOG.debug('Discarding secret %s, NULL Data' % name)
            return

        # We might have secrets with zero
        if secretItem.startswith(b'\x00\x00'):
            LOG.debug('Discarding secret %s, all zeros' % name)
            return

        upperName = name.upper()

        LOG.info('%s ' % name)

        secret = ''

        if upperName.startswith('_SC_'):
            # Service name, a password might be there
            # Let's first try to decode the secret
            try:
                strDecoded = secretItem.decode('utf-16le')
            except:
                pass
            else:
                # We have to get the account the service
                # runs under
                if hasattr(self.__remoteOps, 'getServiceAccount'):
                    account = self.__remoteOps.getServiceAccount(name[4:])
                    if account is None:
github Coalfire-Research / Slackor / impacket / impacket / examples / ntlmrelayx / servers / httprelayserver.py View on Github external
def run(self):
        LOG.info("Setting up HTTP Server")

        if self.config.listeningPort:
            httpport = self.config.listeningPort
        else:
            httpport = 80

        # changed to read from the interfaceIP set in the configuration
        self.server = self.HTTPServer((self.config.interfaceIp, httpport), self.HTTPHandler, self.config)

        try:
             self.server.serve_forever()
        except KeyboardInterrupt:
             pass
        LOG.info('Shutting down HTTP Server')
        self.server.server_close()