Giải tuyển quân Team T vừa diễn ra, và mình giải được 2 câu crypto, 1 câu trong và 1 câu sau giải.

nLCG

Đề

from secrets import randbelow 
from Crypto.Util.number import getPrime
import sys
with open('/flag.txt','r') as f:
    flag = f.read().strip()

part1, part2 = flag[:len(flag)//2], flag[len(flag)//2:]
class LCG:
    def __init__(self):
        self.m = getPrime(256)
        self.a = randbelow(self.m - 1)
        self.c = randbelow(self.m - 1)
        self.x = randbelow(self.m - 1)

    def __call__(self):
        self.x = (self.a * self.x + self.c) % self.m
        return self.x 
    
class nLCG: 
    def __init__(self):
        self.m = getPrime(256)
        self.a = randbelow(self.m - 1)
        self.b = randbelow(self.m - 1)
        self.c = randbelow(self.m - 1)
        self.x = randbelow(self.m - 1)
        while True:
            self.A = randbelow(self.m - 1)
            self.B = randbelow(self.m - 1)
            self.C = randbelow(self.m - 1)
            self.D = randbelow(self.m - 1)
            if (self.A * self.D - self.B * self.C) % self.m != 0:
                break

    def __call__(self):
        self.x = (self.a * self.x**2 + self.b * self.x + self.c) % self.m
        return self.x
    
    def transform(self, x):
        return (self.A * x + self.B) * pow(self.C * x + self.D, -1, self.m) % self.m
    
def chall1(): 
    print("First part: ")
    lcg = LCG()
    print("I will give you some hint")
    for _ in range(5):
        print(lcg())
        sys.stdout.flush()
    win = True 
    for _ in range(3): 
        chall = lcg()
        guess = int(input("Can you guess the number? ")) 
        if guess != chall: 
            win = False 
    if win:
        print(part1)
    else:
        print("Suck my dick!")
        sys.exit(0)

def chall2():
    print("Second part: ")
    nlcg = nLCG()
    print("You will need this ")
    print(f"A = {nlcg.A}")
    print(f"B = {nlcg.B}")
    print(f"C = {nlcg.C}")
    print(f"D = {nlcg.D}")
    print("Now there will be no more hints")
    for _ in range(10):
        print(nlcg.transform(nlcg()))
        sys.stdout.flush()
    win = True
    for _ in range(3):
        chall = nlcg()
        guess = int(input("Can you guess the number? "))
        if guess != chall:
            win = False
    if win:
        print(part2)
    else:
        print("Suck my dick!")
        sys.exit(0)
        
MENU = """Choose an option:
1. Solve for first part
2. Solve for second part
3. Exit
> """
while True: 
    choice = input(MENU)
    if choice == "1":
        chall1()
    elif choice == "2":
        chall2()
    elif choice == "3":
        sys.exit(0)

Phân tích và ý tưởng

Part 1

class LCG:
    def __init__(self):
        self.m = getPrime(256)
        self.a = randbelow(self.m - 1)
        self.c = randbelow(self.m - 1)
        self.x = randbelow(self.m - 1)

    def __call__(self):
        self.x = (self.a * self.x + self.c) % self.m
        return self.x 
def chall1(): 
    print("First part: ")
    lcg = LCG()
    print("I will give you some hint")
    for _ in range(5):
        print(lcg())
        sys.stdout.flush()
    win = True 
    for _ in range(3): 
        chall = lcg()
        guess = int(input("Can you guess the number? ")) 
        if guess != chall: 
            win = False 
    if win:
        print(part1)
    else:
        print("Suck my dick!")
        sys.exit(0)

LCG của phần 1 là một bản LCG thông thường, các state được tính theo công thức xn+1≡axn+c(modm)x_{n+1} \equiv ax_n+c\pmod{m} Đề cho ta biết trước 5 states đầu của LCG, nếu biết a,ca, c có thể thay vào công thức và tính được các state tiếp theo. Nhưng phần này lại không cho biết mm, vì thế ta phải tìm lại mm trước khi tìm a,ca,c.

Ta có 5 states s0,s1,s2,s3,s4s_0,s_1,s_2,s_3,s_4, gọi t1,t2,t3,t4t_1,t_2,t_3,t_4 lần lượt là hiệu s1−s0,s2−s1,s3−s2,s4−s3s_1-s_0,s_2-s_1,s_3-s_2,s_4-s_3 Khi đó ta được

t1=s1−s0t2≡s2−s1≡as1+c−as0−c≡a(s1−s0)≡at1(modm)t3≡s3−s2≡as2+c−as1−c≡a(s2−s1)≡at2(modm)t4≡s4−s3≡as3+c−as2−c≡a(s3−s2)≡at3(modm)\begin{aligned} t_1& = s_1-s_0 \\ t_2& \equiv s_2-s_1 \equiv as_1+c-as_0-c \equiv a(s_1-s_0) \equiv at_1 \pmod{m}\\ t_3& \equiv s_3-s_2 \equiv as_2+c-as_1-c \equiv a(s_2-s_1) \equiv at_2 \pmod{m} \\ t_4& \equiv s_4-s_3 \equiv as_3+c-as_2-c \equiv a(s_3-s_2) \equiv at_3 \pmod{m} \end{aligned} ⇒t1−s1+s0≡0(modm)≡k1mt2−at1≡0(modm)≡k2mt3−at2≡0(modm)≡k3mt4−at3≡0(modm)≡k4m\Rightarrow \begin{aligned} t_1-s_1+s_0& \equiv 0 \pmod{m} \equiv k_1m\\ t_2-at_1& \equiv 0 \pmod{m} \equiv k_2m\\ t_3-at_2& \equiv 0 \pmod{m} \equiv k_3m\\ t_4-at_3& \equiv 0 \pmod{m} \equiv k_4m \end{aligned}

Khi này ta có thể tính GCD để tìm lại được mm, nhưng vì dính aa chưa biết nên có một trick để bỏ được aa, đó là lấy t1t3−t22t_1t_3-t_2^2 và t4t2−t32t_4t_2-t_3^2 Biểu diễn lại để thấy rõ hơn

t1t3−t22≡t1⋅at2−(at1)2≡t1⋅a⋅at1−(at1)2≡0(modm)t4t2−t32≡at3⋅at1−(at2)2≡a2⋅at2⋅t1−(a⋅at1)2≡a3⋅at1⋅t1−(a2⋅t1)2≡(a2⋅t1)2−(a2⋅t1)2≡0(modm)\begin{aligned} t_1t_3-t_2^2& \equiv t_1\cdot at_2-(at_1)^2 \\ &\equiv t_1\cdot a\cdot at_1-(at_1)^2 \\ &\equiv 0\pmod{m}\\ t_4t_2-t_3^2& \equiv at_3\cdot at_1-(at_2)^2 \\ &\equiv a^2\cdot at_2\cdot t_1-(a\cdot at_1)^2\\ & \equiv a^3\cdot at_1\cdot t_1-(a^2\cdot t_1)^2 \\ &\equiv (a^2\cdot t_1)^2-(a^2\cdot t_1)^2 \\ &\equiv 0\pmod{m} \end{aligned}

Khi đó ta có được 2 giá trị k1mk_1m và k2mk_2m, chỉ cần tính GCD để tìm được mm, vì chỉ có 2 giá trị nên khả năng sẽ không ra được chính xác mm, phải factor thêm một lần để lấy được đúng số nguyên tố 256 bits.

Sau khi có được mm ta chỉ cần tính lại aa,bb theo công thức

xn+1≡axn+c(modm)xn+2≡axn+1+c(modm)⇒xn+2−xn+1≡a(xn+1−xn)(modm)⇔a≡(xn+2−xn+1)(xn+1−xn)−1(modm)c≡xn+1−axn(modm)\begin{aligned} x_{n+1}& \equiv ax_n+c\pmod{m} \\ x_{n+2}& \equiv ax_{n+1}+c\pmod{m} \\ \Rightarrow x_{n+2}-x_{n+1}& \equiv a(x_{n+1}-x_n)\pmod{m} \\ \Leftrightarrow a& \equiv (x_{n+2}-x_{n+1})(x_{n+1}-x_n)^{-1}\pmod{m} \\ c& \equiv x_{n+1}-ax_n\pmod{m} \end{aligned}

Sau khi có đủ aa, cc, mm ta chỉ việc thay vào LCG cùng với state mới nhất để tìm 3 states tiếp theo.

from pwn import *
from math import gcd
from functools import reduce
from sage.all import *


HOST = "45.122.249.68"
PORT = 10345
r = remote(HOST, PORT)

class LCG:
    def __init__(self, m, a, c, x):
        self.m = m
        self.a = a
        self.c = c
        self.x = x

    def __call__(self):
        self.x = (self.a * self.x + self.c) % self.m
        return self.x 

class nLCG: 
    def __init__(self, m, a, b, c, x):
        self.m = m
        self.a = a
        self.b = b
        self.c = c
        self.x = x

    def __call__(self):
        self.x = (self.a * self.x**2 + self.b * self.x + self.c) % self.m
        return self.x
    
    def transform(self, x):
        return (self.A * x + self.B) * pow(self.C * x + self.D, -1, self.m) % self.m


def crack_unknown_modulus(states):
    diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])]
    zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])]
    modulus = abs(reduce(gcd, zeroes))
    return modulus

