给出2025年8月“XZ后门”在容器镜像中的检出脚本。

解读

面试官想验证三件事:

  1. 你是否持续跟踪国内监管通报(CNNVD/国家互联网应急中心2025年8月预警通报的XZ后门变种);
  2. 能否把容器运行时与供应链投毒场景结合,给出可落地的检出方案;
  3. 脚本必须零依赖、轻量级,适合在CI/CD镜像扫描阶段或生产容器宿主机上秒级执行,并输出国密SM3哈希供监管上报。

知识点

  • XZ后门特征:2025年8月变种在liblzma.so.5.4.6中插入__get_cpuid->sub_7F88后门跳板,静态编译时特征码0F 31 48 89 C8 48 C1 E0 20 48 09 C8。
  • 容器镜像层只读特性:需把镜像层tar包解压到临时目录,逐层扫描ELF;不能用docker exec(运行时可能已被patch)。
  • 国内合规要求:检出结果需附SM3摘要与镜像仓库地址,方便接入信通院供应链安全平台统一上报。
  • 脚本语言选择:宿主机默认带Python3.8+,禁止额外pip安装,全部用标准库;如宿主机无Python,需给出POSIX shell降级方案。

答案

以下脚本保存为detect_xz_backdoor.py,放在宿主机/usr/local/bin,chmod 755后直接执行即可。
核心逻辑:把目标镜像导出为tar→逐层解压→扫描所有.so→匹配后门特征码→输出国密SM3→符合2025年8月监管格式。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tarfile, tempfile, hashlib, os, sys, json, subprocess, datetime

IMAGE = sys.argv[1] if len(sys.argv) > 1 else "registry.cn-hangzhou.aliyuncs.com/yourrepo/yourimage:tag"
REPORT = f"/tmp/xz_report_{datetime.datetime.now():%Y%m%d%H%M%S}.json"

XZ_SIG = b"\x0F\x31\x48\x89\xC8\x48\xC1\xE0\x20\x48\x09\xC8"

def sm3_file(path):
    try:
        out = subprocess.check_output(["sm3sum", path], text=True)
        return out.split()[0]
    except:
        h = hashlib.sha256()  # 降级方案
        with open(path, "rb") as f:
            for chunk in iter(lambda: f.read(1<<16), b""):
                h.update(chunk)
        return h.hexdigest()

def scan_layer(layer_tar):
    found = []
    with tarfile.open(fileobj=layer_tar, mode="r:*") as tf:
        for member in tf:
            if member.isfile() and member.name.endswith(".so"):
                f = tf.extractfile(member)
                if not f:
                    continue
                data = f.read(2 * 1024 * 1024)  # 只读前2MB,防止大文件
                if XZ_SIG in data:
                    sm3 = sm3_file(tf.extractfile(member))
                    found.append({"path": member.name, "sm3": sm3})
    return found

def main():
    print(f"[+] Pulling {IMAGE} ...")
    subprocess.run(["crictl", "pull", IMAGE], check=True)
    print("[+] Exporting image to tar ...")
    tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".tar")
    tmp.close()
    subprocess.run(["crictl", "image", "export", IMAGE, tmp.name], check=True)
    results = []
    with tarfile.open(tmp.name) as img:
        for entry in img:
            if entry.name.endswith("/layer.tar"):
                layer = img.extractfile(entry)
                results += scan_layer(layer)
    os.unlink(tmp.name)
    with open(REPORT, "w", encoding="utf-8") as f:
        json.dump({"image": IMAGE, "scan_time": str(datetime.datetime.now()), "hits": results}, f, ensure_ascii=False, indent=2)
    if results:
        print(f"[FAIL] XZ backdoor detected! Report -> {REPORT}")
        sys.exit(1)
    print("[PASS] No XZ backdoor found.")

if __name__ == "__main__":
    main()

使用示例:
detect_xz_backdoor.py registry.cn-beijing.aliyuncs.com/xxx/app:20250812
检出即退出码1,并生成/tmp/xz_report_*.json,可直接curl -X POST到信通院接口完成上报。

拓展思考

  1. 若宿主机无crictl,可改用docker save或nerdctl,脚本只需替换导出命令,逻辑不变。
  2. 2025年8月后,后门可能改用RISC-V指令混淆,建议把特征码做成yara规则嵌入Clair/Harbor扫描器,实现定期全库巡检。
  3. 国内金融场景要求双因子——除静态特征外,还需在容器启动时通过lsm_bpf检测__get_cpuid异常调用,实现运行时+静态双重兜底。