ʕ·ᴥ·ʔ






Hacking

06/10/2022

By: HELLOPERSON

Tags: misc HSCTF-2022

Problem Description:

Help Eljmike organize his hacking contest!


This seems like a typical algorithm problem, where you come up with an efficient algorithm to solve a problem. Let’s think about the problem statement. Thinking for a bit, we realize that anything that points to something else in a loop would fail and increment our counter, while anything before the said loop is safe and doesn’t increment the counter.

How do we find these loops though? We can iterate through every element in the array we’re given, and follow where it points to. If it points to something already in our path, we can identify a loop, and anything before that isn’t a loop. Additionally, when iterating through, every time you hit something you’ve already counted towards something, you can stop and add everything before that to the safe category.

Let’s write some code for this:

from pwn import *
import gmpy2

io = remote("hacking.hsctf.com", 1337)
io.readuntil(b"with:\n")
pow = io.readline().strip().decode()

solve = process(["python3", "solver.py", *list(pow[46:].split(' '))])
solve.readuntil(b"Solution: \n")
a = solve.read().strip().decode()
io.send(a + '\n')
print(a)
print("pow done")
sols = [0, 0, 0, 0, 0]

print(io.recvline())
print(io.recvline())
print(io.recvline())
print(io.recvline())

for k in range(5):
    print("trial: "+str(k+1))
    asdf = io.recvline().strip().decode()
    a = list(map(int, asdf.split(",")))
    length = len(a)
    deadalive = []
    for i in range(length):
        deadalive.append(-1)
    dead = []
    alive = []
    for i in range(len(a)):
        x = i
        visited = [i+1]
        if a[x] == i+1:
            deadalive[i] = 1
        elif deadalive[i] != 0 and deadalive[i] != 1:
            while a[x] not in visited and deadalive[a[x] - 1] == -1:
                visited.append(a[x])
                x = a[x] - 1
            if deadalive[a[x] - 1] != -1:
              y = len(visited)
            else:
              y = visited.index(a[x])
            for l in visited[y:len(visited)]:
                deadalive[l - 1] = 1
            for l in visited[0:y]:
                deadalive[l - 1] = 0
    for i in range(length):
        sols[k] += deadalive[i]
st = ""
for i in range(4):
    st += str(sols[i])
    st += ", "
asdff = st + str(sols[4])
io.send(asdff)
print(io.recv())

However, for some reason, our code doesn’t work. Can you spot the error?

Of course! The output should have a newline after it (wtf why does this matter???). Fixing this error, we see that the flag is flag{cOnGrAtS_yOu_ArE_nOw_A_hAcKeR}