Python impacket.smbconnection.SessionError() Examples

The following are 22 code examples of impacket.smbconnection.SessionError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module impacket.smbconnection , or try the search function .
Example #1
Source File: remotecmd.py    From certitude with GNU General Public License v2.0 7 votes vote down vote up
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() 
Example #2
Source File: remotecmd.py    From certitude with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #3
Source File: remotecmd.py    From certitude with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #4
Source File: scan.py    From cve-2019-1040-scanner with MIT License 6 votes vote down vote up
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. 
Example #5
Source File: ntds_parser.py    From cracke-dit with MIT License 5 votes vote down vote up
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.") 
Example #6
Source File: scan.py    From cve-2019-1040-scanner with MIT License 5 votes vote down vote up
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)) 
Example #7
Source File: smb.py    From ActiveReign with GNU General Public License v3.0 5 votes vote down vote up
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() 
Example #8
Source File: patator_ext.py    From project-black with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #9
Source File: patator.py    From patator with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #10
Source File: Targets.py    From spraykatz with MIT License 5 votes vote down vote up
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)) 
Example #11
Source File: impacketconnection.py    From lsassy with MIT License 5 votes vote down vote up
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) 
Example #12
Source File: smb.py    From CrackMapExec with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 
Example #13
Source File: smbspider.py    From CrackMapExec with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 
Example #14
Source File: smbspider.py    From CrackMapExec with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 
Example #15
Source File: winrm.py    From CrackMapExec with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 
Example #16
Source File: smb.py    From CrackMapExec with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def shares(self):
        temp_dir = ntpath.normpath("\\" + gen_random_string())
        #hostid,_,_,_,_,_,_ = self.db.get_hosts(filterTerm=self.host)[0]
        permissions = []

        try:
            for share in self.conn.listShares():
                share_name = share['shi1_netname'][:-1]
                share_remark = share['shi1_remark'][:-1]
                share_info = {'name': share_name, 'remark': share_remark, 'access': []}
                read = False
                write = False

                try:
                    self.conn.listPath(share_name, '*')
                    read = True
                    share_info['access'].append('READ')
                except SessionError:
                    pass

                try:
                    self.conn.createDirectory(share_name, temp_dir)
                    self.conn.deleteDirectory(share_name, temp_dir)
                    write = True
                    share_info['access'].append('WRITE')
                except SessionError:
                    pass

                permissions.append(share_info)
                #self.db.add_share(hostid, share_name, share_remark, read, write)

            self.logger.success('Enumerated shares')
            self.logger.highlight('{:<15} {:<15} {}'.format('Share', 'Permissions', 'Remark'))
            self.logger.highlight('{:<15} {:<15} {}'.format('-----', '-----------', '------'))
            for share in permissions:
                name   = share['name']
                remark = share['remark']
                perms  = share['access']

                self.logger.highlight(u'{:<15} {:<15} {}'.format(name, ','.join(perms), remark))

        except Exception as e:
            error, desc = e.getErrorString()
            self.logger.error('Error enumerating shares: {}'.format(error),
                            color='magenta' if error in smb_error_status else 'red')

        return permissions 
