-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_obfuscator.py
More file actions
83 lines (74 loc) · 2.64 KB
/
python_obfuscator.py
File metadata and controls
83 lines (74 loc) · 2.64 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import ast
import random
import string
import base64
#made by modelguyzz
def obfuscate_script(source_code: str) -> str:
"""
Obfuscates Python source code with:
Variable and function renaming
String encryption (Base64)
Dead code injection
Polymorphic output (randomized each call)
"""
# Helper: Generate random variable/function names
def random_name(length=6):
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for _ in range(length))
# made by modelguyzz
# Step 1: Parse source code to AST
tree = ast.parse(source_code)
# Step 2: Collect variable and function names
class NameCollector(ast.NodeVisitor):
def __init__(self):
self.names = set()
def visit_Name(self, node):
if isinstance(node.ctx, ast.Store) or isinstance(node.ctx, ast.Load):
self.names.add(node.id)
def visit_FunctionDef(self, node):
self.names.add(node.name)
self.generic_visit(node)
collector = NameCollector()
collector.visit(tree)
# Step 3: Build name mapping
name_map = {name: random_name(random.randint(3, 10)) for name in collector.names}
# Step 4: AST Transformer for renaming and string encryption
class Obfuscator(ast.NodeTransformer):
def visit_Name(self, node):
if node.id in name_map:
node.id = name_map[node.id]
return node
def visit_FunctionDef(self, node):
if node.name in name_map:
node.name = name_map[node.name]
self.generic_visit(node)
return node
def visit_Str(self, node):
# Encrypt string using base64
encoded = base64.b64encode(node.s.encode("utf-8")).decode("utf-8")
return ast.Call(
func=ast.Name(id='_decode_string', ctx=ast.Load()),
args=[ast.Constant(value=encoded)],
keywords=[]
)
# made by modelguyzz
obfuscator = Obfuscator()
tree = obfuscator.visit(tree)
ast.fix_missing_locations(tree)
# Step 5: Dead code injection
dead_code_snippets = [
"if False:\n x = 12345\n",
"y = 0\nfor _ in range(0): y += 1\n",
"z = 'dummy' + 'code'\n",
"import math\nmath.sqrt(0)\n"
]
dead_code = random.choice(dead_code_snippets)
# Step 6: Build final source code with string decoder and dead code
final_code = f"""
import base64
{dead_code}
def _decode_string(s):
return base64.b64decode(s).decode('utf-8')
"""
final_code += ast.unparse(tree)
return final_code