新春杯CTF RE题目解析
re的进阶的知识,补充常见的理论以及新出现的wasm类型
新春杯逆向题解
题目链接
通过网盘分享的文件:逆向.zip
链接: https://pan.baidu.com/s/1p_XcsKWhNLwbiF0hkpSrcg?pwd=aaaa 提取码: aaaa
--来自百度网盘超级会员v4的分享
第一题:签到
这个考察的python打包的exe程序的处理的流程
python程序转源码在这里讲到过
python打包产生的exe逆向需要先进行解包再分析其解包产生的.pyc 或者 .pyd 文件,exe解包工具和 .pyc反编译工具: 链接: https://pan.baidu.com/s/1YaqqFoTW1lXYQoDBCiKppw?pwd=grfe
工具下载之后是有下面这两个
在pyc的目录下面是有pycdc.exe和pyinstxtractor.py这两个文件的
这个需要配置python3.11的环境,就很烦
我们换回物理机终端,用anaconda去做
用下面这个指令创建一个python3.11的环境
conda create -n py311 python=3.11 -y之后解包为pyc之后我们找个在线网站进行就行
然后解码pyc文件之后就能看到下面这样的情况
#!/usr/bin/env python
# visit https://tool.lu/pyc/ for more information
# Version: Python 3.11
a = '53 44 50 43 53 45 43 7b 72 65 76 65 72 73 65 5f 71 69 61 6e 5f 64 61 6f 7d 0a'
correct_flag = bytes.fromhex(a).decode('utf-8').strip()
user_input = input('please input your flag: ')
if user_input == correct_flag:
print('great')
return None
print('wrong')
#SDPCSEC{reverse_qian_dao}第二题:Ez_VM
这个是C++写的vm
这里的 push 指的是:把一个字节(或一个元素)追加到动态数组/容器的末尾,也就是常说的 push_back / append。
这个push和我们理解的push不是一个push,我说怎么看起来总是怪怪的
这样之后我们的理解的话就可以了
main函数复杂的指令集的配凑,verify进行校验,最后根据校验标志位输出是否正确
main函数如下
__int64 __fastcall main(
int a1,
char **a2,
char **a3,
double a4,
__m128 a5,
__m128 a6,
__m128 a7,
double a8,
double a9,
__m128 a10,
__m128 a11)
{
__int64 v11; // rbp
double v12; // xmm4_8
double v13; // xmm5_8
char *v14; // rcx
__int64 v15; // rdx
__int64 v16; // rbx
_BYTE *v17; // rax
void *src; // rbp
__int64 n27; // r15
__m128 v20; // xmm0
__m128 v21; // xmm0
__m128 v22; // xmm0
__m128 v23; // xmm4
__m128 v24; // xmm0
_BYTE *v25; // xmm4_8
__m128 v26; // xmm5
__m128 v27; // xmm0
_BYTE *v28; // xmm5_8
__m128 v29; // xmm0
__m128 v30; // xmm0
__int64 v31; // rdx
std::ostream *v32; // rax
__int64 v34; // rax
__int64 v35; // rax
__int64 v36; // rdx
std::ostream *v37; // rax
_QWORD *v38; // rdi
__m128i v39; // [rsp+10h] [rbp-E8h] BYREF
__int64 v40; // [rsp+20h] [rbp-D8h]
void *p_src; // [rsp+30h] [rbp-C8h] BYREF
int v42; // [rsp+38h] [rbp-C0h]
int v43; // [rsp+3Ch] [rbp-BCh]
char *p_s; // [rsp+40h] [rbp-B8h]
int v45; // [rsp+48h] [rbp-B0h]
char v46; // [rsp+4Ch] [rbp-ACh]
char s[168]; // [rsp+50h] [rbp-A8h] BYREF
std::operator<<<std::char_traits<char>>(&std::cout, "Please enter your flag: ", a3);
v11 = *(__int64 *)((char *)&std::cin[2] + *(_QWORD *)(std::cin[0] - 24));
std::__istream_extract(std::cin, s, 100);
v14 = (char *)std::cin + *(_QWORD *)(std::cin[0] - 24);
if ( !*((_DWORD *)v14 + 8) && (unsigned __int64)(v11 - 1) > 0x63 )
{
v38 = (_QWORD *)*((_QWORD *)v14 + 29);
if ( v38[2] >= v38[3]
&& (*(unsigned int (__fastcall **)(_QWORD *, double, double, double, double, double, double, double, double))(*v38 + 72LL))(
v38,
a4,
*(double *)a5.m128_u64,
*(double *)a6.m128_u64,
*(double *)a7.m128_u64,
v12,
v13,
*(double *)a10.m128_u64,
*(double *)a11.m128_u64) == -1 )
{
std::ios::clear(
(char *)std::cin + *(_QWORD *)(std::cin[0] - 24),
*(_DWORD *)((char *)&std::cin[4] + *(_QWORD *)(std::cin[0] - 24)) | 2u);
}
}
if ( strlen(s) == 27 )
{
v16 = 0;
v17 = 0;
src = 0;
n27 = 0;
do
{
while ( 1 )
{
LOBYTE(p_src) = 16;
if ( (_BYTE *)v16 == v17 )
{
v39.m128i_i64[0] = (__int64)src;
v39.m128i_i64[1] = v16;
v40 = v16;
sub_1B10((__int64)&v39, &p_src);
v20 = (__m128)_mm_load_si128(&v39);
src = (void *)v39.m128i_i64[0];
v16 = v40;
}
else
{
*v17 = 16;
a5 = (__m128)(unsigned __int64)(v17 + 1);
v20 = (__m128)_mm_unpacklo_epi64((__m128i)(unsigned __int64)src, (__m128i)a5);
}
a5 = _mm_movehl_ps(a5, v20);
LOBYTE(p_src) = 0;
if ( v16 == a5.m128_u64[0] )
{
v40 = v16;
v39 = (__m128i)v20;
sub_1B10((__int64)&v39, &p_src);
v21 = (__m128)_mm_load_si128(&v39);
src = (void *)v39.m128i_i64[0];
v16 = v40;
}
else
{
*(_BYTE *)a5.m128_u64[0] = 0;
a6 = (__m128)(a5.m128_u64[0] + 1);
v21 = (__m128)_mm_unpacklo_epi64((__m128i)(unsigned __int64)src, (__m128i)a6);
}
a6 = _mm_movehl_ps(a6, v21);
LOBYTE(p_src) = 32;
if ( v16 == a6.m128_u64[0] )
{
v40 = v16;
v39 = (__m128i)v21;
sub_1B10((__int64)&v39, &p_src);
v22 = (__m128)_mm_load_si128(&v39);
src = (void *)v39.m128i_i64[0];
v16 = v40;
}
else
{
*(_BYTE *)a6.m128_u64[0] = 32;
a7 = (__m128)(a6.m128_u64[0] + 1);
v22 = (__m128)_mm_unpacklo_epi64((__m128i)(unsigned __int64)src, (__m128i)a7);
}
a7 = _mm_movehl_ps(a7, v22);
LOBYTE(p_src) = 0;
if ( a7.m128_u64[0] == v16 )
{
v40 = v16;
v39 = (__m128i)v22;
sub_1B10((__int64)&v39, &p_src);
v24 = (__m128)_mm_load_si128(&v39);
src = (void *)v39.m128i_i64[0];
v16 = v40;
}
else
{
*(_BYTE *)a7.m128_u64[0] = 0;
v23 = (__m128)(a7.m128_u64[0] + 1);
v24 = (__m128)_mm_unpacklo_epi64((__m128i)(unsigned __int64)src, (__m128i)v23);
}
v25 = (_BYTE *)_mm_movehl_ps(v23, v24).m128_u64[0];
LOBYTE(p_src) = 17;
if ( (_BYTE *)v16 == v25 )
{
v40 = v16;
v39 = (__m128i)v24;
sub_1B10((__int64)&v39, &p_src);
v27 = (__m128)_mm_load_si128(&v39);
src = (void *)v39.m128i_i64[0];
v16 = v40;
}
else
{
*v25 = 17;
v26 = (__m128)(unsigned __int64)(v25 + 1);
v27 = (__m128)_mm_unpacklo_epi64((__m128i)(unsigned __int64)src, (__m128i)v26);
}
v28 = (_BYTE *)_mm_movehl_ps(v26, v27).m128_u64[0];
LOBYTE(p_src) = 48;
if ( v28 == (_BYTE *)v16 )
{
v40 = v16;
v39 = (__m128i)v27;
sub_1B10((__int64)&v39, &p_src);
v29 = (__m128)_mm_load_si128(&v39);
src = (void *)v39.m128i_i64[0];
v16 = v40;
}
else
{
*v28 = 48;
a10 = (__m128)(unsigned __int64)(v28 + 1);
v29 = (__m128)_mm_unpacklo_epi64((__m128i)(unsigned __int64)src, (__m128i)a10);
}
a10 = _mm_movehl_ps(a10, v29);
LOBYTE(p_src) = 0;
if ( v16 == a10.m128_u64[0] )
{
v40 = v16;
v39 = (__m128i)v29;
sub_1B10((__int64)&v39, &p_src);
v30 = (__m128)_mm_load_si128(&v39);
src = (void *)v39.m128i_i64[0];
v16 = v40;
}
else
{
*(_BYTE *)a10.m128_u64[0] = 0;
a11 = (__m128)(a10.m128_u64[0] + 1);
v30 = (__m128)_mm_unpacklo_epi64((__m128i)(unsigned __int64)src, (__m128i)a11);
}
a11 = _mm_movehl_ps(a11, v30);
LOBYTE(p_src) = n27;
if ( v16 == a11.m128_u64[0] )
break;
*(_BYTE *)a11.m128_u64[0] = n27++;
v17 = (_BYTE *)(a11.m128_u64[0] + 1);
if ( n27 == 27 )
goto LABEL_23;
}
v40 = v16;
v39 = (__m128i)v30;
sub_1B10((__int64)&v39, &p_src);
++n27;
v17 = (_BYTE *)v39.m128i_i64[1];
src = (void *)v39.m128i_i64[0];
v16 = v40;
}
while ( n27 != 27 );
LABEL_23:
LOBYTE(p_src) = -1;
if ( (_BYTE *)v16 == v17 )
{
v39.m128i_i64[0] = (__int64)src;
v39.m128i_i64[1] = v16;
v40 = v16;
sub_1B10((__int64)&v39, &p_src);
src = (void *)v39.m128i_i64[0];
v16 = v40;
}
else
{
*v17 = -1;
}
p_src = src;
v42 = 0;
v43 = 0;
p_s = s;
v45 = 0;
v46 = 1;
verify(&p_src);
if ( v46 )
v32 = (std::ostream *)std::operator<<<std::char_traits<char>>(
&std::cout,
"Congratulations! The flag is correct.",
v31);
else
v32 = (std::ostream *)std::operator<<<std::char_traits<char>>(&std::cout, "Wrong! Try again.", v31);
sub_1970(v32);
if ( src )
operator delete(src, v16 - (_QWORD)src);
return 0;
}
else
{
v34 = std::operator<<<std::char_traits<char>>(&std::cout, "Wrong! (Length mismatch. Expected: ", v15);
v35 = std::ostream::_M_insert<unsigned long>(v34, 27);
v37 = (std::ostream *)std::operator<<<std::char_traits<char>>(v35, ")", v36);
sub_1970(v37);
return 1;
}
}我们还原结构体可以看出来逻辑
p_src.code_ptr = src;
p_src.ip = 0;
*(_DWORD *)p_src.regs = 0;
p_src.input_ptr = s;
p_src.in_pos = 0;
p_src.ok = 1;
verify(&p_src);
if ( p_src.ok )
v32 = (std::ostream *)std::operator<<<std::char_traits<char>>(
&std::cout,
"Congratulations! The flag is correct.",
v31);在校验中我们只要维持好这个p_src.ok的标志位即可
verify函数如下(还原结构体)
可以加上下面的这些提示词
构建没有ida_struct模块的结构体
用户希望通过IDAPython脚本创建结构体,而不使用ida_struct模块。我们可以通过idc.set_local_type定义本地类型(Local Types),并应用显式填充数组来对齐结构体。定义的结构体vm_ctx_t会使用#pragma pack以确保字节对齐,且包含适当的内存填充。
导入下面结构体
typedef struct vm_ctx_t
{
unsigned char *code_ptr; // +0x00
int ip; // +0x08
unsigned char regs[4]; // +0x0C (verify: ctx->regs[reg] == *((BYTE*)ctx + reg + 12))
char *input_ptr; // +0x10
int in_pos; // +0x18
unsigned char ok; // +0x1C
unsigned char _pad1D[3]; // +0x1D
} vm_ctx_t;verify的函数如下
vm_ctx_t *__fastcall verify(vm_ctx_t *ctx)
{
vm_ctx_t *ctx_1; // rax
unsigned __int8 *code_ptr; // rdi
__int64 ip; // rcx
unsigned __int8 n0x20; // si
int v5; // edx
int v6; // ecx
unsigned __int8 v7; // cl
__int64 in_pos; // rsi
char *v9; // rdx
__int64 v10; // rcx
__int64 v11; // rcx
__int64 n0x1A; // rdx
unsigned __int8 v13; // cl
ctx_1 = ctx;
code_ptr = ctx->code_ptr;
while ( 1 )
{
while ( 1 )
{
while ( 1 )
{
ip = ctx_1->ip;
n0x20 = code_ptr[ip];
v5 = ctx_1->ip;
v6 = ip + 1;
ctx_1->ip = v6;
if ( n0x20 != 0x20 )
break;
ctx_1->ip = v5 + 2;
v13 = code_ptr[v6];
ctx_1->ip = v5 + 3;
ctx_1->regs[v13] ^= code_ptr[v5 + 2];
}
if ( n0x20 > 0x20u )
break;
if ( n0x20 == 16 )
{
ctx_1->ip = v5 + 2;
in_pos = ctx_1->in_pos;
v9 = &ctx_1->input_ptr[in_pos];
if ( !*v9 )
goto LABEL_14;
v10 = code_ptr[v6];
ctx_1->in_pos = in_pos + 1;
ctx_1->regs[v10] = *v9;
}
else
{
if ( n0x20 != 17 )
goto LABEL_9;
ctx_1->ip = v5 + 2;
v7 = code_ptr[v6];
ctx_1->ip = v5 + 3;
ctx_1->regs[v7] = code_ptr[v5 + 2];
}
}
if ( n0x20 != 0x30 )
break;
ctx_1->ip = v5 + 2;
v11 = code_ptr[v6];
ctx_1->ip = v5 + 3;
n0x1A = code_ptr[v5 + 2];
if ( (unsigned __int8)n0x1A > 0x1Au || ctx_1->regs[v11] != aWPvjL[n0x1A] )
LABEL_14:
ctx_1->ok = 0;
}
if ( n0x20 == 0xFF )
return ctx_1;
LABEL_9:
ctx_1->ok = 0;
return ctx_1;
}这里的话就是一个简单的异或
main函数复杂填充指令,然后进入verify函数进行验证
aWPvjL = (
b"w}pvj" +
bytes([0x27]) +
b"#&(<(#)!<\"#&" + # 这里包含一个双引号,需要转义
bytes([0x27]) +
b"< %$ %l" # 注意:< 后面是两个空格
)
assert len(aWPvjL) == 27
flag = bytes([b ^ 0x11 for b in aWPvjL]).decode("ascii")
print(flag)第三题:baby_rc4
upx魔改的壳,需要修改成55 50 58 21这个序列
之后就是rc4解密,这里看上去很复杂,实际上就是一个初始化s盒,然后再利用s盒进行加密
也就是
KSA = Key Scheduling Algorithm(密钥调度算法)
PRGA = Pseudo-Random Generation Algorithm(伪随机生成算法)
这个题目魔改rc4是改了最后的处理的过程
key = b"happynewyear"
cipher = bytes([
0x19,0x9D,0xDF,0x8D,0xED,0x42,0xAB,0x52,0x7E,0x25,
0xC8,0xD2,0x48,0x56,0xEA,0xAB,0x60,0x94,0xCF,0x7E,
0x66,0x4D,0x1C,0xE2,0x62,0x21,0xC7,0xAE,0xFD,0x39
])
# KSA
S = list(range(256))
j = 0
for i in range(256):
j = (j + S[i] + key[i % len(key)]) & 0xFF
S[i], S[j] = S[j], S[i]
# PRGA + decrypt (plain = cipher + keystream)
i = j = 0
plain = bytearray()
for c in cipher:
i = (i + 1) & 0xFF
j = (j + S[i]) & 0xFF
S[i], S[j] = S[j], S[i]
k = S[(S[i] + S[j]) & 0xFF]
plain.append((c + k) & 0xFF)
print(plain.decode())讲解一下rc4,主要是由下面这两个部分组成的
A. KSA:Key Scheduling Algorithm(密钥调度/初始化)
用用户给的 key,把内部状态 S 盒(长度 256 的数组)洗牌。
- 初始:
S[i] = i(0..255) - 然后用 key 反复参与交换,让 S 变成一个“依赖 key 的置换”。
S = [0,1,2,...,255]
j = 0
for i in 0..255:
j = (j + S[i] + key[i mod keylen]) mod 256
swap(S[i], S[j])B. PRGA:Pseudo-Random Generation Algorithm(生成密钥流)
每输出 1 个字节:
- 更新两个指针 i、j
- 交换 S[i], S[j]
- 从 S 里取出 1 个字节作为 keystream byte
i = 0, j = 0
repeat for each output byte:
i = (i + 1) mod 256
j = (j + S[i]) mod 256
swap(S[i], S[j])
t = (S[i] + S[j]) mod 256
out = S[t] # 这就是 keystream byte最后:
cipher[i] = plain[i] XOR keystream[i]- 解密同理:
plain[i] = cipher[i] XOR keystream[i]
第四题:WebAssembly
wasm类型的题目,通过这个题目可以深度理解轮秘钥和密钥流的区别。简单说一下
轮密钥确实是从某个“主密钥/输入信息”派生出来的多个子密钥,用来在多轮里不断搅拌数据。
密钥流通常来自一个“可生成任意长度输出”的生成器(PRNG/流密码结构),它的核心特征是:
给一个 seed/state,就能按需吐出 1 字节、1KB、1MB… 的伪随机字节序列,直接拿来 XOR。
这个题目的关键的变量如下:
user:用户名字符串(C 里const char*,JS 里普通字符串)
pass:密码字符串(要求 16 bytes;C 里当作 16 个字节处理)
keys[0..7]:8 个 64-bit 的轮密钥(每个 8 字节,总计 64 字节)
mixed[16]:Feistel 变换输出(16 字节)
TARGET[16]:固定常量(16 字节),用于验证密码是否正确
seed:64-bit 种子(8 字节)
keystream[n]:密钥流(n 字节,题里 n=39)
FLAG_CIPHERTEXT[39]:固定密文(39 字节)
flag:解密结果(39 字节左右的可打印字符串)
这里的flag获取是有两种方法的,一种是输入正确的账号和密码,等待wasm机制自动弹出来flag
还有一种更加暴力的,直接溯源flag弹出来机制还原出来flag,另一种的还原flag也是基于第一种的方法。
第一种的一个是需要绕过的几点
用户名是哈希,但并不是用的常见的sha哈希,而是fnv-1a哈希
密码是写死的,需要与target一样,而这个加密是并不是常见aes加密等,而是feistel分组变换,这里的分组变换的秘钥加密来源于一开始我们输入的用户名,了解了这些我们就能理清楚了,还原出来target就能拿到正确的密码了
另一种直接还原flag需要额外注意下面这几点
首先是需要求解出来mix的数值,然后利用这个数值去求密钥流,用这个密钥流解密密文获取flag
1)验账号(user)
- wasm 先对 user 做 FNV-1a 32-bit 哈希
- 必须等于固定常量
0x477DDD25,不等就直接失败(输出 “bad user”)
// 32-bit FNV-1a
uint32_t fnv1a32(const char *s) {
uint32_t h = 2166136261u; // 0x811C9DC5
while (*s) {
h ^= (uint8_t)(*s); // XOR 1 byte
h *= 16777619u; // 0x01000193 (mod 2^32)
s++;
}
return h;
}
// check
if (fnv1a32(user) != 0x477DDD25u) fail("bad user");2)验密码(pass,必须 16 字节)
这里迷的话是usr用来初始化s状态量,这个s的存在是获取轮秘钥的关键。
- 用 user 生成 8 个 64-bit 的 keys[0..7](相当于“用户名派生出来的密钥”)
- 把你输入的 pass(16字节) 当成一个 128-bit 块
- 用 自制 Feistel 8 轮(不是 AES)把 pass 变换成
mixed(16字节) - 如果
mixed != TARGET(固定16字节)→ 密码错(输出 “bad password”) - 如果
mixed == TARGET→ 登录成功
//keys的产生
uint64_t rotl64(uint64_t x, int r) {
return (x << r) | (x >> (64 - r));
}
// 从 user 派生 keys[0..7]
void derive_keys_from_user(const char *user, uint64_t keys[8]) {
uint64_t s = 0xC3A5C85C97CB3127ULL; // 初始状态
const uint64_t K = 0x9E3779B97F4A7C15ULL; // 常量
// 用用户名逐字节搅拌 s(mod 2^64)
for (each byte c in user) {
s ^= (uint64_t)c + K + (s << 6) + (s >> 2);
s = rotl64(s, 9) ^ (s >> 3);
}
// 再从 s 导出 8 个 64-bit 轮密钥
for (int r = 0; r < 8; r++) {
s ^= (s >> 12);
s ^= (s << 25);
s ^= (s >> 27);
keys[r] = s * 2685821657736338717ULL; // (mod 2^64)
}
}
//轮函数的加密
uint64_t round_f(uint64_t x, uint64_t k) {
x += k;
x ^= rotl64(x, 17);
x += rotl64(x, 41);
x ^= (x >> 23);
x *= 0x9E3779B97F4A7C15ULL; // (mod 2^64)
x ^= (x >> 27);
return x;
}
uint64_t load64le(uint8_t b[8]); // 小端装载
void store64le(uint8_t out[8], uint64_t v);
void feistel16(uint8_t pass16[16], uint8_t mixed16[16], uint64_t keys[8]) {
uint64_t L = load64le(pass16 + 0); // pass 前8字节
uint64_t R = load64le(pass16 + 8); // pass 后8字节
for (int r = 0; r < 8; r++) {
uint64_t f = round_f(R, keys[r]);
uint64_t newL = R;
uint64_t newR = L ^ f;
L = newL;
R = newR;
}
store64le(mixed16 + 0, L);
store64le(mixed16 + 8, R);
}
// check
if (memcmp(mixed, TARGET, 16) != 0) fail("bad password");3)解 flag(只有登录成功才会跑到这一步)
这个seed是通过算法进行的自我拓展,和密码那一块的逻辑是有本质区别的
- 算 seed:
seed = LE64(mixed前8字节) XOR keys[0] XOR 0xA5A5...
“PRNG 状态”就是:伪随机数生成器(Pseudo-Random Number Generator)在某一时刻“记住的内部数据”。
- 用 seed 跑 xorshift64 生成一段 keystream(密钥流)
- 用密钥流把密文解出来:
flag = FLAG_CIPHERTEXT XOR keystream - 把得到的 flag 写到 outbuf 返回给 JS 显示
//产生seed种子,种子的含义确实挺不错的
uint64_t seed = load64le(mixed[0..7]) ^ keys[0] ^ 0xA5A5A5A5A5A5A5A5ULL;
// xorshift64* 的一次迭代(mod 2^64)
uint64_t xorshift64star(uint64_t x) {
x ^= (x >> 12);
x ^= (x << 25);
x ^= (x >> 27);
x *= 2685821657736338717ULL;
return x;
}
// 生成 n 字节密钥流:每次迭代产生 8 字节(小端输出)
void keystream(uint64_t seed, uint8_t *out, size_t n) {
uint64_t x = seed;
size_t off = 0;
while (off < n) {
x = xorshift64star(x);
uint8_t block[8];
store64le(block, x);
copy out[off..] = block[0..take-1];
off += take;
}
}
keystream(seed, ks, 39); // 题里 ct_len=39
for (i=0..38) flag[i] = FLAG_CIPHERTEXT[i] ^ ks[i];
flag[39] = 0;一个“前端本地 WASM 登录验证器”——用户输入用户名/密码后,JS 负责算一个 ticket 并显示,然后把用户名/密码交给 WASM 里的 authenticate 函数去判定对错,WASM 把结果(成功/失败 + 一段提示文本)返回给页面展示
user 决定 keys
keys + pass 决定 mixed
mixed(前8) + keys[0] 决定 seed
seed 决定 keystream
keystream XOR 固定密文 = flag
HTML 负责页面和交互,release.js 负责把 .wasm 加载起来并提供桥接能力,.wasm 里才是核心校验逻辑,crypto-js.js 只是额外算一个 SHA1 给你展示。
下面展示一下这个层级的关系
这里的内部代码的理解的话可以从Moudle这个进行关联突破
index.html
├── 引入 crypto-js.js ——> 提供 CryptoJS.SHA1(算 ticket,仅展示)
└── 引入 build/release.js
└── fetch/instantiate -> release.wasm
├── 导出 malloc/free/memory
└── 导出 authenticate(核心校验)
└── 初始化 Module: HEAPU8 / cwrap / UTF8ToString / _malloc/_free
└── 调用 Module.onRuntimeInitialized()
└── index.html 在回调里 cwrap 出 window._auth然后我们大体展示一下思路
存储计算函数
window._auth = Module.cwrap('authenticate', 'number', ['string', 'string', 'number', 'number']);进行核验
const ok = window._auth(user, pass, ptr, BUF);我们只要通过核验,就能给我们输出flag,我们需要做的就是考虑如何通过核验
我们通过阅读html可以知道
我们装载了crypto-js和release这两个js文件
crypto-js这个js作用是提供了sha1的算法
release.js的作用提供给了moule一定的功能函数
<script src="crypto-js.js"></script>
<script>
var Module = {
onRuntimeInitialized: function () {
window._auth = Module.cwrap('authenticate', 'number', ['string', 'string', 'number', 'number']);
document.getElementById('btn').disabled = false;
document.getElementById('out').textContent = 'wasm ready';
}
};
</script>
<script src="build/release.js"></script>
<script>
const out = document.getElementById('out');
document.getElementById('btn').onclick = () => {
const user = document.getElementById('user').value;
const pass = document.getElementById('pass').value;
const ticket = CryptoJS.SHA1(user + "|pepper|v2").toString();
const BUF = 256;
const ptr = Module._malloc(BUF);
Module.HEAPU8.fill(0, ptr, ptr + BUF);
const ok = window._auth(user, pass, ptr, BUF);
const msg = Module.UTF8ToString(ptr);
Module._free(ptr);
out.textContent = "ticket=" + ticket + "\n" + (ok ? ("[OK]\n" + msg) : ("[FAIL]\n" + msg));
};release.js的提供可以通过阅读得知这个是用来加载wasm的
(function (global) {
const Module = global.Module || (global.Module = {});
function utf8ToBytes(str) {
const out = new Uint8Array(str.length + 1);
for (let i = 0; i < str.length; i++) out[i] = str.charCodeAt(i) & 0xff;
out[str.length] = 0;
return out;
}
function UTF8ToString(heapU8, ptr) {
let s = '';
for (let p = ptr; heapU8[p] !== 0; p++) s += String.fromCharCode(heapU8[p]);
return s;
}
function cwrap(exports, heapU8, name, returnType, argTypes) {
const fn = exports[name];
if (typeof fn !== 'function') throw new Error('export not found: ' + name);
return function (...args) {
const allocs = [];
const callArgs = [];
for (let i = 0; i < argTypes.length; i++) {
const t = argTypes[i];
const v = args[i];
if (t === 'string') {
const b = utf8ToBytes(String(v));
const p = exports.malloc(b.length);
heapU8.set(b, p);
allocs.push(p);
callArgs.push(p);
} else {
callArgs.push(v | 0);
}
}
const ret = fn(...callArgs);
for (const p of allocs) exports.free(p);
return ret;
};
}
async function init() {
const scriptURL = (typeof document !== 'undefined' && document.currentScript)
? document.currentScript.src
: '';
const wasmURL = new URL('release.wasm', scriptURL || (typeof location !== 'undefined' ? location.href : ''));
const resp = await fetch(wasmURL);
const bytes = await resp.arrayBuffer();
const { instance } = await WebAssembly.instantiate(bytes, {
env: {
}
});
Module.instance = instance;
Module.exports = instance.exports;
Module.memory = instance.exports.memory;
Module.HEAPU8 = new Uint8Array(Module.memory.buffer);
Module._malloc = instance.exports.malloc;
Module._free = instance.exports.free;
Module.UTF8ToString = (ptr) => UTF8ToString(Module.HEAPU8, ptr);
Module.cwrap = (name, returnType, argTypes) => cwrap(instance.exports, Module.HEAPU8, name, returnType, argTypes);
if (typeof Module.onRuntimeInitialized === 'function') {
Module.onRuntimeInitialized();
}
}
init().catch((e) => {
const msg = '[release.js] init failed: ' + (e && e.message ? e.message : String(e));
if (typeof console !== 'undefined') console.error(e);
if (typeof document !== 'undefined') {
const pre = document.getElementById('out');
if (pre) pre.textContent = msg;
}
});
})(typeof window !== 'undefined' ? window : globalThis);
题目源码
因为题目很抽象,所以要了wasm的题目源码
如果说硬看反汇编,那确实是很强了
#include <stdint.h>
#include <stddef.h>
// ---- tiny libc subset (no stdlib) ----
static size_t my_strlen(const char* s) {
size_t n = 0;
while (s[n] != 0) n++;
return n;
}
static void my_memcpy(uint8_t* dst, const uint8_t* src, size_t n) {
for (size_t i = 0; i < n; i++) dst[i] = src[i];
}
static int my_memcmp(const uint8_t* a, const uint8_t* b, size_t n) {
for (size_t i = 0; i < n; i++) {
if (a[i] != b[i]) return (int)a[i] - (int)b[i];
}
return 0;
}
static void write_msg(uint8_t* out, int out_len, const char* msg) {
if (out_len <= 0) return;
int i = 0;
for (; i < out_len - 1 && msg[i]; i++) out[i] = (uint8_t)msg[i];
out[i] = 0;
}
// ---- bump allocator ----
extern uint8_t __heap_base;
static uint32_t heap_ptr = 0;
__attribute__((export_name("malloc")))
uint32_t malloc(uint32_t n) {
if (heap_ptr == 0) heap_ptr = (uint32_t)(uintptr_t)(&__heap_base);
// align 8
heap_ptr = (heap_ptr + 7) & ~7u;
uint32_t p = heap_ptr;
heap_ptr += n;
return p;
}
__attribute__((export_name("free")))
void free(uint32_t p) {
(void)p; // no-op for bump allocator
}
// ---- crypto-ish core ----
static uint64_t rotl64(uint64_t x, unsigned r) {
return (x << r) | (x >> (64 - r));
}
static uint32_t fnv1a32(const char* s) {
uint32_t h = 2166136261u;
for (; *s; s++) {
h ^= (uint8_t)(*s);
h *= 16777619u;
}
return h;
}
static uint64_t round_f(uint64_t x, uint64_t k) {
x += k;
x ^= rotl64(x, 17);
x += rotl64(x, 41);
x ^= (x >> 23);
x *= 0x9E3779B97F4A7C15ULL;
x ^= (x >> 27);
return x;
}
static void derive_keys_from_user(const char* user, uint64_t keys[8]) {
uint64_t s = 0xC3A5C85C97CB3127ULL;
for (size_t i = 0; user[i]; i++) {
uint64_t c = (uint8_t)user[i];
s ^= (c + 0x9e3779b97f4a7c15ULL + (s << 6) + (s >> 2));
s = rotl64(s, 9) ^ (s >> 3);
}
for (int r = 0; r < 8; r++) {
s ^= (s >> 12);
s ^= (s << 25);
s ^= (s >> 27);
keys[r] = s * 2685821657736338717ULL;
}
}
static uint64_t load64le(const uint8_t* p) {
uint64_t v = 0;
for (int i = 7; i >= 0; i--) {
v = (v << 8) | p[i];
}
return v;
}
static void store64le(uint8_t* p, uint64_t v) {
for (int i = 0; i < 8; i++) {
p[i] = (uint8_t)(v & 0xFF);
v >>= 8;
}
}
static void feistel16(const uint8_t in[16], uint8_t out[16], const uint64_t keys[8]) {
uint64_t L = load64le(in);
uint64_t R = load64le(in + 8);
for (int r = 0; r < 8; r++) {
uint64_t f = round_f(R, keys[r]);
uint64_t newL = R;
uint64_t newR = L ^ f;
L = newL;
R = newR;
}
store64le(out, L);
store64le(out + 8, R);
}
static void xorshift_stream(uint64_t seed, uint8_t* out, size_t n) {
uint64_t x = seed;
size_t off = 0;
while (off < n) {
x ^= (x >> 12);
x ^= (x << 25);
x ^= (x >> 27);
x *= 2685821657736338717ULL;
uint8_t blk[8];
store64le(blk, x);
size_t take = (n - off) < 8 ? (n - off) : 8;
my_memcpy(out + off, blk, take);
off += take;
}
}
// === generated constants ===
// (filled by tools/gen_constants.py)
static const uint8_t TARGET[16] = { 0x9f, 0x3c, 0xc3, 0x76, 0x6f, 0x84, 0xcb, 0xae, 0x51, 0x99, 0x3f, 0xbf, 0x15, 0x63, 0x4b, 0x66 };
static const uint8_t FLAG_CIPHERTEXT[39] = { 0x90, 0xcf, 0x44, 0x4a, 0x5d, 0xa4, 0x5f, 0x8c, 0x87, 0xd5, 0x42, 0x01, 0x2e, 0xbc, 0xbf, 0x5a, 0x54, 0x54, 0x6b, 0x92, 0xcc, 0x67, 0xac, 0x56, 0xbc, 0x06, 0xa6, 0x7c, 0x16, 0xee, 0x0d, 0xe6, 0x61, 0x1c, 0xfb, 0xc6, 0x39, 0x55, 0x84 };
static const uint32_t USER_HASH = 0x477ddd25u;
__attribute__((export_name("authenticate")))
int authenticate(const char* user, const char* pass, uint8_t* out_flag, int out_len) {
if (!user || !pass || !out_flag || out_len <= 0) return 0;
if (fnv1a32(user) != USER_HASH) {
write_msg(out_flag, out_len, "bad user");
return 0;
}
// This build requires 16-byte password.
size_t plen = my_strlen(pass);
if (plen != 16) {
write_msg(out_flag, out_len, "password must be 16 bytes");
return 0;
}
uint64_t keys[8];
derive_keys_from_user(user, keys);
// Treat password as raw 16 bytes (avoid relying on C-string traversal later)
uint8_t key[16];
my_memcpy(key, (const uint8_t*)pass, 16);
uint8_t mixed[16];
feistel16(key, mixed, keys);
if (my_memcmp(mixed, TARGET, 16) != 0) {
write_msg(out_flag, out_len, "bad password");
return 0;
}
// decrypt flag
const size_t ct_len = sizeof(FLAG_CIPHERTEXT);
if (out_len < (int)ct_len + 1) return 0;
uint64_t seed = load64le(mixed) ^ keys[0] ^ 0xA5A5A5A5A5A5A5A5ULL;
uint8_t ks[256];
if (ct_len > sizeof(ks)) return 0;
xorshift_stream(seed, ks, ct_len);
for (size_t i = 0; i < ct_len; i++) out_flag[i] = FLAG_CIPHERTEXT[i] ^ ks[i];
out_flag[ct_len] = 0;
return 1;
}最终的exp如下
MASK64 = 0xFFFFFFFFFFFFFFFF
#对应i64.rotl
def rotl64(x, r):
return ((x << r) & MASK64) | (x >> (64 - r))
#FNV-1a 32-bit
def fnv1a32(s: str) -> int:
h = 2166136261
for b in s.encode():
h ^= b
h = (h * 16777619) & 0xFFFFFFFF
return h
def round_f(x, k):
x = (x + k) & MASK64
x ^= rotl64(x, 17)
x = (x + rotl64(x, 41)) & MASK64
x ^= (x >> 23)
x = (x * 0x9E3779B97F4A7C15) & MASK64
x ^= (x >> 27)
return x & MASK64
#根据 username 派生出 8 个 64bit 轮密钥 (keys)
def derive_keys_from_user(user: str):
s = 0xC3A5C85C97CB3127
for c in user.encode():
s ^= (c + 0x9e3779b97f4a7c15 + ((s << 6) & MASK64) + (s >> 2)) & MASK64
s = (rotl64(s, 9) ^ (s >> 3)) & MASK64
keys = []
for _ in range(8):
s ^= (s >> 12)
s ^= ((s << 25) & MASK64)
s ^= (s >> 27)
keys.append((s * 2685821657736338717) & MASK64)
return keys
#从 mixed16反推password
def feistel_inv_from_target(mixed16: bytes, keys):
L = int.from_bytes(mixed16[:8], "little")
R = int.from_bytes(mixed16[8:], "little")
for r in reversed(range(8)):
oldR = L
f = round_f(L, keys[r])
oldL = (R ^ f) & MASK64
L, R = oldL, oldR
return L.to_bytes(8, "little") + R.to_bytes(8, "little")
#生成 keystream
def xorshift_stream(seed: int, n: int) -> bytes:
out = bytearray()
x = seed & MASK64
while len(out) < n:
x ^= (x >> 12)
x ^= ((x << 25) & MASK64)
x ^= (x >> 27)
x = (x * 2685821657736338717) & MASK64
out.extend(x.to_bytes(8, "little"))
return bytes(out[:n])
USER_HASH = 0x477DDD25
target = bytes.fromhex("9f3cc3766f84cbae51993fbf15634b66")
miwen = bytes.fromhex(
"90cf444a5da45f8c87d542012ebcbf5a"
"54546b92cc67ac56bc06a67c16ee0de6"
"611cfbc6395584"
)
user = "Et11an"
assert fnv1a32(user) == USER_HASH
keys = derive_keys_from_user(user)
password = feistel_inv_from_target(target, keys)
print("password:", password.decode())
seed = int.from_bytes(target[:8], "little") ^ keys[0] ^ 0xA5A5A5A5A5A5A5A5
ks = xorshift_stream(seed, len(miwen))
flag = bytes(a ^ b for a, b in zip(miwen, ks))
print("flag:", flag.decode())