상세 컨텐츠

본문 제목

[Dreamhack] Python Start (Pwnable)

SYSTEM HACKING/Dreamhack

by koharin 2025. 7. 24. 22:39

본문

728x90
반응형

CTF pwnable python으로 검색해보니..N-CTF 2019에서 출제된 Python Jailbreak 문제와 유사했다.

def filter_code(user_input): # You cannot use those words.
    banned_word=['eval', 'exec', 'import', 'open', 'os', 'read', 'system', 'write', 'sh', 'break', 'mro', 'cat', 'flag']
    for i in range(0,len(banned_word),1):
        x=banned_word[i]
        if x in user_input:
            return False
    return True

현재 13가지가 block된 상황이다.

code=input('Input code > ') # Please input your code.
result=filter_code(code) # Check if you used banned word.

if result==True: # If you follow my rule, then I execute your code.
    try:
        exec(code) # (*) Search what does 'exec' means!
    except:
        pass
else:
    print('Your input is blocked.')

입력을 filter_code 함수에 의해 검사한 후, 없으면 exec()로 입력된 명령어를 실행해준다. 즉, code execution이 가능하다.

Python Jailbreack write up을 참고해보면, dir() 명령어를 활용한다.

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> __name__
'__main__'
>>> import os
>>> hello='world'
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'hello', 'os']

dir() 내장 함수는 어떤 객체를 인자로 넣어주면 해당 객체가 어떤 변수와 메소드(method)를 가지고 있는지 나열해준다고 한다.

>>> dir(hello)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

만약 str인 hello를 인자로 주는 경우, str 객체에 대한 메소드를 나열해준다.

이때 __builtins__은 에러와 내장함수를 담는 모듈이다.

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

'im'+'port'와 같이 우회 가능

os 모듈을 통해 system으로 명령어를 실행할건데,

이때 __builtins__의 import로 os를 import하고

system을 호출한다.

os, system, 등 필터링이 있기 때문에 'o'+'s'와 같이 우회해준다.

 

 

728x90
반응형

관련글 더보기