r.recvuntil(b"> ")
r.sendline(b"1")
r.recvuntil(b"I will give you some hint\n")
x1 = []
for i in range(5):
    x = r.recvline().strip().decode()
    x1.append(int(x))

m1 = crack_unknown_modulus(x1)
m1 = int(factor(m1)[-1][0])
a = (x1[2] - x1[1]) * pow(x1[1] - x1[0], -1, m1) % m1
c = (x1[1] - a * x1[0]) % m1
lcg = LCG(m1, a, c, x1[-1])

for i in range(3):
    r.recvuntil(b"Can you guess the number?")
    r.sendline(str(lcg()).encode())
print(r.recvline())

Part 2

class nLCG: 
    def __init__(self):
        self.m = getPrime(256)
        self.a = randbelow(self.m - 1)
        self.b = randbelow(self.m - 1)
        self.c = randbelow(self.m - 1)
        self.x = randbelow(self.m - 1)
        while True:
            self.A = randbelow(self.m - 1)
            self.B = randbelow(self.m - 1)
            self.C = randbelow(self.m - 1)
            self.D = randbelow(self.m - 1)
            if (self.A * self.D - self.B * self.C) % self.m != 0:
                break

    def __call__(self):
        self.x = (self.a * self.x**2 + self.b * self.x + self.c) % self.m
        return self.x
    
    def transform(self, x):
        return (self.A * x + self.B) * pow(self.C * x + self.D, -1, self.m) % self.m
    
def chall2():
    print("Second part: ")
    nlcg = nLCG()
    print("You will need this ")
    print(f"A = {nlcg.A}")
    print(f"B = {nlcg.B}")
    print(f"C = {nlcg.C}")
    print(f"D = {nlcg.D}")
    print("Now there will be no more hints")
    for _ in range(10):
        print(nlcg.transform(nlcg()))
        sys.stdout.flush()
    win = True
    for _ in range(3):
        chall = nlcg()
        guess = int(input("Can you guess the number? "))
        if guess != chall:
            win = False
    if win:
        print(part2)
    else:
        print("Suck my dick!")
        sys.exit(0)

