PatriotCTF 2024 - Emoji Stack
π‘ λ¬Έμ λ λ€μκ³Ό κ°λ€
νμ΄
def emoji_stack_interpreter(program):
# Initialize the stack (256 cells) and the pointer
stack = [0] * 256
pointer = 0
output = []
# Create a pointer for reading the program
i = 0
# Helper function to get the current value at the pointer
def get_value():
return stack[pointer]
# Helper function to update the stack with modular arithmetic
def set_value(value):
stack[pointer] = value % 256
while i < len(program):
cmd = program[i]
if cmd == ':point_right:':
pointer = (pointer + 1) % 256 # Move right, wrap around if needed
elif cmd == ':point_left:':
pointer = (pointer - 1) % 256 # Move left, wrap around if needed
elif cmd == ':thumbsup:':
set_value(get_value() + 1) # Increment the current cell
elif cmd == ':thumbsdown:':
set_value(get_value() - 1) # Decrement the current cell
elif cmd == ':speech_balloon:':
output.append(chr(get_value())) # Print the ASCII value of the current cell
elif cmd == ':repeat:':
# Repeat the previous instruction (next two characters represent the hex value)
repeat_count = int(program[i+1:i+3], 16)
previous_cmd = program[i-1]
for _ in range(repeat_count):
if previous_cmd == ':thumbsup:':
set_value(get_value() + 1)
elif previous_cmd == ':thumbsdown:':
set_value(get_value() - 1)
elif previous_cmd == ':point_right:':
pointer = (pointer + 1) % 256
elif previous_cmd == ':point_left:':
pointer = (pointer - 1) % 256
i += 2 # Skip the next two hex characters
i += 1
return ''.join(output)
# Read the content of the input file
file_path = 'input.txt'
with open(file_path, 'r') as file:
program = file.read()
# Run the interpreter
flag = emoji_stack_interpreter(program)
print(flag)
1. . emoji_stack_interpreter ν¨μ μ μ
• μ€ν μ΄κΈ°ν:
• stack = [0] * 256: 256κ°μ μ λ‘ κ΅¬μ±λ μ€νμ 0μΌλ‘ μ΄κΈ°νν©λλ€.
• pointer = 0: μ€ν ν¬μΈν°λ μ²μμ 첫 λ²μ§Έ μ μ κ°λ¦¬ν΅λλ€.
• output = []: κ²°κ³Ό λ¬Έμμ΄μ λ΄μ 리μ€νΈμ λλ€.
• get_value ν¨μ: νμ¬ ν¬μΈν°κ° κ°λ¦¬ν€λ μ μ κ°μ λ°ννλ ν¨μμ λλ€.
• set_value ν¨μ: νμ¬ μ μ κ°μ λ£μ λ 256μΌλ‘ λλ λλ¨Έμ§λ₯Ό μ μ₯ν©λλ€. μ΄λ μ κ°μ΄ 0~255 μ¬μ΄μ μλλ‘ λ³΄μ₯ν©λλ€.
2. while 루ν:
νλ‘κ·Έλ¨μ κ° λͺ λ Ήμ ν κΈμμ© μ½μΌλ©΄μ μ²λ¦¬ν©λλ€.
• ν¬μΈν° μ΄λ (π, π):
• π: μ€ν ν¬μΈν°λ₯Ό μ€λ₯Έμͺ½μΌλ‘ μ΄λν©λλ€. pointer = (pointer + 1) % 256λ‘, 256μ λμ΄κ°λ©΄ λ€μ μ²μμΌλ‘ λμμ΅λλ€.
• π: μ€ν ν¬μΈν°λ₯Ό μΌμͺ½μΌλ‘ μ΄λν©λλ€. pointer = (pointer - 1) % 256λ‘, 0μμ μΌμͺ½μΌλ‘ κ°λ©΄ λ§μ§λ§ μ λ‘ μ΄λν©λλ€.
• κ° μ¦κ° λ° κ°μ (π, π):
• π: νμ¬ μ κ°μ 1 μ¦κ°μν΅λλ€.
• π: νμ¬ μ κ°μ 1 κ°μμν΅λλ€.
• μΆλ ₯ λͺ λ Ή (π¬):
• νμ¬ μ μ κ°μ ASCII λ¬Έμλ‘ λ³νν΄ output 리μ€νΈμ μΆκ°ν©λλ€. chr(get_value())λ₯Ό ν΅ν΄ ASCII λ³νμ μνν©λλ€.
• λ°λ³΅ μ²λ¦¬ (π):
• π λ€μμ μ€λ λ μ리 μ«μλ 16μ§μλ‘ λͺ λ² λ°λ³΅ν μ§ λνλ λλ€. μλ₯Ό λ€μ΄ π47μ μ§μ λͺ λ Ήμ 0x47(μ¦, 71λ²) λ°λ³΅νλ κ²μ λλ€.
• μ΄ λ μ§μ λͺ λ Ή(π, π, π, π)μ λ°λ³΅ν΄μ μ€νν©λλ€.
3. νμΌ μ½κΈ°:
input.txt νμΌμ μ½μ΄ Emoji Stack νλ‘κ·Έλ¨ λ΄μ©μ κ°μ Έμ΅λλ€.
4. ν΄μκΈ° μ€ν:
emoji_stack_interpreter(program) ν¨μμ νμΌμμ μ½μ νλ‘κ·Έλ¨μ μ λ¬νμ¬ μ€νν ν, μΆλ ₯κ°(νλκ·Έ)μ λ°ν