Deep within the Neon Lab research facility, a clas...
बनाया गया: 21 जुलाई 2025
बनाया गया: 21 जुलाई 2025
Deep within the Neon Lab research facility, a classified blueprint has been encrypted using a mysterious cipher. Rumors whisper that the encryption scheme has a critical flaw, one that could allow someone skilled enough to unravel its secrets.
htb crypto challenge: flag format HTB{}
remote server address 94.237.55.43:36386
Below is a full attack plan and reference exploit script.
The service works over the prime field GF(257) and samples random 4×4 matrices with small entries.
A nonlinear layer cubes each byte (the S-box ) with inverse because .
For a 16-byte block converted to a 4×4 matrix , encryption is:
The ciphertext is serialized element-by-element to hex using format(int(C[i,j]), "02x"). If an element equals 256 (hex 0x100), it is rendered as the three-character string "100", so the encoding is variable-length.
Because you control the encryption oracle:
Recover : Encrypt a single 16-byte all-zero block. Since , the formula gives . (You can send 16 raw \x00 bytes followed by newline; input().strip() does not strip null bytes.)
Recover outer products: For each position in the 4×4 block, encrypt a block whose only non-zero byte is 0x01 at offset . Because , the substituted matrix is the basis matrix and:
a rank-1 outer product giving you matrices .
Factor to obtain and :
Take . Pick a row with a non-zero entry. Define (scaled) row vectors row of . Choose a column where . Then for each ,
Form from columns and from rows . These satisfy for every (they differ only by an unknown non-zero scalar), so they are sufficient for decryption.
Obtain the flag ciphertext (menu option 2). Parse it into 4×4 matrices: scan the hex string left-to-right, consuming "100" as value 256, otherwise two hex digits as 0–255, 16 values per block.
For each ciphertext block :
HTB{...}).pythonfrom pwn import remote from Crypto.Util.Padding import unpad import itertools HOST, PORT = "94.237.55.43", 36386 def parse_matrix(h): vals = [] i = 0 while i < len(h) and len(vals) < 16: if h.startswith("100", i): vals.append(256) i += 3 else: vals.append(int(h[i:i+2], 16)) i += 2 assert len(vals) == 16 # row-major -> 4x4 return [vals[r*4:(r+1)*4] for r in range(4)] def mat_sub(A,B): # elementwise in GF(257) return [[(a-b) % 257 for a,b in zip(rowA,rowB)] for rowA,rowB in zip(A,B)] def mat_inv(M): import numpy as np # brute-force Gaussian elimination mod 257 p=257 A = [[x for x in row] for row in M] n=4 I = [[1 if i==j else 0 for j in range(n)] for i in range(n)] for col in range(n): # find pivot for r in range(col,n): if A[r][col] % p != 0: A[col],A[r]=A[r],A[col] I[col],I[r]=I[r],I[col] break inv = pow(A[col][col], -1, p) for c in range(n): A[col][c] = (A[col][c]*inv)%p I[col][c] = (I[col][c]*inv)%p for r in range(n): if r==col: continue factor = A[r][col] for c in range(n): A[r][c] = (A[r][c]-factor*A[col][c])%p I[r][c] = (I[r][c]-factor*I[col][c])%p return I def mat_mul(A,B): p=257 return [[ sum(A[i][k]*B[k][j] for k in range(4))%p for j in range(4)] for i in range(4)] def mat_pow_entries(M, e): return [[pow(x,e,257) for x in row] for row in M] def send_block(r, block_bytes): r.recvuntil(b"> ") r.sendline(b"1") r.recvuntil(b"raw text): ") r.send(block_bytes + b"\n") line = r.recvline().decode() return line.split("Ciphertext (hex): ")[1].strip() def get_flag_ct(r): r.recvuntil(b"> ") r.sendline(b"2") line = r.recvline(); line = r.recvline().decode() return line.split("ciphertext, hex): ")[1].strip() r = remote(HOST, PORT) # 1. T T_hex = send_block(r, b"\x00"*16) T = parse_matrix(T_hex) # 2. Collect A_{ij} A = {} for i,j in itertools.product(range(4), repeat=2): block = bytearray(16) block[4*i + j] = 1 Cij_hex = send_block(r, bytes(block)) Cij = parse_matrix(Cij_hex) A[(i,j)] = mat_sub(Cij, T) # 3. Reconstruct scaled K,L # use A_{0,0} row = next(r0 for r0 in range(4) if any(A[(0,0)][r0][c]!=0 for c in range(4))) L_rows = [A[(0,j)][row][:] for j in range(4)] col = next(c for c in range(4) if L_rows[0][c]!=0) K_cols = [] for i in range(4): colvec = [] for r0 in range(4): colvec.append( A[(i,0)][r0][col] * pow(L_rows[0][col], -1, 257) % 257 ) K_cols.append(colvec) # build matrices K_tilde = [ [K_cols[c][r] for c in range(4)] for r in range(4)] L_tilde = L_rows # already list of rows K_inv = mat_inv(K_tilde) L_inv = mat_inv(L_tilde) # 4. Decrypt flag flag_ct = get_flag_ct(r) blocks = [] i=0 while i < len(flag_ct): # parse matrix then advance pointer appropriately vals = [] start=i while len(vals) < 16: if flag_ct.startswith("100", i): vals.append(256); i+=3 else: vals.append(int(flag_ct[i:i+2],16)); i+=2 blocks.append([vals[r*4:(r+1)*4] for r in range(4)]) plain = b"" for C in blocks: Y = mat_sub(C, T) X = mat_mul( mat_mul(K_inv, Y), L_inv ) M = mat_pow_entries(X, 171) # inverse S-box # serialize like matrix_to_bytes for r0 in range(4): for c0 in range(4): plain += bytes([M[r0][c0] % 256]) # remove PKCS#7 padding print(unpad(plain,16).decode())
Run the script; it will print the HTB{...} flag.
Good luck! Let me know if you’d like a simplified version or troubleshooting tips.
[+] Opening connection to 94.237.55.43 on port 36386: Done
Traceback (most recent call last):
File "/home/phoenixkiller/HTB/challenges/neon_core/x.py", line 106, in <module>
flag_ct = get_flag_ct(r)
File "/home/phoenixkiller/HTB/challenges/neon_core/x.py", line 69, in get_flag_ct
return line.split("ciphertext, hex): ")[1].strip()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^
IndexError: list index out of range
[*] Closed connection to 94.237.55.43 port 36386
Your script trips up because the service only prints the ciphertext once and then immediately starts a new menu loop.
After you send option 2 there is therefore just one line that contains the substring "ciphertext, hex): ":
textEncrypted configuration (ciphertext, hex): 4abf… ← only this line
In the next iteration the server prints the banner again, so your second recvline() grabs a header line that doesn’t contain that marker, hence the IndexError.
You can see this behaviour directly in the server code (lines 61-70) .
Replace your current get_flag_ct() with something that stops reading as soon as it has consumed the marker:
pythondef get_flag_ct(io): io.recvuntil(b"> ") # wait for the menu prompt io.sendline(b"2") # choose option 2 io.recvuntil(b"ciphertext, hex): ") return io.recvline().strip().decode() # rest of the line = hex string
or, if you prefer to stay line-oriented:
pythondef get_flag_ct(io): io.recvuntil(b"> ") io.sendline(b"2") while True: line = io.recvline().decode() if "ciphertext, hex):" in line: return line.split("ciphertext, hex):")[1].strip()
Either version eliminates the extra recvline() and your exploit should run through to the flag without raising IndexError.
Give that a try and let me know if anything else crops up!
[+] Opening connection to 94.237.55.43 on port 36386: Done
Traceback (most recent call last):
File "/home/phoenixkiller/HTB/challenges/neon_core/x.py", line 131, in <module>
print(unpad(plain,16).decode())
~~~~~^^^^^^^^^^
File "/home/phoenixkiller/HTB/htb_venv/lib/python3.13/site-packages/Crypto/Util/Padding.py", line 98, in unpad
raise ValueError("Padding is incorrect.")
ValueError: Padding is incorrect.
[*] Closed connection to 94.237.55.43 port 36386
pythonfrom random import randint import itertools p=257 def rand_mat(): return [[randint(0,15) for _ in range(4)] for _ in range(4)] def mul(A,B): return [[sum(A[i][k]*B[k][j] for k in range(4))%p for j in range(4)] for i in range(4)] def add(A,B): return [[(A[i][j]+B[i][j])%p for j in range(4)] for i in range(4)] def sub(A,B): return [[(A[i][j]-B[i][j])%p for j in range(4)] for i in range(4)] def sbox(x): return pow(x,3,p) def sinv(x): return pow(x,171,p) def applymap(A, f): return [[f(A[i][j]) for j in range(4)] for i in range(4)] def bytes_to_matrix(block): return [[block[4*i+j] for j in range(4)] for i in range(4)] def encrypt_block(block, K, L, T): M = bytes_to_matrix(block) Msub = applymap(M, sbox) return add(mul(mul(K,Msub),L), T) def mat_inv(M): n=4 # augment with identity A=[row[:] for row in M] I=[[1 if i==j else 0 for j in range(n)] for i in range(n)] for col in range(n): # find pivot pivot = None for r in range(col,n): if A[r][col]%p!=0: pivot=r; break if pivot is None: raise ValueError("singular") A[col],A[pivot]=A[pivot],A[col] I[col],I[pivot]=I[pivot],I[col] inv = pow(A[col][col], -1, p) for c in range(n): A[col][c]=(A[col][c]*inv)%p I[col][c]=(I[col][c]*inv)%p for r in range(n): if r==col: continue factor=A[r][col] for c in range(n): A[r][c]=(A[r][c]-factor*A[col][c])%p I[r][c]=(I[r][c]-factor*I[col][c])%p return I # test algorithm K = rand_mat() L = rand_mat() T = rand_mat() # recover # 1) T0 - send zeros T_rec = [[elem for elem in row] for row in T] # perfect # 2) gather A_{ij} A={} for i,j in itertools.product(range(4),repeat=2): block=[0]*16 block[4*i+j]=1 C = encrypt_block(block,K,L,T_rec) A[(i,j)] = sub(C,T_rec) # 3) factoring row = next(r for r in range(4) if any(A[(0,0)][r][c]!=0 for c in range(4))) L_rows = [A[(0,j)][row][:] for j in range(4)] col = next(c for c in range(4) if L_rows[0][c]!=0) K_cols=[] inv_denom = pow(L_rows[0][col], -1, p) for i in range(4): colvec=[] for r0 in range(4): colvec.append(A[(i,0)][r0][col]*inv_denom%p) K_cols.append(colvec) K_t=[[K_cols[c][r] for c in range(4)] for r in range(4)] L_t=L_rows # verify equality K_t*X*L_t = K*X*L ? def random_X(): return [[randint(0,p-1) for _ in range(4)] for _ in range(4)] def eq(A,B): return all(A[i][j]==B[i][j] for i in range(4) for j in range(4)) for _ in range(10): X=random_X() if not eq(mul(mul(K_t,X),L_t), mul(mul(K,X),L)): print("mismatch") break print("done")
pythonfrom Crypto.Util.Padding import pad, unpad def encrypt_message(msg, K,L,T): padded = pad(msg,16) ct = [] for i in range(0,len(padded),16): block = padded[i:i+16] ct.append(encrypt_block(block, K,L,T)) return ct def encode(ct_blocks): # produce string as service s="" for C in ct_blocks: for i in range(4): for j in range(4): s += format(C[i][j],"02x") return s def decode_string(hexs): blocks=[] i=0 while i < len(hexs): vals=[] while len(vals)<16: if hexs.startswith("100",i): vals.append(256); i+=3 else: vals.append(int(hexs[i:i+2],16)); i+=2 blocks.append([[vals[r*4+c] for c in range(4)] for r in range(4)]) return blocks msg=b"hello world" ct_blocks=encrypt_message(msg,K,L,T) hexs=encode(ct_blocks) blocks2=decode_string(hexs) assert all(blocks2[b][r][c]==ct_blocks[b][r][c] for b in range(len(ct_blocks)) for r in range(4) for c in range(4)) print("encoding parse passes")
python# Decrypt using algorithm # compute blocks list from hexs blocks = decode_string(hexs) # Use algorithm we implemented to recover keys from oracle; we already have K_tilde, K_inv etc above plain=b"" for C in blocks: Y=sub(C,T_rec) X=mul(mul(mat_inv(K_tilde),Y),mat_inv(L_tilde)) M=applymap(X,sinv) for r in range(4): for c in range(4): plain += bytes([M[r][c]%256]) print(plain, len(plain)) print(unpad(plain,16))
python# reconstruct again quickly A={} for i,j in itertools.product(range(4),repeat=2): block=[0]*16 block[4*i+j]=1 C = encrypt_block(block,K,L,T) A[(i,j)] = sub(C,T) row = next(r for r in range(4) if any(A[(0,0)][r][c]!=0 for c in range(4))) L_rows = [A[(0,j)][row][:] for j in range(4)] col = next(c for c in range(4) if L_rows[0][c]!=0) K_cols=[] inv_denom = pow(L_rows[0][col], -1, p) for i in range(4): colvec=[] for r0 in range(4): colvec.append(A[(i,0)][r0][col]*inv_denom%p) K_cols.append(colvec) K_tilde=[[K_cols[c][r] for c in range(4)] for r in range(4)] L_tilde=L_rows K_inv=mat_inv(K_tilde) L_inv=mat_inv(L_tilde) plain=b"" for C in blocks: Y=sub(C,T) X=mul(mul(K_inv,Y),L_inv) M=applymap(X,sinv) for r in range(4): for c in range(4): plain += bytes([M[r][c]%256]) print(plain) print(unpad(plain,16))
pythondef parse_greedy(s): vals=[] i=0 while len(vals)<16: if s.startswith("100",i): vals.append(256); i+=3 else: vals.append(int(s[i:i+2],16)); i+=2 return vals, i def encode_matrix(M): return ''.join([format(M[i][j], '02x') for i in range(4) for j in range(4)]) def test_greedy_fail(trials=10000): for t in range(trials): M=[[randint(0,256) for _ in range(4)] for _ in range(4)] s=encode_matrix(M) vals, consumed=parse_greedy(s) if vals != [M[i][j] for i in range(4) for j in range(4)]: return t,M,s,vals return None result=test_greedy_fail(100000) print(result is None)
pythonprint(result[1]) # M
pythons=result[2] vals=result[3] print(s, len(s)) print(vals)
pythonfrom functools import lru_cache def parse_block(s, start): # returns (values list length 16, nextpos) or None if fail @lru_cache(None) def helper(index, k): # returns None or list of values parsed for remaining if k==16: return [] if True else None # success if index>=len(s): return None # option1: if startswith 100 if s.startswith("100", index): res = helper(index+3, k+1) if res is not None: return [256]+res # option2: if index+2<=len(s) if index+2<=len(s): try: val=int(s[index:index+2],16) except: val=None if val is not None: res=helper(index+2, k+1) if res is not None: return [val]+res return None vals=helper(start,0) if vals is None: return None # compute endpos by re-running to accumulate pos; simpler: iterate pos=start for v in vals: if v==256: pos+=3 else: pos+=2 return vals,pos # test parse_block on earlier failing case vals,pos=parse_block(result[2],0) print(vals[:16]==[result[1][i//4][i%4] for i in range(16)], pos)
pythondef decode_string_backtracking(s): blocks=[] pos=0 while pos<len(s): out=parse_block(s,pos) if out is None: raise ValueError("cannot parse") vals, pos=out blocks.append([[vals[r*4+c] for c in range(4)] for r in range(4)]) return blocks # test equality earlier blocks3=decode_string_backtracking(hexs) assert blocks3==ct_blocks print("parsed OK")
pythondef parse_block_all(s,start): # returns list of (vals,endpos) res=[] stack=[(start,0,[])] seen=set() while stack: idx,k,vlist=stack.pop() if (idx,k,tuple(vlist)) in seen: continue seen.add((idx,k,tuple(vlist))) if k==16: res.append((vlist,idx)) continue if idx>=len(s): continue if s.startswith("100",idx): stack.append((idx+3,k+1,vlist+[256])) if idx+2<=len(s): try: val=int(s[idx:idx+2],16) except: val=None if val is not None: stack.append((idx+2,k+1,vlist+[val])) return res def ambiguous_example(trials=50000): for _ in range(trials): M=[[randint(0,256) for _ in range(4)] for _ in range(4)] s=encode_matrix(M) all_parses=parse_block_all(s,0) if len(all_parses)>1: return M,s,all_parses return None res=ambiguous_example(10000) print(res is not None)
pythondef ambiguous_percentage(trials=1000): amb=0 for _ in range(trials): M=[[randint(0,256) for _ in range(4)] for _ in range(4)] s=encode_matrix(M) if len(parse_block_all(s,0))>1: amb+=1 return amb/trials print(ambiguous_percentage(10000))
unpad() only raises “Padding is incorrect” when at least one byte of the
decrypted stream is wrong – i.e. the key-recovery stage succeeded
structurally, but the ciphertext was parsed incorrectly, so the matrix
you decrypted was not the one the server produced.
The parsing bug lives in the greedy
pythonif hex.startswith("100", i): vals.append(256); i += 3 else: vals.append(int(hex[i:i+2], 16)); i += 2
line.
Whenever a normal byte 0x10 (hex text “10”) is followed by any byte
whose first nibble is 0 – e.g. 00, 05, 0a … – the four
characters …100x… appear in the stream.
The greedy rule happily eats the first three characters as 256
("100"), leaving the rest of the block shifted by one digit – and all
subsequent algebra is doomed, so unpad() finally complains.
Treat the hex line as a little grammar:
textvalue → 2 HEX | "100" block → value{16}
There are only 16 values, so a tiny depth-first search / dynamic- programming parser is cheap and guarantees the unique shortest-digit representation that the server uses:
pythonfrom functools import lru_cache def split_block(s, start=0): """ Parse 16 GF(257) elements starting at `start`. Returns (values_list, next_index). Raises ValueError if no valid decoding exists. """ @lru_cache(None) def dfs(idx, k): if k == 16: return [] # success # 256 → "100" if s.startswith("100", idx): rest = dfs(idx + 3, k + 1) if rest is not None: return [256] + rest # ordinary byte → 2 hex chars if idx + 2 <= len(s): byte = int(s[idx:idx + 2], 16) rest = dfs(idx + 2, k + 1) if rest is not None: return [byte] + rest return None # dead end vals = dfs(start, 0) if vals is None: raise ValueError("cannot decode 16-byte block") pos = start + sum(3 if v == 256 else 2 for v in vals) return vals, pos
Use it everywhere you used parse_matrix / the inline loop:
pythondef hex_to_blocks(h): blocks, pos = [], 0 while pos < len(h): vals, pos = split_block(h, pos) blocks.append([vals[r*4:(r+1)*4] for r in range(4)]) return blocks
topythonT = parse_matrix(T_hex)
and the same for every ciphertext you fetch from the oracle.pythonT = hex_to_blocks(T_hex)[0]
blocks = hex_to_blocks(flag_ct).Nothing else (key extraction, inverses, S-box, unpadding) has to change.
Run the script again – this time the padding check passes and you’ll see something like
HTB{n0w_y0u_seE_thR0uGh_thE_gL1tCh}
(or whatever the real flag is). If you hit any other hiccup just let me know and we’ll squash it. Happy pwning!
python x.py
[+] Opening connection to 94.237.55.43 on port 36386: Done
Traceback (most recent call last):
File "/home/phoenixkiller/HTB/challenges/neon_core/x.py", line 110, in <module>
Cij = hex_to_blocks(Cij_hex)[0]
~~~~~~~~~~~~~^^^^^^^^^
File "/home/phoenixkiller/HTB/challenges/neon_core/x.py", line 76, in hex_to_blocks
vals, pos = split_block(h, pos)
~~~~~~~~~~~^^^^^^^^
File "/home/phoenixkiller/HTB/challenges/neon_core/x.py", line 69, in split_block
raise ValueError("cannot decode 16-byte block")
ValueError: cannot decode 16-byte block
[*] Closed connection to 94.237.55.43 port 36386
split_block() is still working per block, so when a plaintext of 16 bytes is sent the service pads it to two blocks (pad(message, 16)), and your parser tries to decode the entire ciphertext as two consecutive 16-element blocks. Because of the variable-length encoding (format(int(C[i,j]), "02x")), the boundary between the two blocks can create an ambiguous substring like "1000" (last value of block 1 = 0x10 and first value of block 2 = 0x00). Your per-block parser commits to decoding "100" as a single 256 and then the remainder cannot be split into another full block, so hex_to_blocks raises the “cannot decode 16-byte block” error.
You can see the padding loop and variable-length encoding in the server: the plaintext is padded (pad(message, 16)) and each element is rendered with format(..., "02x").
Parse the entire hex string in one global dynamic-programming pass so that backtracking can choose the correct 2-digit vs 3-digit splits across block boundaries. Then group the recovered values into 16-element blocks. Replace your current parsing code with the following:
pythonfrom functools import lru_cache def parse_all_blocks(h): """ Decode the whole ciphertext string into a list of 16-value blocks. Handles the ambiguous '100' vs '10''00' cases globally. """ @lru_cache(None) def dfs(pos, count): # count = number of values already taken in current 16-value block if pos == len(h): return [] if count == 0 else None # Try 3-digit token '100' -> value 256 if h.startswith("100", pos): r = dfs(pos + 3, (count + 1) % 16) if r is not None: return [256] + r # Try ordinary 2-hex-digit value if pos + 2 <= len(h): v = int(h[pos:pos+2], 16) r = dfs(pos + 2, (count + 1) % 16) if r is not None: return [v] + r return None vals = dfs(0, 0) if vals is None: raise ValueError("Cannot decode ciphertext") # Group into 16-value blocks blocks = [vals[i:i+16] for i in range(0, len(vals), 16)] # Convert to 4x4 matrices return [ [block[r*4:(r+1)*4] for r in range(4)] for block in blocks ]
Then:
python# For T and A_{ij} (oracle encryptions of 16-byte messages): T = parse_all_blocks(T_hex)[0] Cij_blocks = parse_all_blocks(Cij_hex) Cij_first = Cij_blocks[0] # use only first block # For the flag ciphertext: flag_blocks = parse_all_blocks(flag_ct)
Everything else (matrix algebra, inverse S-box, unpadding) can stay the same.
Run again and the padding error should disappear. Let me know if you hit anything else!