Ở phần 2 các state của nLCG được tính theo công thức xn+1≡axn2+bxn+c(modm)x_{n+1} \equiv ax_n^2+bx_n+c\pmod{m} Đồng thời nLCG có thêm hàm transform để thay đổi giá trị xx y≡(Ax+B)(Cx+D)−1(modm)y \equiv (Ax+B)(Cx+D)^{-1}\pmod{m}

Vấn đề vẫn là tìm lại được các hệ số a,b,ca,b,c và mm. Và đề cho biết A,B,C,DA,B,C,D cùng với 10 states bị transform của nLCG.

y1≡(Ax1+B)(Cx1+D)−1(modm)y2≡(Ax2+B)(Cx2+D)−1(modm)⋮y10≡(Ax10+B)(Cx10+D)−1(modm)\begin{aligned} y_1& \equiv (Ax_1+B)(Cx_1+D)^{-1}\pmod{m} \\ y_2& \equiv (Ax_2+B)(Cx_2+D)^{-1}\pmod{m} \\ \vdots \\ y_{10}& \equiv (Ax_{10}+B)(Cx_{10}+D)^{-1}\pmod{m} \end{aligned}

Cách tìm mm cũng tương tự phần 1, phải tìm được sự liên kết giữa các states liên tiếp, từ đó tìm cách cô lập kmkm sang một bên và tìm lại mm bằng GCD. Ta gọi xn+1≡f(xn)≡axn2+bxn+c(modm)x_{n+1} \equiv f(x_n) \equiv ax_n^2+bx_n+c\pmod{m} và y≡g(x)≡(Ax+B)(Cx+D)−1(modm)y \equiv g(x) \equiv (Ax+B)(Cx+D)^{-1}\pmod{m} ⇒x≡g−1(y)\Rightarrow x \equiv g^{-1}(y), g−1(y)g^{-1}(y) là hàm ngược của g(x)g(x) với yn+1≡g(xn+1)≡(Axn+1+B)(Cxn+1+D)−1(modm)y_{n+1} \equiv g(x_{n+1}) \equiv (Ax_{n+1}+B)(Cx_{n+1}+D)^{-1}\pmod{m} ⇒yn+1≡g(f(xn))\Rightarrow y_{n+1} \equiv g(f(x_n)) ⇒yn+1≡g(f(g−1(yn)))\Rightarrow y_{n+1} \equiv g(f(g^{-1}(y_n)))

Khi này ta đã biểu diễn được yn+1y_{n+1} qua yny_n, phương trình này có dạng

yn+1≡(qyn2+ryn+s)(tyn2+uyn+v)−1(modm)(tyn2+uyn+v)yn+1≡qyn2+ryn+s(modm)tyn+1yn2+uyn+1yn+vyn+1−qyn2−ryn−s≡0(modm)\begin{aligned} y_{n+1} \equiv (qy_n^2+ry_n+s)(ty_n^2+uy_n+v)^{-1}\pmod{m} \\ (ty_n^2+uy_n+v)y_{n+1} \equiv qy_n^2+ry_n+s\pmod{m} \\ ty_{n+1}y_n^2+uy_{n+1}y_n+vy_{n+1}-qy_n^2-ry_n-s \equiv 0\pmod{m} \end{aligned}

Khi này đã trở thành phương trình 6 ẩn với các hệ số lần lượt là yn+1yn2  ;  yn+1yn  ;  yn+1;−yn2;−yn;−1y_{n+1}y_n^2 \;; \;y_{n+1}y_n\;;\;y_{n+1};-y_n^2;-y_n;-1

Lúc này ta có thể lập được hệ phương trình 6 ẩn, tức ma trận 6x6, và với 10 transformed states được cho, ta tạo được nhiều ma trận 6x6. Ta tìm lại mm bằng cách tính GCD của các định thức của các ma trận 6x6 tạo nên, vì det của các ma trận phải bằng 0(modm)0\pmod{m} (do hệ phương trình có nghiệm không tầm thường)

ví dụ một ma trận có thể tạo thành

(y1y02y1y0y1−y02−y0−1y2y12y2y1y2−y12−y1−1y3y22y3y2y3−y22−y2−1y4y32y4y3y4−y32−y3−1y5y42y5y4y5−y42−y4−1y6y52y6y5y6−y52−y5−1)\begin{pmatrix} y_1y_0^2 & y_1y_0 & y_1 & -y_0^2 & -y_0 & -1 \\ y_2y_1^2 & y_2y_1 & y_2 & -y_1^2 & -y_1 & -1 \\ y_3y_2^2 & y_3y_2 & y_3 & -y_2^2 & -y_2 & -1 \\ y_4y_3^2 & y_4y_3 & y_4 & -y_3^2 & -y_3 & -1 \\ y_5y_4^2 & y_5y_4 & y_5 & -y_4^2 & -y_4 & -1 \\ y_6y_5^2 & y_6y_5 & y_6 & -y_5^2 & -y_5 & -1 \end{pmatrix} M⋅(tuvqrs)≡0(modm)M \cdot \begin{pmatrix} t\\ u\\ v\\ q\\ r\\ s \end{pmatrix} \equiv 0 \pmod{m}

Khi này ta được det(M)≡0(modm)=kim\text{det}(M) \equiv 0\pmod{m}=k_im, ta quay lại bài toán tính GCD để tìm lại mm, và giống như phần 1, mm cũng cần factor để lấy đúng số nguyên tố 256 bits .

Sau khi có được mm ta cần untransform các yy để tìm lại đúng state của nLCG, công thức là x=(yD−B)(A−Cy)−1(modm)x=(yD-B)(A-Cy)^{-1}\pmod{m}

