Skip to content

Commit

Permalink
Hook can help debug regex usage
Browse files Browse the repository at this point in the history
  • Loading branch information
b-c-ds authored and bcaller committed Dec 31, 2020
1 parent 2a4a2b1 commit d48af06
Showing 1 changed file with 41 additions and 2 deletions.
43 changes: 41 additions & 2 deletions regexploit/hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,41 @@ def last_tb(self):
return self.traceback[-1]


class WrappedRegex:
def __init__(self, regex):
self.regex = regex

def run_and_log(self, method, args, kwargs):
print("Pattern:", repr(self.regex.pattern[:200]))
print(f"{method}()", *(repr(a) for a in args))
print(*traceback.format_stack()[2:-4])
return getattr(self.regex, method)(*args, **kwargs)

def search(self, *args, **kwargs):
return self.run_and_log("search", args, kwargs)

def match(self, *args, **kwargs):
return self.run_and_log("match", args, kwargs)

def fullmatch(self, *args, **kwargs):
return self.run_and_log("fullmatch", args, kwargs)

def sub(self, *args, **kwargs):
return self.run_and_log("sub", args, kwargs)

def subn(self, *args, **kwargs):
return self.run_and_log("subn", args, kwargs)

def split(self, *args, **kwargs):
return self.run_and_log("split", args, kwargs)

def findall(self, *args, **kwargs):
return self.run_and_log("findall", args, kwargs)

def finditer(self, *args, **kwargs):
return self.run_and_log("finditer", args, kwargs)


def get_and_clear_regexes():
"""
Retrieves regexes that have been `re.compile`-ed and removes them from the `regexes` set.
Expand All @@ -37,7 +72,7 @@ def get_and_clear_regexes():
return


def install():
def install(log_all_uses: bool = False):
"""
Activate the hook.
"""
Expand All @@ -47,7 +82,11 @@ def install():
def compile(pattern, flags=0):
tb = traceback.extract_stack()[:-1] # Ignore our hook
regexes.add(CompiledRegex(pattern, flags, tb))
return old_compile(pattern, flags)
regex = old_compile(pattern, flags)
if log_all_uses:
return WrappedRegex(regex)
else:
return regex

compile._is_hook = True
re.compile = compile
Expand Down

0 comments on commit d48af06

Please sign in to comment.