本文整理汇总了Python中impacket.smbconnection.SessionError方法的典型用法代码示例。如果您正苦于以下问题:Python smbconnection.SessionError方法的具体用法?Python smbconnection.SessionError怎么用?Python smbconnection.SessionError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类impacket.smbconnection
的用法示例。
在下文中一共展示了smbconnection.SessionError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def check(self, remote_host):
# Validate credentials first
if not self.creds_validated:
self.validate_creds(remote_host)
self.creds_validated = True
# Now start scanner
try:
smbClient = SMBConnection(remote_host, remote_host, sess_port=int(self.__port)) #, preferredDialect=SMB2_DIALECT_21
except:
return
ntlm.computeResponseNTLMv2 = mod_computeResponseNTLMv2
try:
smbClient.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)
logging.info('Target %s is VULNERABLE to CVE-2019-1040 (authentication was accepted)', remote_host)
except SessionError as exc:
if 'STATUS_INVALID_PARAMETER' in str(exc):
logging.info('Target %s is not vulnerable to CVE-2019-1040 (authentication was rejected)', remote_host)
else:
logging.warning('Unexpected Exception while authenticating to %s: %s', remote_host, exc)
smbClient.close()
# Process command-line arguments.
示例2: __findWritableShare
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def __findWritableShare(self):
self.__log__(logging.DEBUG, 'Searching for writable share')
shares = self.__smbconnection.listShares()
dirname = getRandomName() + '-write-test'
tries = []
for share in shares:
if share['shi1_type'] in [smb.SHARED_DISK, smb.SHARED_DISK_HIDDEN]:
shareName = share['shi1_netname'][:-1]
shareOK = True
try:
# try to create directory
self.__smbconnection.createDirectory(shareName, dirname)
except SessionError, e:
tries.append(shareName)
# if error, depends on whether the test directory existed or not
shareOK = True if e.getErrorCode == nt_errors.STATUS_OBJECT_NAME_COLLISION else False
if shareOK:
# We found a share, delete our test
self.__smbconnection.deleteDirectory(shareName, dirname)
self.__log__(logging.DEBUG, 'Using share "%s"' % shareName)
self.__writableShare = shareName
return
示例3: __createWorkingDirectory
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def __createWorkingDirectory(self):
self.__log__(logging.DEBUG, 'Creating working directory')
try:
dirname = '%s-local' % PROGRAM_NAME
self.__smbconnection.createDirectory(self.__writableShare, dirname)
self.__workingDirectory = dirname
self.__pendingCleanupActions.append((self.__deleteWorkingDirectory, 3))
except SessionError, e:
if e.getErrorCode()!=nt_errors.STATUS_OBJECT_NAME_COLLISION:
raise e
else:
self.__workingDirectory = dirname
self.__pendingCleanupActions.append((self.__deleteWorkingDirectory, 3))
self.__log__(logging.WARNING, 'Directory "%s" is already present' % dirname)
示例4: fileExists
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def fileExists(self, remoteName):
try:
self.__log__(logging.DEBUG, 'Trying to access ' + remoteName)
tid = self.__smbconnection.connectTree(self.__writableShare)
remoteName = '%s\\%s' % (self.__workingDirectory, remoteName)
fid = self.__smbconnection.openFile(tid, remoteName, desiredAccess=FILE_READ_DATA)
self.__log__(logging.DEBUG, 'File exists: ' + remoteName)
self.__smbconnection.closeFile(tid, fid)
return False
except SessionError, e:
if e.getErrorCode() == nt_errors.STATUS_OBJECT_NAME_NOT_FOUND:
self.__log__(logging.DEBUG, 'File does not exist: ' + remoteName)
return False
self.__log__(logging.ERROR, 'Error during file access', e)
raise FileError()
示例5: login
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def login(self):
try:
ip = list({addr[-1][0] for addr in getaddrinfo(self.hostname, 0, 0, 0, 0)})[0]
if ip != self.hostname:
self._log.debug("Host {} resolved to {}".format(self.hostname, ip))
except gaierror as e:
return RetCode(ERROR_DNS_ERROR, e)
try:
self._conn = SMBConnection(self.hostname, ip, timeout=self.timeout)
except Exception as e:
return RetCode(ERROR_CONNECTION_ERROR, e)
username = ''
if not self.kerberos:
username = self.username.split("@")[0]
self._log.debug("Authenticating against {}".format(ip))
else:
self._log.debug("Authenticating against {}".format(self.hostname))
try:
if not self.kerberos:
self._conn.login(username, self.password, domain=self.domain_name, lmhash=self.lmhash,
nthash=self.nthash, ntlmFallback=True)
else:
self._conn.kerberosLogin(username, self.password, domain=self.domain_name, lmhash=self.lmhash,
nthash=self.nthash, aesKey=self.aesKey, kdcHost=self.dc_ip)
except SessionError as e:
self._log.debug("Provided credentials : {}\\{}:{}".format(self.domain_name, username, self.password))
return RetCode(ERROR_LOGIN_FAILURE, e)
except KerberosException as e:
self._log.debug("Kerberos error")
return RetCode(ERROR_LOGIN_FAILURE, e)
except Exception as e:
return RetCode(ERROR_UNDEFINED, e)
return RetCode(ERROR_SUCCESS)
示例6: enum_host_info
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def enum_host_info(self):
# smb no open, specify the domain
if self.args.domain:
self.domain = self.args.domain
self.logger.extra['hostname'] = self.hostname
else:
try:
smb_conn = SMBConnection(self.host, self.host, None)
try:
smb_conn.login('', '')
except SessionError as e:
if "STATUS_ACCESS_DENIED" in e.message:
pass
self.domain = smb_conn.getServerDomain()
self.hostname = smb_conn.getServerName()
self.server_os = smb_conn.getServerOS()
self.logger.extra['hostname'] = self.hostname
try:
smb_conn.logoff()
except:
pass
except Exception as e:
logging.debug("Error retrieving host domain: {} specify one manually with the '-d' flag".format(e))
if self.args.domain:
self.domain = self.args.domain
if self.args.local_auth:
self.domain = self.hostname
示例7: spider
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def spider(self, share, folder='.', pattern=[], regex=[], exclude_dirs=[], depth=None, content=False, onlyfiles=True):
if regex:
try:
self.regex = [re.compile(rx) for rx in regex]
except Exception as e:
self.logger.error('Regex compilation error: {}'.format(e))
self.folder = folder
self.pattern = pattern
self.exclude_dirs = exclude_dirs
self.content = content
self.onlyfiles = onlyfiles
if share == "*":
self.logger.info("Enumerating shares for spidering")
permissions = []
try:
for share in self.smbconnection.listShares():
share_name = share['shi1_netname'][:-1]
share_remark = share['shi1_remark'][:-1]
try:
self.smbconnection.listPath(share_name, '*')
self.share = share_name
self.logger.info("Spidering share: {0}".format(share_name))
self._spider(folder, depth)
except SessionError:
pass
except Exception as e:
self.logger.error('Error enumerating shares: {}'.format(e))
else:
self.share = share
self.logger.info("Spidering {0}".format(folder))
self._spider(folder, depth)
return self.results
示例8: _spider
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def _spider(self, subfolder, depth):
'''
Abondon all hope ye who enter here.
You're now probably wondering if I was drunk and/or high when writing this.
Getting this to work took a toll on my sanity. So yes. a lot.
'''
# The following is some funky shit that deals with the way impacket treats file paths
if subfolder in ['', '.']:
subfolder = '*'
elif subfolder.startswith('*/'):
subfolder = subfolder[2:] + '/*'
else:
subfolder = subfolder.replace('/*/', '/') + '/*'
# End of the funky shit... or is it? Surprise! This whole thing is funky
filelist = None
try:
filelist = self.smbconnection.listPath(self.share, subfolder)
self.dir_list(filelist, subfolder)
if depth == 0:
return
except SessionError as e:
if not filelist:
if 'STATUS_ACCESS_DENIED' not in str(e):
logging.debug("Failed listing files on share {} in directory {}: {}".format(self.share, subfolder, e))
return
for result in filelist:
if result.is_directory() and result.get_longname() not in ['.','..']:
if subfolder == '*':
self._spider(subfolder.replace('*', '') + result.get_longname(), depth-1 if depth else None)
elif subfolder != '*' and (subfolder[:-2].split('/')[-1] not in self.exclude_dirs):
self._spider(subfolder.replace('*', '') + result.get_longname(), depth-1 if depth else None)
return
示例9: plaintext_login
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def plaintext_login(self, domain, username, password):
try:
self.password = password
self.username = username
self.domain = domain
self.conn.login(username, password, domain)
self.check_if_admin()
self.db.add_credential('plaintext', domain, username, password)
if self.admin_privs:
self.db.add_admin_user('plaintext', domain, username, password, self.host)
out = u'{}\\{}:{} {}'.format(domain,
username,
password,
highlight('({})'.format(self.config.get('CME', 'pwn3d_label')) if self.admin_privs else ''))
self.logger.success(out)
if not self.args.continue_on_success:
return True
elif self.signing: # check https://github.com/byt3bl33d3r/CrackMapExec/issues/321
try:
self.conn.logoff()
except:
pass
self.create_conn_obj()
except SessionError as e:
error, desc = e.getErrorString()
self.logger.error(u'{}\\{}:{} {} {}'.format(domain,
username,
password,
error,
'({})'.format(desc) if self.args.verbose else ''),
color='magenta' if error in smb_error_status else 'red')
if error not in smb_error_status:
self.inc_failed_login(username)
return False
if not self.args.continue_on_success:
return True
示例10: process_remote
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def process_remote(username, password, target, historic):
hashes = list()
print("Attempting to connect to {}...".format(target))
try:
connection = SMBConnection(target, target)
connection.login(username, password, "", "", "")
ops = RemoteOperations(connection, False, None)
ops.setExecMethod("smbexec")
stopper = Event()
spinner = Thread(target=__update, args=(stopper, hashes))
spinner.start()
NTDSHashes(None, None, isRemote=True, remoteOps=ops, noLMHash=True, useVSSMethod=False,
justNTLM=True, printUserStatus=True, history=historic, lastLogon=True, pwdLastSet=True,
perSecretCallback=lambda type, secret: hashes.append(__process_hash(secret))).dump()
stopper.set()
spinner.join()
if len(hashes) == 0:
raise Exception("Extraction seemingly finished successfully but I didn't find any hashes...")
return __get_domain(hashes), hashes
except socket_error:
raise Exception("Failed to connect to {}".format(target))
except SessionError as e:
if e.error == 3221225581:
raise Exception("Username or password incorrect - please try again.")
示例11: listLocalAdminAccess
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def listLocalAdminAccess(target, user, pwnableTargets):
with timeout(5):
try:
if invoke_checklocaladminaccess(target, user.domain, user.username, user.password, user.lmhash, user.nthash):
logging.info("%s%s is %spwnable%s!" % (infoYellow, target, green, white))
pwnableTargets.append(target)
except SessionError as e:
error = e.getErrorString()
logging.info("%s%s is %snot pwnable%s! (%s)" % (infoYellow, target, red, white, error))
except Exception as e:
logging.info("%s%s is %snot pwnable%s! (%s)" % (infoYellow, target, red, white, e))
示例12: execute
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def execute(self, host, port='139', user=None, password='', password_hash=None, domain='', persistent='1'):
with Timing() as timing:
fp, _ = self.bind(host, port)
try:
if user is None:
fp.login('', '') # retrieve workgroup/domain and computer name
else:
with Timing() as timing:
if password_hash:
if ':' in password_hash:
lmhash, nthash = password_hash.split(':')
else:
lmhash, nthash = 'aad3b435b51404eeaad3b435b51404ee', password_hash
fp.login(user, '', domain, lmhash, nthash)
else:
fp.login(user, password, domain)
logger.debug('No error')
code, mesg = '0', '%s\\%s (%s)' % (fp.getServerDomain(), fp.getServerName(), fp.getServerOS())
self.reset()
except SessionError as e:
code = '%x' % e.getErrorCode()
mesg = nt_errors.ERROR_MESSAGES[e.getErrorCode()][0]
if persistent == '0':
self.reset()
return self.Response(code, mesg, timing)
示例13: host_info
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def host_info(self):
try:
self.con.login('', '')
except SessionError as e:
if "STATUS_ACCESS_DENIED" in e.getErrorString():
pass
self.srvdomain = self.con.getServerDomain() # Demo
self.host = self.get_hostname()
self.os = self.con.getServerOS() # Windows 10 Build 17134
self.signing = self.con.isSigningRequired() # True/False
if not self.srvdomain:
self.srvdomain = self.con.getServerName()
arch = self.get_os_arch()
if arch != 0:
self.os_arch = " x{}".format(str(arch))
if self.con.getServerDNSDomainName():
domain = self.con.getServerDNSDomainName()
else:
domain = self.ip
try:
# Log off before attempting new auth
self.logoff()
except:
pass
self.db.update_host(self.host, self.ip, domain, self.os, self.signing)
if self.args.gen_relay_list and not self.signing:
self.loggers['relay_list'].info(self.ip)
self.smb_connection()
示例14: validate_creds
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def validate_creds(self, remote_host):
try:
smbClient = SMBConnection(remote_host, remote_host, sess_port=int(self.__port)) #, preferredDialect=SMB2_DIALECT_21
smbClient.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)
except SessionError as exc:
if 'STATUS_LOGON_FAILURE' in str(exc):
logging.error('Error validating credentials - make sure the supplied credentials are correct')
else:
logging.warning('Unexpected Exception while validating credentials against {}: %s'.format(remote_host), exc)
raise KeyboardInterrupt
except:
logging.error('Error during connection to {}. TCP/445 refused, timeout?'.format(remote_host))
示例15: _get_groupsxml
# 需要导入模块: from impacket import smbconnection [as 别名]
# 或者: from impacket.smbconnection import SessionError [as 别名]
def _get_groupsxml(self, groupsxml_path, gpo_display_name):
gpo_groups = list()
content_io = StringIO()
groupsxml_path_split = groupsxml_path.split('\\')
gpo_name = groupsxml_path_split[6]
target = self._domain_controller
share = groupsxml_path_split[3]
file_name = '\\'.join(groupsxml_path_split[4:])
smb_connection = SMBConnection(remoteName=target, remoteHost=target)
# TODO: kerberos login
smb_connection.login(self._user, self._password, self._domain,
self._lmhash, self._nthash)
smb_connection.connectTree(share)
try:
smb_connection.getFile(share, file_name, content_io.write)
except SessionError:
return list()
content = content_io.getvalue().replace('\r', '')
groupsxml_soup = BeautifulSoup(content, 'xml')
for group in groupsxml_soup.find_all('Group'):
members = list()
memberof = list()
local_sid = group.Properties.get('groupSid', str())
if not local_sid:
if 'administrators' in group.Properties['groupName'].lower():
local_sid = 'S-1-5-32-544'
elif 'remote desktop' in group.Properties['groupName'].lower():
local_sid = 'S-1-5-32-555'
else:
local_sid = group.Properties['groupName']
memberof.append(local_sid)
for member in group.Properties.find_all('Member'):
if not member['action'].lower() == 'add':
continue
if member['sid']:
members.append(member['sid'])
else:
members.append(member['name'])
if members or memberof:
# TODO: implement filter support (seems like a pain in the ass,
# I'll do it if the feature is asked). PowerView also seems to
# have the barest support for filters, so ¯\_(ツ)_/¯
gpo_group = GPOGroup(list())
setattr(gpo_group, 'gpodisplayname', gpo_display_name)
setattr(gpo_group, 'gponame', gpo_name)
setattr(gpo_group, 'gpopath', groupsxml_path)
setattr(gpo_group, 'members', members)
setattr(gpo_group, 'memberof', memberof)
gpo_groups.append(gpo_group)
return gpo_groups