Bước cuối cùng là khôi phục lại a,b,ca,b,c, ta có công thức tính state tiếp theo là xn+1=axn2+bxn+c(modm)x_{n+1}=ax_n^2+bx_n+c\pmod{m} Thấy rằng nếu ta có nhiều hơn 3 phương trình như trên, ta có thể lập được hệ phương trình 3 ẩn và giải tìm a,b,ca,b,c. ví dụ lập ma trận để giải hệ phương trình

(x02x01x12x11x22x21)⋅(abc)≡(x1x2x3)(modm)\begin{pmatrix} x_0^2 & x_0 & 1 \\ x_1^2 & x_1 & 1 \\ x_2^2 & x_2 & 1 \end{pmatrix} \cdot \begin{pmatrix} a \\ b \\ c \end{pmatrix} \equiv \begin{pmatrix} x_1 \\ x_2 \\ x_3 \end{pmatrix} \pmod{m} (abc)≡(x02x01x12x11x22x21)−1⋅(x1x2x3)(modm)\begin{pmatrix} a \\ b \\ c \end{pmatrix} \equiv \begin{pmatrix} x_0^2 & x_0 & 1 \\ x_1^2 & x_1 & 1 \\ x_2^2 & x_2 & 1 \end{pmatrix}^{-1} \cdot \begin{pmatrix} x_1 \\ x_2 \\ x_3 \end{pmatrix} \pmod{m}

Sau khi có đủ cả a,b,c,ma,b,c,m thì ta chỉ cần thay chúng vào cùng với state mới nhất để tính các state tiếp theo và gửi cho server để lấy flag.

from pwn import *
from math import gcd
from functools import reduce
from sage.all import *
r.recvuntil(b"> ")
r.sendline(b"2")
r.recvuntil(b"You will need this \n")
A = int(r.recvline().strip().decode()[4:])
B = int(r.recvline().strip().decode()[4:])
C = int(r.recvline().strip().decode()[4:])
D = int(r.recvline().strip().decode()[4:])

r.recvuntil( b'Now there will be no more hints\n')

def trans(xt, A, B, C, D, m):
    return (xt * D - B) * pow(- xt * C + A, -1, m) % m

x2t = []
for i in range(10):
    x2t.append(int(r.recvline().strip().decode()))

coeffs = []
for i in range(9):
    coeff = [x2t[i] ** 2 * x2t[i+1], x2t[i] * x2t[i+1], x2t[i+1], -x2t[i] ** 2, -x2t[i], -1]
    coeffs.append(coeff)
mat = []
for i in range(3):
    mat.append([x for x in coeffs[i:i+6]])

matrix = []
for i in range(3):
    matrix.append(Matrix(ZZ,mat[i]))

det = []
for i in range(3):
    det.append(matrix[i].determinant())

m2 = reduce(gcd,det)
m2 = int(factor(m2)[-1][0])

x2 = []
for i in range(10):
    x2.append(trans(x2t[i], A, B, C, D, m2))

ma = Matrix(Zmod(m2), [[x2[0] ** 2, x2[0], 1], [x2[1] ** 2, x2[1], 1], [x2[2] ** 2, x2[2], 1]])
vec = vector(Zmod(m2),[x2[1],x2[2],x2[3]])
a, b, c = ma.solve_right(vec)
nlcg = nLCG(m2, a, b, c, x2[-1])
for i in range(3):
    r.recvuntil(b"Can you guess the number?")
    r.sendline(str(nlcg()).encode())
print(r.recvline())

Script

from pwn import *
from math import gcd
from functools import reduce
from sage.all import *


HOST = "45.122.249.68"
PORT = 10345
r = remote(HOST, PORT)

class LCG:
    def __init__(self, m, a, c, x):
        self.m = m
        self.a = a
        self.c = c
        self.x = x

    def __call__(self):
        self.x = (self.a * self.x + self.c) % self.m
        return self.x 

class nLCG: 
    def __init__(self, m, a, b, c, x):
        self.m = m
        self.a = a
        self.b = b
        self.c = c
        self.x = x

    def __call__(self):
        self.x = (self.a * self.x**2 + self.b * self.x + self.c) % self.m
        return self.x
    
    def transform(self, x):
        return (self.A * x + self.B) * pow(self.C * x + self.D, -1, self.m) % self.m


def crack_unknown_modulus(states):
    diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])]
    zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])]
    modulus = abs(reduce(gcd, zeroes))
    return modulus

r.recvuntil(b"> ")
r.sendline(b"1")
r.recvuntil(b"I will give you some hint\n")
x1 = []
for i in range(5):
    x = r.recvline().strip().decode()
    x1.append(int(x))

m1 = crack_unknown_modulus(x1)
m1 = int(factor(m1)[-1][0])
a = (x1[2] - x1[1]) * pow(x1[1] - x1[0], -1, m1) % m1
c = (x1[1] - a * x1[0]) % m1
lcg = LCG(m1, a, c, x1[-1])

for i in range(3):
    r.recvuntil(b"Can you guess the number?")
    r.sendline(str(lcg()).encode())
print(r.recvline())
#============================================

r.recvuntil(b"> ")
r.sendline(b"2")
r.recvuntil(b"You will need this \n")
A = int(r.recvline().strip().decode()[4:])
B = int(r.recvline().strip().decode()[4:])
C = int(r.recvline().strip().decode()[4:])
D = int(r.recvline().strip().decode()[4:])

r.recvuntil( b'Now there will be no more hints\n')

def trans(xt, A, B, C, D, m):
    return (xt * D - B) * pow(- xt * C + A, -1, m) % m

x2t = []
for i in range(10):
    x2t.append(int(r.recvline().strip().decode()))