Example #17
Source File: smb.py    From CrackMapExec with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def hash_login(self, domain, username, ntlm_hash):
        lmhash = ''
        nthash = ''

        #This checks to see if we didn't provide the LM Hash
        if ntlm_hash.find(':') != -1:
            lmhash, nthash = ntlm_hash.split(':')
        else:
            nthash = ntlm_hash

        try:
            self.hash = ntlm_hash
            if lmhash: self.lmhash = lmhash
            if nthash: self.nthash = nthash

            self.username = username
            self.domain = domain
            self.conn.login(username, '', domain, lmhash, nthash)

            self.check_if_admin()
            self.db.add_credential('hash', domain, username, ntlm_hash)

            if self.admin_privs:
                self.db.add_admin_user('hash', domain, username, ntlm_hash, self.host)

            out = u'{}\\{} {} {}'.format(domain,
                                         username,
                                         ntlm_hash,
                                         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
            # check https://github.com/byt3bl33d3r/CrackMapExec/issues/321
            if self.signing:
                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,
                                                        ntlm_hash,
                                                        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 
Example #18
Source File: smbspider.py    From CrackMapExec with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def search_content(self, path, result):
        path = path.replace('*', '')
        try:
            rfile = RemoteFile(self.smbconnection, path + result.get_longname(), self.share, access=FILE_READ_DATA)
            rfile.open()

            while True:
                try:
                    contents = rfile.read(4096)
                    if not contents:
                        break
                except SessionError as e:
                    if 'STATUS_END_OF_FILE' in str(e):
                        break

                except Exception:
                    traceback.print_exc()
                    break

                for pattern in self.pattern:
                    if contents.lower().find(pattern.lower()) != -1:
                        self.logger.highlight(u"//{}/{}/{}{} [lastm:'{}' size:{} offset:{} pattern:'{}']".format(self.smbconnection.getRemoteHost(), 
                                                                                                            self.share,
                                                                                                            path,
                                                                                                            result.get_longname(),
                                                                                                            'n\\a' if not self.get_lastm_time(result) else self.get_lastm_time(result),
                                                                                                            result.get_filesize(),
                                                                                                            rfile.tell(),
                                                                                                            pattern))
                        self.results.append('{}{}'.format(path, result.get_longname()))

                for regex in self.regex:
                    if regex.findall(contents):
                        self.logger.highlight(u"//{}/{}/{}{} [lastm:'{}' size:{} offset:{} regex:'{}']".format(self.smbconnection.getRemoteHost(),
                                                                                                          self.share,
                                                                                                          path,
                                                                                                          result.get_longname(),
                                                                                                          'n\\a' if not self.get_lastm_time(result) else self.get_lastm_time(result),
                                                                                                          result.get_filesize(),
                                                                                                          rfile.tell(),
                                                                                                          regex.pattern))
                        self.results.append('{}{}'.format(path, result.get_longname()))

            rfile.close()
            return

        except SessionError as e:
            if 'STATUS_SHARING_VIOLATION' in str(e):
                pass

        except Exception:
            traceback.print_exc() 
Example #19
Source File: mssql.py    From CrackMapExec with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def enum_host_info(self):
        # this try pass breaks module http server, more info https://github.com/byt3bl33d3r/CrackMapExec/issues/363
        try:
            # Probably a better way of doing this, grab our IP from the socket
            self.local_ip = str(self.conn.socket).split()[2].split('=')[1].split(':')[0]
        except:
            pass

        if self.args.auth_type == 'windows':
            if self.args.domain:
                self.domain = self.args.domain
            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

                    if self.args.domain:
                        self.domain = self.args.domain

                    if self.args.local_auth:
                        self.domain = self.hostname

                except Exception as e:
                    self.logger.error("Error retrieving host domain: {} specify one manually with the '-d' flag".format(e))

        self.mssql_instances = self.conn.getInstances(10)
        if len(self.mssql_instances) > 0:
            for i, instance in enumerate(self.mssql_instances):
                for key in instance.keys():
                    if key.lower() == 'servername':
                        self.hostname = instance[key]
                        break

            self.db.add_computer(self.host, self.hostname, self.domain, self.server_os, len(self.mssql_instances))

        try:
            self.conn.disconnect()
        except:
            pass 
Example #20
Source File: remotecmd.py    From certitude with GNU General Public License v2.0 4 votes vote down vote up
def __init__(self, threadname, ip, login, password, **kwargs):

        self.logger = logging.getLogger('remotecmd.' + threadname)
        if 'verbosity' in kwargs.keys():
            self.logger.setLevel(kwargs['verbosity'])

        # Init variables
        self.__ip = ip
        self.__login = login

        # KWargs
        domain = DEFAULT_DOMAIN if 'domain' not in kwargs.keys() else kwargs['domain']
        commandPriority = DEFAULT_PRIORITY if 'priority' not in kwargs.keys() else kwargs['priority']
        self.rootDir = '.' if not 'rootDir' in kwargs.keys() else kwargs['rootDir']
        
        # Local variables
        self.__rootDir = '.' if 'rootDir' not in kwargs.keys() else kwargs['rootDir']
        self.__writableShare = None
        self.__workingDirectory = None
        self.__SVCManager = None
        self.__service = None
        self.drive = None
        
        # Setup & cleanup actions
        self.__pendingCleanupActions = []
        self.__pendingSetupActions = [
            (self.__findWritableShare, 3),
            (self.__createWorkingDirectory, 3),
            (self.__openSVCManager, 3),
            (self.__createService, 3),
            (self.__dropBinary, 3),
            (self.__startService, 3),
            (self.__setNet, 1),
        ]

        # Transport connection
        self.__rpctransport = transport.DCERPCTransportFactory('ncacn_np:%s[\pipe\svcctl]' % ip)
        self.__rpctransport.set_dport(445)
        self.__rpctransport.set_credentials(login, password, domain, '', '', '')
        self.__rpctransport.set_kerberos(False, '')
        self.__dcerpc = self.__rpctransport.get_dce_rpc()
        
        # Initiate login
        try:
            self.__dcerpc.connect()
            self.__smbconnection = self.__rpctransport.get_smb_connection()
            self.__log__(logging.INFO, 'Login successful')
            
        except SessionError, e:
            raise LoginError('Error during login: %s' % e.getErrorString()[0])
    
    
    # SETUP function 
Example #21
Source File: gpo.py    From pywerview with GNU General Public License v3.0 4 votes vote down vote up
def get_netgpogroup(self, queried_gponame='*', queried_displayname=str(),
                        queried_domain=str(), ads_path=str(), resolve_sids=False):
        results = list()
        gpos = self.get_netgpo(queried_gponame=queried_gponame,
                               queried_displayname=queried_displayname,
                               queried_domain=queried_domain,
                               ads_path=ads_path)

        for gpo in gpos:
            gpo_display_name = gpo.displayname

            groupsxml_path = '{}\\MACHINE\\Preferences\\Groups\\Groups.xml'.format(gpo.gpcfilesyspath)
            gpttmpl_path = '{}\\MACHINE\\Microsoft\\Windows NT\\SecEdit\\GptTmpl.inf'.format(gpo.gpcfilesyspath)

            results += self._get_groupsxml(groupsxml_path, gpo_display_name)
            try:
                results += self._get_groupsgpttmpl(gpttmpl_path, gpo_display_name)
            except SessionError:
                # If the GptTmpl file doesn't exist, we skip this
                pass

        if resolve_sids:
            for gpo_group in results:
                members = gpo_group.members
                memberof = gpo_group.memberof

                resolved_members = list()
                resolved_memberof = list()
                with NetRequester(self._domain_controller, self._domain, self._user,
                                  self._password, self._lmhash, self._nthash) as net_requester:
                    for member in members:
                        try:
                            resolved_member = net_requester.get_adobject(queried_sid=member, queried_domain=queried_domain)[0]
                            resolved_member = resolved_member.distinguishedname.split(',')
                            resolved_member_domain = '.'.join(resolved_member[1:])
                            resolved_member = '{}\\{}'.format(resolved_member_domain, resolved_member[0])
                            resolved_member = resolved_member.replace('CN=', '').replace('DC=', '')
                        except IndexError:
                            resolved_member = member
                        finally:
                            resolved_members.append(resolved_member)
                    gpo_group.members = resolved_members

                    for member in memberof:
                        try:
                            resolved_member = net_requester.get_adobject(queried_sid=member, queried_domain=queried_domain)[0]
                            resolved_member = resolved_member.distinguishedname.split(',')[:2]
                            resolved_member = '{}\\{}'.format(resolved_member[1], resolved_member[0])
                            resolved_member = resolved_member.replace('CN=', '').replace('DC=', '')
                        except IndexError:
                            resolved_member = member
                        finally:
                            resolved_memberof.append(resolved_member)
                    gpo_group.memberof = memberof = resolved_memberof

        return results 
Example #22
Source File: gpo.py    From pywerview with GNU General Public License v3.0 4 votes vote down vote up
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