Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def getCredential(self, server, anySPN=True):
for c in self.credentials:
if c['server'].prettyPrint().upper() == b(server.upper()) or c['server'].prettyPrint().upper().split(b'@')[0] == b(server.upper())\
or c['server'].prettyPrint().upper().split(b'@')[0] == b(server.upper().split('@')[0]):
LOG.debug('Returning cached credential for %s' % c['server'].prettyPrint().upper())
return c
LOG.debug('SPN %s not found in cache' % server.upper())
if anySPN is True:
LOG.debug('AnySPN is True, looking for another suitable SPN')
for c in self.credentials:
# Let's search for any TGT/TGS that matches the server w/o the SPN's service type/port, returns
# the first one
if c['server'].prettyPrint().find(b'/') >=0:
# Let's take the port out for comparison
cachedSPN = (c['server'].prettyPrint().upper().split(b'/')[1].split(b'@')[0].split(b':')[0] + b'@' + c['server'].prettyPrint().upper().split(b'/')[1].split(b'@')[1])
searchSPN = '%s@%s' % (server.upper().split('/')[1].split('@')[0].split(':')[0],
server.upper().split('/')[1].split('@')[1])
if cachedSPN == b(searchSPN):
LOG.debug('Returning cached credential for %s' % c['server'].prettyPrint().upper())
return c
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. ")
else:
TGS = creds.toTGS(principal)
LOG.debug('Using TGS from cache')
# retrieve user information from CCache file if needed
if user == '' and creds is not None:
user = creds['client'].prettyPrint().split(b'@')[0]
LOG.debug('Username retrieved from CCache: %s' % user)
elif user == '' and len(ccache.principal.components) > 0:
user = ccache.principal.components[0]['data']
LOG.debug('Username retrieved from CCache: %s' % user)
while True:
try:
if self.getDialect() == smb.SMB_DIALECT:
return self._SMBConnection.kerberos_login(user, password, domain, lmhash, nthash, aesKey, kdcHost,
TGT, TGS)
return self._SMBConnection.kerberosLogin(user, password, domain, lmhash, nthash, aesKey, kdcHost, TGT,
TGS)
def __getLSASecretKey(self):
LOG.debug('Decrypting LSA Key')
# Let's try the key post XP
value = self.getValue('\\Policy\\PolEKList\\default')
if value is None:
LOG.debug('PolEKList not found, trying PolSecretEncryptionKey')
# Second chance
value = self.getValue('\\Policy\\PolSecretEncryptionKey\\default')
self.__vistaStyle = False
if value is None:
# No way :(
return None
self.__decryptLSA(value[1])
# Default computer SPNs
spns = [
'HOST/%s' % computerHostname,
'HOST/%s.%s' % (computerHostname, domain),
'RestrictedKrbHost/%s' % computerHostname,
'RestrictedKrbHost/%s.%s' % (computerHostname, domain),
]
ucd = {
'dnsHostName': '%s.%s' % (computerHostname, domain),
'userAccountControl': 4096,
'servicePrincipalName': spns,
'sAMAccountName': newComputer,
'unicodePwd': '"{}"'.format(newPassword).encode('utf-16-le')
}
LOG.debug('New computer info %s', ucd)
LOG.info('Attempting to create computer in: %s', parent)
res = self.client.add(newComputerDn.decode('utf-8'), ['top','person','organizationalPerson','user','computer'], ucd)
if not res:
# Adding computers requires LDAPS
if self.client.result['result'] == RESULT_UNWILLING_TO_PERFORM and not self.client.server.ssl:
LOG.error('Failed to add a new computer. The server denied the operation. Try relaying to LDAP with TLS enabled (ldaps) or escalating an existing account.')
else:
LOG.error('Failed to add a new computer: %s' % str(self.client.result))
return False
else:
LOG.info('Adding new computer with username: %s and password: %s result: OK' % (newComputer, newPassword))
alreadyAddedComputer = True
# Return the SAM name
return newComputer
def __getNLKMSecret(self):
LOG.debug('Decrypting NL$KM')
value = self.getValue('\\Policy\\Secrets\\NL$KM\\CurrVal\\default')
if value is None:
raise Exception("Couldn't get NL$KM value")
if self.__vistaStyle is True:
record = LSA_SECRET(value[1])
tmpKey = self.__sha256(self.__LSAKey, record['EncryptedData'][:32])
self.__NKLMKey = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:])
else:
self.__NKLMKey = self.__decryptSecret(self.__LSAKey, value[1])
server.activeRelays[target][port]['data'] = data
# Let's store the protocol scheme, needed be used later when trying to find the right socks relay server to use
server.activeRelays[target][port]['scheme'] = scheme
# Default values in case somebody asks while we're gettting the data
server.activeRelays[target][port][userName]['isAdmin'] = 'N/A'
# Do we have admin access in this connection?
try:
LOG.debug("Checking admin status for user %s" % str(userName))
isAdmin = client.isAdmin()
server.activeRelays[target][port][userName]['isAdmin'] = isAdmin
except Exception as e:
# Method not implemented
server.activeRelays[target][port][userName]['isAdmin'] = 'N/A'
pass
LOG.debug("isAdmin returned: %s" % server.activeRelays[target][port][userName]['isAdmin'])
else:
LOG.info('Relay connection for %s at %s(%d) already exists. Discarding' % (userName, target, port))
client.killConnection()
def __getitem__(self, key):
if key == 'Data':
try:
return ''.join([chr(i) for i in self.fields[key]])
except ValueError:
# We might have Unicode chars in here, let's use unichr instead
LOG.debug('ValueError exception on %s' % self.fields[key])
LOG.debug('Switching to unichr()')
return ''.join([unichr(i) for i in self.fields[key]])
else:
return NDR.__getitem__(self,key)
def __getBlock(self, offset):
self.fd.seek(4096+offset,0)
sizeBytes = self.fd.read(4)
data = sizeBytes + self.fd.read(unpack('
if file.find('__') >=0 or os.path.splitext(file)[1] == '.pyc':
continue
__import__(__package__ + '.' + os.path.splitext(file)[0])
module = sys.modules[__package__ + '.' + os.path.splitext(file)[0]]
try:
pluginClasses = set()
try:
if hasattr(module,'PROTOCOL_ATTACK_CLASSES'):
# Multiple classes
for pluginClass in module.PROTOCOL_ATTACK_CLASSES:
pluginClasses.add(getattr(module, pluginClass))
else:
# Single class
pluginClasses.add(getattr(module, getattr(module, 'PROTOCOL_ATTACK_CLASS')))
except Exception, e:
LOG.debug(e)
pass
for pluginClass in pluginClasses:
for pluginName in pluginClass.PLUGIN_NAMES:
LOG.debug('Protocol Attack %s loaded..' % pluginName)
PROTOCOL_ATTACKS[pluginName] = pluginClass
except Exception, e:
LOG.debug(str(e))