coeffs = []
for i in range(9):
    coeff = [x2t[i] ** 2 * x2t[i+1], x2t[i] * x2t[i+1], x2t[i+1], -x2t[i] ** 2, -x2t[i], -1]
    coeffs.append(coeff)
mat = []
for i in range(3):
    mat.append([x for x in coeffs[i:i+6]])

matrix = []
for i in range(3):
    matrix.append(Matrix(ZZ,mat[i]))

det = []
for i in range(3):
    det.append(matrix[i].determinant())

m2 = reduce(gcd,det)
m2 = int(factor(m2)[-1][0])

x2 = []
for i in range(10):
    x2.append(trans(x2t[i], A, B, C, D, m2))

ma = Matrix(Zmod(m2), [[x2[0] ** 2, x2[0], 1], [x2[1] ** 2, x2[1], 1], [x2[2] ** 2, x2[2], 1]])
vec = vector(Zmod(m2),[x2[1],x2[2],x2[3]])
a, b, c = ma.solve_right(vec)
nlcg = nLCG(m2, a, b, c, x2[-1])
for i in range(3):
    r.recvuntil(b"Can you guess the number?")
    r.sendline(str(nlcg()).encode())
print(r.recvline())

Bài này đối với mình khó vì mình không tìm ra được các bước liên kết yn+1y_{n+1} và yny_n để tìm lại mm nên ngồi mãi 8 tiếng không ra, nhưng nhờ có anh Đức nên mình mới có thể giải được.

Flag: W1{sometimes_all_you_need_is_a_pen_and_paper!}

Boincit

Đề

#!/usr/bin/env python3
import hashlib
import json
import os
import random
import sys

HERE = os.path.dirname(os.path.abspath(__file__))

with open(os.path.join(HERE, "flag.txt"), "r", encoding="utf-8") as f:
    FLAG = f.read().strip()


def dsha256(b: bytes) -> bytes:
    return hashlib.sha256(hashlib.sha256(b).digest()).digest()


def leaf_hash(item: bytes) -> bytes:
    return dsha256(item)


def node_hash(left: bytes, right: bytes) -> bytes:
    return dsha256(left + right)


def merkle_computation(leaves: list[bytes]) -> bytes:
    if len(leaves) == 0:
        return b"\x00" * 32
    count = 0
    inner = [None] * 32
    while count < len(leaves):
        h = leaves[count]
        count += 1
        level = 0
        while not (count & (1 << level)):
            h = dsha256(inner[level] + h)
            level += 1
        inner[level] = h

    level = 0
    while not (count & (1 << level)):
        level += 1
    h = inner[level]
    while count != (1 << level):
        h = dsha256(h + h)
        count += 1 << level
        level += 1
        while not (count & (1 << level)):
            h = dsha256(inner[level] + h)
            level += 1
    return h


def verify_proof(item: bytes, proof: list, root: bytes) -> bool:
    h = leaf_hash(item)
    for sib, is_left in proof:
        h = node_hash(sib, h) if is_left else node_hash(h, sib)
    return h == root


def parse_proof(raw: str) -> list:
    raw = raw.strip()
    if not raw:
        return []
    out = []
    for part in raw.split(","):
        part = part.strip()
        if not part:
            continue
        if ":" not in part:
            raise ValueError("Invalid proof pair format. Use <hash>:L or <hash>:R")
        h, d = part.split(":", 1)
        sibling = bytes.fromhex(h.strip())
        direction = d.strip().upper()
        if len(sibling) != 32:
            raise ValueError("Proof hashes must be 32 bytes")
        if direction not in {"L", "R"}:
            raise ValueError("Proof direction must be L or R")
        out.append((sibling, direction == "L"))
    return out


def main():
    sys.stdout.reconfigure(line_buffering=True)

    n = random.choice([n for n in range(100, 1001, 4) if (n & (n - 1)) != 0])

    print(f"[+] Number of leaf nodes: {n}")

    items = [os.urandom(32) for _ in range(n)]

    print("\n[+] Public Items:")
    print(json.dumps([itm.hex() for itm in items]))

    leaves = [leaf_hash(x) for x in items]
    root = merkle_computation(leaves)
    print(f"\n[*] Computed Merkle Root: {root.hex()}")

    try:
        idx_input = input(f"\nChoose target item index (0 to {n-1}): ").strip()
        target_idx = int(idx_input)
        if target_idx < 0 or target_idx >= n:
            print("[-] Error: Index out of range!")
            return
    except Exception:
        print("[-] Error: Invalid index format!")
        return

    target_item = items[target_idx]

    print("\nSubmit two DIFFERENT valid Merkle proofs for your target item.")
    print("Format: <hash1>:L,<hash2>:R,...")

    try:
        raw_proof_a = input("Proof A: ").strip()
        raw_proof_b = input("Proof B: ").strip()

        proofA = parse_proof(raw_proof_a)
        proofB = parse_proof(raw_proof_b)
    except Exception as e:
        print(f"[-] Parsing Error: {e}")
        return

    if proofA == proofB:
        print("[-] Failed: Proof A and Proof B must be DIFFERENT!")
        return

    if verify_proof(target_item, proofA, root) and verify_proof(target_item, proofB, root):
        print(f"[+] FLAG: {FLAG}")
    else:
        print(f"[-] Verification Failed!")


if __name__ == "__main__":
    main()

Phân tích và ý tưởng

Bài này đối với mình khá rối nên mình sẽ tóm tắt ý nghĩa các hàm và mối liên hệ trước. dsha256 và leaf_hash thực hiện băm SHA256 hai lần liên tục, node_hash gọi hàm dsha256 cho chuỗi nối hai plaintext khác nhau, merkle_computation tính giá trị root dùng để xác nhận giá trị hash đưa vào verify_proof.

