Skip to content

Instantly share code, notes, and snippets.

@P403n1x87
Created October 5, 2022 09:45
Show Gist options
  • Save P403n1x87/5d3f926d0f40dde2e2495b5a6f569dcd to your computer and use it in GitHub Desktop.
Save P403n1x87/5d3f926d0f40dde2e2495b5a6f569dcd to your computer and use it in GitHub Desktop.
gevent patch poc

When run as

python -m main

the expected output is

[abu] patched dolly
[main] Abu

That's because we are patching the dolly module and the Dolly class is now the Abu class.

When run as

PYHTONPATH=. python -m main

we force the pre-loading of the sitecustomize.py script, which loads dolly and spawns a thread that later on creates an instance of dolly.Dolly. However, at this point the module is patched by main, whence

[sitecustomize] Dolly
[abu] patched dolly
[main] Abu
[thread] Abu

When run as

CLONE=1 PYHTONPATH=. python -m main

we ask abu to first make a "clone" of the dolly module by deleting the "dolly" entry from sys.modules. The call to __import__ will reload the module, effectively creating a clone that will be patched instead of the original one. This leaves the references acquired by the sitecustomize.py script intact, while all the code executed after the patching will make use of the patched cloned module:

[sitecustomize] Dolly
[abu] cloning dolly
[abu] patched dolly
[main] Abu
[thread] Dolly
import os
import sys
clone = bool(os.getenv("CLONE", False))
class Abu(object):
pass
def patch():
global clone
if clone:
print("[abu] cloning dolly")
del sys.modules["dolly"]
dolly = __import__("dolly")
dolly.Dolly = Abu
print("[abu] patched dolly")
class Dolly(object):
pass
import abu
abu.patch()
import dolly
d = dolly.Dolly()
print("[main] %s" % d.__class__.__name__)
import dolly
from threading import Thread
from time import sleep
d = dolly.Dolly()
print("[sitecustomize] %s" % d.__class__.__name__)
def target():
sleep(1)
d = dolly.Dolly()
print("[thread] %s" % d.__class__.__name__)
Thread(target=target).start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment