1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
| import argparse import io import json import zipfile from pathlib import Path
from PIL import Image, ImageDraw, ImageFont, ImageStat
PIGPEN_PATHS = { "A": "M 20 4 L 20 20 L 4 20", "B": "M 4 4 L 4 20 L 20 20 L 20 4", "C": "M 4 4 L 4 20 L 20 20", "D": "M 4 4 L 20 4 L 20 20 L 4 20", "E": "M 4 4 L 20 4 L 20 20 L 4 20 Z", "F": "M 20 4 L 4 4 L 4 20 L 20 20", "G": "M 4 4 L 20 4 L 20 20", "H": "M 4 20 L 4 4 L 20 4 L 20 20", "I": "M 20 4 L 4 4 L 4 20", "S": "M 4 4 L 12 20 L 20 4", "T": "M 4 4 L 20 12 L 4 20", "U": "M 20 4 L 4 12 L 20 20", "V": "M 4 20 L 12 4 L 20 20", }
PIGPEN_BASE = { **{ch: ch for ch in "ABCDEFGHI"}, **dict(zip("JKLMNOPQR", "ABCDEFGHI")), **dict(zip("STUVWXYZ", "STUVSTUV")), }
PIGPEN_SEGMENTS = { "A": [(20, 4), (20, 20), (4, 20)], "B": [(4, 4), (4, 20), (20, 20), (20, 4)], "C": [(4, 4), (4, 20), (20, 20)], "D": [(4, 4), (20, 4), (20, 20), (4, 20)], "E": [(4, 4), (20, 4), (20, 20), (4, 20), (4, 4)], "F": [(20, 4), (4, 4), (4, 20), (20, 20)], "G": [(4, 4), (20, 4), (20, 20)], "H": [(4, 20), (4, 4), (20, 4), (20, 20)], "I": [(20, 4), (4, 4), (4, 20)], "S": [(4, 4), (12, 20), (20, 4)], "T": [(4, 4), (20, 12), (4, 20)], "U": [(20, 4), (4, 12), (20, 20)], "V": [(4, 20), (12, 4), (20, 20)], }
def flag2_to_bits(flag2: str) -> str: """ flag2 按 ASCII 编码成 bit 串,PNG/JPG 类型按位承载这些 bit。 """ try: data = flag2.encode("ascii") except UnicodeEncodeError: raise ValueError("flag2 must be ASCII, because it is encoded as 8-bit ASCII.")
return "".join(f"{b:08b}" for b in data)
def clamp(x, lo=0, hi=255): return max(lo, min(hi, int(x)))
def load_consolas(font_path=None, size=72): """ 优先加载 Consolas。 如果系统里没有 Consolas,可以通过 --font 手动指定 consola.ttf。 """ if font_path: return ImageFont.truetype(font_path, size)
candidates = [ "C:/Windows/Fonts/consola.ttf", "C:/Windows/Fonts/consolab.ttf", ]
for p in candidates: try: return ImageFont.truetype(p, size) except Exception: pass
print("[!] Warning: Consolas or monospace TTF not found, using PIL default font.") return ImageFont.load_default()
def text_bbox(draw: ImageDraw.ImageDraw, text: str, font): return draw.textbbox((0, 0), text, font=font)
def draw_char_top_left_on_cover( cover_path: Path, ch: str, out_fmt: str, font_path=None, font_size=64, margin=32, delta=8, ): """ 对用户提供的 cover 图片,在左上角用小字号写入外层标记 PIGPEN。
字符颜色基于左上角局部背景均值加/减固定 delta。 这样不同 cover 上都是统一色差,而不是固定绝对颜色。 """ img = Image.open(cover_path).convert("RGB") draw = ImageDraw.Draw(img)
if ch: font = load_consolas(font_path, font_size)
bbox = text_bbox(draw, ch, font) tw = bbox[2] - bbox[0] th = bbox[3] - bbox[1]
w, h = img.size
x = min(margin, max(0, w - tw)) y = min(margin, max(0, h - th))
sample_box = ( max(0, x), max(0, y), min(w, x + tw + 4), min(h, y + th + 4), )
region = img.crop(sample_box) mean_rgb = ImageStat.Stat(region).mean[:3] avg = sum(mean_rgb) / 3
if avg > 128: color = tuple(clamp(c - delta) for c in mean_rgb) else: color = tuple(clamp(c + delta) for c in mean_rgb)
draw.text( (x - bbox[0], y - bbox[1]), ch, fill=color, font=font, )
return save_image_to_bytes(img, out_fmt)
def make_synthetic_dark_image( ch: str, out_fmt: str, font_path=None, size=96, font_size=72, ): """ 生成自动 cover。
背景:rgb(0, 0, 0)
字符:rgb(1, 1, 1)
""" bg = (0, 0, 0)
img = Image.new("RGB", (size, size), bg)
if ch: draw_pigpen_char(img, ch, font_path=font_path, font_size=font_size)
return save_image_to_bytes(img, out_fmt)
def draw_pigpen_char(img: Image.Image, ch: str, font_path=None, font_size=72): """Draw one inner flag character as a pigpen glyph; punctuation stays literal.""" draw = ImageDraw.Draw(img) upper = ch.upper() base = PIGPEN_BASE.get(upper) margin = max(8, img.width // 12) if base in PIGPEN_SEGMENTS: points = PIGPEN_SEGMENTS[base] scale = min((img.width - 2 * margin) / 24, (img.height - 2 * margin) / 24) scaled = [(margin + x * scale, margin + y * scale) for x, y in points] draw.line(scaled, fill=(1, 1, 1), width=max(2, int(scale * 2)), joint="curve") if upper in "JKLMNOPQRWXYZ": cx = margin + 12 * scale cy = margin + 12 * scale radius = max(1, int(scale * 1.5)) draw.ellipse( (cx - radius, cy - radius, cx + radius, cy + radius), fill=(1, 1, 1) ) return
font = load_consolas(font_path, font_size) bbox = text_bbox(draw, ch, font) tw = bbox[2] - bbox[0] th = bbox[3] - bbox[1] x = min(margin, max(0, img.width - tw)) y = min(margin, max(0, img.height - th)) draw.text((x - bbox[0], y - bbox[1]), ch, fill=(1, 1, 1), font=font)
def save_image_to_bytes(img: Image.Image, out_fmt: str) -> bytes: """ 保存为 PNG 或 JPG。 """ buf = io.BytesIO()
if out_fmt == "png": img.save( buf, format="PNG", ) elif out_fmt == "jpg": img.save( buf, format="JPEG", quality=100, subsampling=0, optimize=False, ) else: raise ValueError(f"Unsupported image format: {out_fmt}")
return buf.getvalue()
def make_zip_bytes(filename: str, data: bytes) -> bytes: """ 创建一个 zip,里面只有一个文件。 """ buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf: zf.writestr(filename, data)
return buf.getvalue()
def make_polyglot(image_bytes: bytes, zip_bytes: bytes) -> bytes: """ 稳定版 image + zip polyglot。
文件结构:
[正常图片数据][正常 ZIP 数据]
作为图片打开时,图片查看器通常忽略尾部 ZIP 数据。 作为 ZIP 打开时,解压器从尾部 EOCD 找 ZIP 结构。 """ return image_bytes + zip_bytes
def infer_output_name(out_path: str | None, first_ext: str) -> Path: if out_path: return Path(out_path) return Path(f"1.{first_ext}")
def main(): parser = argparse.ArgumentParser( description="Generate nested image+zip polyglot CTF challenge." )
parser.add_argument( "--flag1", required=True, help="flag1, one pigpen character per inner layer" ) parser.add_argument("--flag2", required=True, help="flag2, encoded by image types") parser.add_argument( "--covers", nargs="*", default=[], help="cover1 cover2 ... coverm. Used only for the first m layers.", ) parser.add_argument("--innertxt", required=True, help="inner text file path") parser.add_argument( "--out", default=None, help="output file path, default A1.png/jpg" )
parser.add_argument( "--inner-extensions", action="store_true", help="include .png/.jpg extensions for inner files. Default: hidden extensions.", ) parser.add_argument( "--manifest", default="manifest_for_author.json", help="author-only manifest output path", )
args = parser.parse_args()
flag1 = args.flag1 flag2 = args.flag2 flag2_bits = flag2_to_bits(flag2)
if len(flag2_bits) < len(flag1) + 1: raise ValueError( "This challenge version needs one outer cover plus one inner image per flag1 character. " f"Got {len(flag2_bits)} image layers for {len(flag1)} flag1 characters." )
n = len(flag2_bits)
covers = [Path(p) for p in args.covers] for p in covers: if not p.exists(): raise FileNotFoundError(p)
innertxt_path = Path(args.innertxt) if not innertxt_path.exists(): raise FileNotFoundError(innertxt_path)
layer_exts = ["jpg" if bit == "1" else "png" for bit in flag2_bits]
payload = innertxt_path.read_bytes() payload_name = "flag.txt"
manifest_layers = []
for idx in range(n, 0, -1): layer_no = idx ext = layer_exts[layer_no - 1]
if layer_no == 1: hidden_char = "PIGPEN" elif layer_no <= len(flag1) + 1: hidden_char = flag1[layer_no - 2] else: hidden_char = ""
if layer_no <= len(covers): cover_path = covers[layer_no - 1] image_bytes = draw_char_top_left_on_cover( cover_path=cover_path, ch=hidden_char, out_fmt=ext, ) cover_mode = "provided_cover" cover_used = str(cover_path) else: image_bytes = make_synthetic_dark_image( ch=hidden_char, out_fmt=ext, ) cover_mode = "synthetic_dark_square" cover_used = None
zip_bytes = make_zip_bytes(payload_name, payload) polyglot = make_polyglot(image_bytes, zip_bytes)
payload = polyglot
if args.inner_extensions: payload_name = f"{layer_no}.{ext}" else: payload_name = f"{layer_no}.zip"
manifest_layers.append( { "layer": layer_no, "image_type": ext, "flag2_bit": flag2_bits[layer_no - 1], "hidden_flag1_char": hidden_char if hidden_char else None, "hidden_encoding": ( "literal_outer_marker" if layer_no == 1 else "pigpen" if hidden_char else None ), "cover_mode": cover_mode, "cover_used": cover_used, "zip_contains": "flag.txt" if layer_no == n else f"{layer_no + 1}", } )
out_path = infer_output_name(args.out, layer_exts[0]) out_path.write_bytes(payload)
manifest = { "flag1": flag1, "flag2": flag2, "flag2_bits": flag2_bits, "n": n, "output": str(out_path), "note": "Do not distribute this file to players.", "layers": list(reversed(manifest_layers)), }
if args.manifest: Path(args.manifest).write_text( json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8", )
print("[+] Done") print(f"[+] output: {out_path}") print(f"[+] n: {n}") print(f"[+] len(flag1): {len(flag1)}") print(f"[+] len(flag2): {len(flag2)}") print(f"[+] len(flag2_bits): {len(flag2_bits)}") print(f"[+] first image type: {layer_exts[0]}") print(f"[+] covers used for first m layers: {len(covers)}") print(f"[+] inner filenames include extensions: {args.inner_extensions}") if args.manifest: print(f"[+] author manifest: {args.manifest}")
if __name__ == "__main__": main()
|