Server cho ta biết nn là số lượng node lá (độ lớn của items cũng như leaves), items là dữ liệu thô được tạo ngẫu nhiên của leaves, cuối cùng là root. Yêu cầu của server: chọn index của item trong items làm target_item, sau đó nhập 2 chuỗi proof_A và proof_B khác nhau để đưa vào hàm verify với root. Nếu cả hai proof_A và proof_B sau khi xử lí đều giống root thì server sẽ trả flag.

Điểm đặc biệt của server là khi đưa proof ta cần phải chọn phía bên trái hay phải để thực hiện hash (góp phần tạo nên lỗi sẽ được đề cập sau).

Hàm verify nhận item mà ta chọn để làm giá trị khởi tạo cho hh, sau đó thực hiện node_hash các phần tử trong proof, sau cùng là so sánh với root . Hàm chính chứa lỗi là merkle_computation, đoạn đầu là khởi tạo các giá trị cho mảng inner

    count = 0
    inner = [None] * 32
    while count < len(leaves):
        h = leaves[count]
        count += 1
        level = 0
        while not (count & (1 << level)):
            h = dsha256(inner[level] + h)
            level += 1
        inner[level] = h

    level = 0
    while not (count & (1 << level)):
        level += 1
    h = inner[level]

Có thể thấy rằng inner được khởi tạo dựa trên việc hash leaves, mà leaves được tạo từ việc hash items đã biết. Vì thế ta có thể biết được các giá trị của inner. Và nhìn vào đoạn code ở trên có một điểm đặc biệt nữa là có 2 đoạn tính level lại, và việc khởi tạo h=h=inner[level] ở vòng lặp cuối.

    while count != (1 << level):
        h = dsha256(h + h)
        count += 1 << level
        level += 1
        while not (count & (1 << level)):
            h = dsha256(inner[level] + h)
            level += 1
    return h

Đoạn cuối của hàm là tính node_hash và trả kết quả nhưng có một đoạn nguy hiểm đó là việc gán h=dsha256(h+h)h = dsha256(h + h), liên kết đến hàm verify thì node_hash chia ra L và R, nhưng nếu đưa vào đoạn cuối đó thì không còn quan trọng L hay R nữa tức nếu có (h,L)(h,L) và (h,R)(h,R) thì khi đưa vào dsha256(h+h)dsha256(h+h) sẽ đều thành dsha256(h+h)dsha256(h+h) nhưng 2 proof đó không giống nhau.

Vậy hướng làm sẽ là chọn một index phù hợp, sau đó tìm một proof có thể verify được với root, sau đó đổi phía tại đúng chỗ tính h=dsha256(h+h)h=dsha256(h+h), khi đó 2 proof sẽ khác nhau đúng tại một chỗ nhưng cùng verify được root.

Vậy làm sao để chọn được index phù hợp? Nhìn lại phần khởi tạo giá trị cho inner, ta thấy giá trị hh được khởi tạo chính là inner được gán ở vòng lặp cuối, mà phía trên cùng của vòng lặp chính là leaves[count]\text{leaves[count]} tức leaves[len(leaves)-1]\text{leaves[len(leaves)-1]}. Đây đúng là index mà mình cần. Sau khi biết index cần, muốn tính proof cho ra chính xác root thì chỉ cần biết được các giá trị hh ở trong hàm merkle_computation đồng thời cũng biết được hướng là L hay R. Ta chỉnh sửa một chút hàm merkle_computation để lấy inner, sau đó tạo một hàm mới chỉ chạy vòng lặp cuối và đoạn hash sau cùng

def merkle_computation(leaves: list[bytes]) -> bytes:
    if len(leaves) == 0:
        return b"\x00" * 32
    count = 0
    inner = [None] * 32
    while count < len(leaves):
        if count == len(leaves) - 1:
            inner_p = inner
        h = leaves[count]
        count += 1
        level = 0
        while not (count & (1 << level)):
            h = dsha256(inner[level] + h)
            level += 1
        inner[level] = h

    level = 0
    while not (count & (1 << level)):
        level += 1
    h = inner[level]
    while count != (1 << level):
        h = dsha256(h + h)
        count += 1 << level
        level += 1
        while not (count & (1 << level)):
            h = dsha256(inner[level] + h)
            level += 1
    return h, inner_p

data = []
def merkle(leaf, index, inner) -> bytes:
    h = leaf
    count = index + 1
    level = 0
    while not (count & (1 << level)):
        h = dsha256(inner[level] + h)
        data.append((inner[level], 1))
        level += 1
    inner[level] = h

    level = 0
    while not (count & (1 << level)):
        level += 1
    h = inner[level]
    t = 0
    while count != (1 << level):
        if t == 0:
            data.append((h, 0))
            t = 1
        else:
            data.append((h, 0))
        h = dsha256(h + h)
        count += 1 << level
        level += 1
        while not (count & (1 << level)):
            h = dsha256(inner[level] + h)
            data.append((inner[level], 1))
            level += 1
    return h

Vậy là ta biết được cả index, proof. Việc cuối cùng cần làm là thay đổi hướng L thành R ở đúng vị trí dsha256(h+h)dsha256(h+h) và gửi cho server.

Script

from pwn import *
import json
import hashlib
r = remote("45.122.249.68",10392)
#r = process(["python3", "server.py"])
def dsha256(b: bytes) -> bytes:
    return hashlib.sha256(hashlib.sha256(b).digest()).digest()


def leaf_hash(item: bytes) -> bytes:
    return dsha256(item)


def node_hash(left: bytes, right: bytes) -> bytes:
    return dsha256(left + right)

