py2.7测试通过

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# coding=utf-8
def hook_func(module, func, act, hook_arg, hook_result):
try:
if hook_arg or hook_result:
old_module = __import__(module)
old_function = getattr(old_module, func)
def wrapper(*args, **kwargs):
if hook_arg:
a = list(args)
k = [v for k, v in enumerate(kwargs)]
values = a.extend(k) if k else a
act(values)
result = old_function(*args, **kwargs)
if hook_result:
act(result)
return result
setattr(old_module, func, wrapper)
else:
pass
except Exception,e:
print e
def check_file_path(values):
if any('../' in path for path in values):
raise Exception('Insecure filepath found!')
def monkey_patch():
hook_func('__builtin__', 'open', check_file_path, hook_arg=True, hook_result=False)
if __name__ == '__main__':
monkey_patch()
open(input('enter your path >'),'w+')

测试

1
2
3
4
5
6
7
8
9
10
python builtins.py
enter your path >"../../sf"
Traceback (most recent call last):
File "builtins.py", line 37, in <module>
open(input('enter your path >'),'w+')
File "builtins.py", line 13, in wrapper
act(values)
File "builtins.py", line 30, in check_file_path
raise Exception('Insecure filepath found!')
Exception: Insecure filepath found!