def merkle_computation(leaves: list[bytes]) -> bytes:
    if len(leaves) == 0:
        return b"\x00" * 32
    count = 0
    inner = [None] * 32
    while count < len(leaves):
        if count == len(leaves) - 1:
            inner_p = inner
        h = leaves[count]
        count += 1
        level = 0
        while not (count & (1 << level)):
            h = dsha256(inner[level] + h)
            level += 1
        inner[level] = h

    level = 0
    while not (count & (1 << level)):
        level += 1
    h = inner[level]
    while count != (1 << level):
        h = dsha256(h + h)
        count += 1 << level
        level += 1
        while not (count & (1 << level)):
            h = dsha256(inner[level] + h)
            level += 1
    return h, inner_p

data = []
def merkle(leaf, index, inner) -> bytes:
    h = leaf
    count = index + 1
    level = 0
    while not (count & (1 << level)):
        h = dsha256(inner[level] + h)
        data.append((inner[level], 1))
        level += 1
    inner[level] = h

    level = 0
    while not (count & (1 << level)):
        level += 1
    h = inner[level]
    t = 0
    while count != (1 << level):
        if t == 0:
            data.append((h, 0))
            t = 1
        else:
            data.append((h, 0))
        h = dsha256(h + h)
        count += 1 << level
        level += 1
        while not (count & (1 << level)):
            h = dsha256(inner[level] + h)
            data.append((inner[level], 1))
            level += 1
    return h

r.recvuntil(b"[+] Number of leaf nodes: ")
n = int(r.recvline().strip())
r.recvuntil(b"[+] Public Items:\n")
item = json.loads(r.recvline().strip().decode())
items = [bytes.fromhex(x) for x in item]
leaves = [leaf_hash(x) for x in items]
_, inner = merkle_computation(leaves)
merkle(leaves[-1], len(leaves) - 1, inner)

r.recvuntil(b"): ")
r.sendline(str(n - 1).encode())
proof_a = "".join(x[0].hex() + ":" + ( "L" if x[1] == 1 else "R" ) + "," for x in data)[:-1]
proof_b = "".join(x[0].hex() + ":" + "L" + "," for x in data)[:-1]
r.recvuntil(b"Proof A: ")
r.sendline(proof_a.encode())
r.recvuntil(b"Proof B: ")
r.sendline(proof_b.encode())

print(r.recvall())

Bài này nhờ hint của anh Tú mà mình biết phải để ý đến dsha256(h+h)dsha256(h+h) trước nên làm khá nhanh, nhưng phần code phân tích cũng phức tạp :)))))

Flag: W1{CVE-2012-2459_m3rkl3_b1tc01n_dupl1c4t3_n0d3_c0ll1s10n_xqZtvJSwKP3mn6B8rf2DC9g4h7s4lyUE60189fb4}

Ngoài ra còn một bài unofficial của anh Đức trong giải này nữa

sPERM

Đề

import random
import hashlib
import sys


with open('flag.txt','r') as f:
    flag = f.read().strip()



def count_cycles(arr):
    n = len(arr)
    visited = [False] * (n + 1)
    cycles = 0
    for i in range(1, n + 1):
        if not visited[i]:
            curr = i
            while not visited[curr]:
                visited[curr] = True
                curr = arr[curr - 1]
            cycles += 1
    return cycles

MENU = """Choose an option:
1. Guess
2. Get hint
3. Exit
> """

def main():
    n = 64
    limit = 363 # 36?
    
    secret = list(range(1, n + 1))
    random.shuffle(secret)
    print("Can you guess my number? ")
    queries = 0
    
    while queries < limit:
        choice = input(MENU)
        if choice == "1":
            guess = list(map(int, input("Enter your guess: ").strip().split()))
            if guess == secret:
                print(f"Correct! The flag is: {flag}")
                break
            else:
                print("Wrong guess!")
        elif choice == "2":
            queries += 1
            pi = list(map(int, input("Enter your permutation: ").strip().split()))
            composed = [secret[pi[i]] for i in range(n)]
            print(count_cycles(composed))
            sys.stdout.flush()
        elif choice == "3":
            exit(0)

if __name__ == "__main__":
    main()

Phân tích và ý tưởng

Đây là một bài liên quan đến hoán vị, server sẽ tạo một' mảng secret là một hoán vị của {1,2,..,64}, nhiệm vụ là phải tìm lại chính xác hoán vị đó, gửi lại cho server xác thực. Ngoài ra còn một lựa chọn là tự tạo cho mình một hoán vị dựa trên secret, server sẽ trả về số lượng chu trình trong chuỗi hoán vị đó. Về hoán vị mình có tìm và đọc từ bài blog của anh Đức: https://hackmd.io/@dvck13/Hk8UA6bNGx

Ta có composed là một hoán vị ta có thể điều khiển

composed=σ=(12…64secret[pi[0]]secret[pi[1]]…secret[pi[n−1]])\text{composed}=\begin{equation} \sigma =\begin{pmatrix} 1 & 2 & \dotsc & 64\\ \text{secret}\left[pi\left[0\right]\right] & \text{secret}\left[pi\left[1\right]\right] & \dotsc & \text{secret}\left[pi\left[n-1\right]\right] \end{pmatrix} \end{equation}

Thông qua việc nhập các giá trị pi, sau đó chúng sẽ làm index cho secret, tạo thành một hoán vị mới. Nhưng trong phần nhập pi lại không có điều kiện phải nhập các số khác nhau đôi một, nên ta có thể nhập pi là một chuỗi chứa 1 giá trị lặp lại liên tục. Khi đó hoán vị đó trở thành dãy chỉ chứa một số duy nhất, rồi sẽ tính số lượng chu trình như bình thường.

secret = [7,6,1,3,2,4,5]
print("secret: ", secret)
for i in range(n):
    print(f"====={i}=====")
    pi = [i for _ in range(n)]
    composed = [secret[pi[i]] for i in range(n)]
    print("pi: ", pi)
    print("composed: ", composed)
    print("cycle: ", count_cycles(composed))

image

Một đoạn script test nhỏ phía trên về trường hợp này cho ta thấy có thể tìm được vị trí của số 1 trong secret do chính hàm count_cycles leak ra.

Xét 2 ví dụ sau để rõ hơn

σ=(12345671111111)\begin{equation} \sigma =\begin{pmatrix} 1 & 2 & 3 & 4 & 5 & 6 & 7 \\ 1 & 1 & 1 & 1 & 1 & 1 & 1 \end{pmatrix} \end{equation}

Bắt đầu từ σ(1)=1\sigma (1)=1 nhưng tại index 1 đã được thăm nên tạo thành một cycle , tiếp theo σ(2)=1\sigma (2)=1 nhưng tại 1 đã được thăm nên σ(2)\sigma (2) cũng tạo thành một cycle khác, cứ tiếp tục như vậy đến hết. Vậy sau đó cuối cùng số lượng cycle là 7, σ=(1)(2)(3)(4)(5)(6)(7)\sigma =(1)(2)(3)(4)(5)(6)(7) image

tiếp theo là ví dụ với số khác 1

σ=(12345672222222)\begin{equation} \sigma =\begin{pmatrix} 1 & 2 & 3 & 4 & 5 & 6 & 7 \\ 2 & 2 & 2 & 2 & 2 & 2 & 2 \end{pmatrix} \end{equation}

Bắt đầu từ σ(1)=2\sigma (1)=2 vì tại index 2 chưa được thăm nên tiếp tục σ(2)=2\sigma (2)=2, lúc này tại index 2 đã được thăm nên tạo thành một cycle (1,2)(1,2), các phần tử về sau sẽ tự tạo thành 1 cycle riêng không giống nhau. image

Mà ta biết pi được dùng làm index cho secret, nên nếu như số lượng cycle bằng với số lượng phần tử thì tại vị trí có giá trị index pi[i] của secret sẽ là 1.

Từ đó có nền để thực hiện oracle tìm lại các số khác. pi cũng có điểm đặc biệt liên kết với cả secret và composed đó là index của pi cũng là index của composed còn pi lại là index của secret. Khi thử một giá trị pi cố định nhưng thay đổi index, mình thấy được rằng số lượng cycle sẽ giảm hoặc giữ nguyên.

print("secret: ", secret)
for j in range(n):
    pi = [2 for _ in range(n)]
    pi[j] = 5
    composed = [secret[pi[i]] for i in range(n)]
    print(composed)
    print(f"index {j}: ", get_disjoint_cycles(composed))
    print("count cycles: ", count_cycles(composed))
    print("======")

image image

Thấy rằng ở ảnh 1 thì giá trị số 5 = pi[j] tương ứng với index của secret, còn index thứ 2 không đỏi count_cycles lại là giá trị tại index đó, ở đây index 5 của secret = 4. Hình số 2 cũng tương tự như vậy.

Vậy ta có thể rút ra cách tìm lại được các số là

  • Cho pi là mảng chứa index của số 1 của secret.
  • Gán lần lượt pi[j]=x, để tìm giá trị tại index x của secret.
  • Thu thập kết quả count cycles và lấy index thứ 2 khi count cycles không đổi.

Nhưng bị giới hạn bởi limit nên ta không thể dùng linear search như vậy được, tìm kiếm như vậy sẽ quá limit. Vì thế phải thay thế bằng phương pháp tìm kiếm khác là binary search. Khi đó với một số thay vì phải gửi request 64 lần, ta sẽ rút ngắn lại còn vài lần. Nhưng dùng binary search vẫn bị lố limit một ít, vậy nên phải brute tìm lại hoán vị của một nhóm nhỏ vài phần tử sau cùng.

Script

from itertools import permutations
from pwn import *

r = process(["python3", "chal.py"])
n = 64
one_idx = 0
for i in range(n):
    pi = [i for _ in range(n)]
    send = "".join(str(x) + " " for x in pi)
    r.recvuntil(b"> ")
    r.sendline(b"2")
    r.recvuntil(b"Enter your permutation: ")
    r.sendline(send.encode())
    cnt_cir = int(r.recvline().strip().decode())
    if cnt_cir == n:
        one_idx = i
        break
recover = [0] * n
recover[one_idx] = 1


def binary_search_oracle(idx, cnt, io):
    l = 1
    r = n
    while l <= r:
        pi = [one_idx for _ in range(n)]
        mid = l + (r - l) // 2
        if l == r:
            return mid + 1
        try:
            pi[mid] = idx
        except IndexError:
            return mid
        send = "".join(str(x) + " " for x in pi)
        io.recvuntil(b"> ")
        io.sendline(b"2")
        io.recvuntil(b"Enter your permutation: ")
        io.sendline(send.encode())
        cnt_cir = int(io.recvline().strip().decode())
        if cnt_cir == cnt:
            r = mid
        else:
            l = mid + 1
    return mid + 1


for i in range(n-8):
    if i == one_idx:
        continue
    val= binary_search_oracle(i, n, r)
    recover[i] = val
    
miss = []
data = "".join( str(recover[i]) + " " for i in range(n-8))
for i in range(1, n+1):
    if i not in recover:
        miss.append(i)

for combos in permutations(miss):
    print(combos)
    per = "".join(str(combos[i]) + " " for i in range(len(combos)))
    r.recvuntil(b"> ")
    r.sendline(b"1")
    r.recvuntil(b"Enter your guess: ")
    r.sendline((data + per).encode())
    recv = r.recvline()
    if b"Correct" in recv:
        print(recv)
        break