Creating an advanced deobfuscator with a graphical user interface (GUI) tailored for Lua and Luau scripts involves several key components:
- Parsing and Analyzing Lua/Luau Code
- Deobfuscation Techniques Implementation
- GUI Development
- Integration and User Experience Enhancements
Below is a comprehensive guide to developing such a tool using Python, leveraging the tkinter library for the GUI and lupa or LuaPy for Lua parsing and execution. Additionally, we'll utilize libraries like re for regex operations and ast for abstract syntax tree manipulation.
1. Setting Up the Environment
Prerequisites
-
Python 3.x: Ensure you have Python installed. You can download it from python.org.
-
Lua Parser Libraries: lupa or LuaPy can be used for Lua parsing.
pip install lupa
-
GUI Library: We'll use tkinter, which comes pre-installed with Python.
Directory Structure
deobfuscator/
├── main.py
├── gui.py
├── deobfuscator_engine.py
├── utils.py
├── requirements.txt
└── README.md
2. Designing the Deobfuscator Engine
2.1. Parsing Lua/Luau Code
Parsing Lua code can be done using the lupa library, which is a Lua-Python bridge.
# deobfuscator_engine.py
from lupa import LuaRuntime
class LuaParser:
def __init__(self):
self.lua = LuaRuntime(unpack_returned_tuples=True)
def parse_code(self, code):
try:
parsed = self.lua.execute(f"return {{...}}", globals={"...": code})
return parsed
except Exception as e:
print(f"Parsing Error: {e}")
return None
2.2. Deobfuscation Techniques
Implement various deobfuscation techniques as per the obfuscation types specified.
# deobfuscator_engine.py
import re
class Deobfuscator:
def __init__(self, code):
self.code = code
def remove_junk_code(self):
# Remove死 code blocks (Dead Code)
pattern = r"(if|elseif|else)\s*\(.*?\)\s*then\s*.*?end"
self.code = re.sub(pattern, '', self.code, flags=re.DOTALL)
return self
def simplify_arithmetic(self):
# Simplify modulo and hexadecimal operations
pattern = r"0x([0-9a-fA-F]+)"
self.code = re.sub(pattern, lambda x: str(int(x.group(0), 16)), self.code)
pattern = r"\((\w+)\s*[-+*/%]\s*\d+\)"
self.code = re.sub(pattern, lambda x: f"{x.group(1)}", self.code)
return self
def optimize_loops(self):
# Remove or simplify loops with random conditions
pattern = r"while\s*\(.*?\)\s*do\s*.*?end"
self.code = re.sub(pattern, '', self.code, flags=re.DOTALL)
return self
def rename_variables(self):
# Rename variables to meaningful names
var_pattern = r"\b([a-zA-Z_]\w*)\b"
variables = set(re.findall(var_pattern, self.code))
var_mapping = {var: f"var_{i}" for i, var in enumerate(variables)}
for var, new_var in var_mapping.items():
self.code = re.sub(rf"\b{var}\b", new_var, self.code)
return self
def deobfuscate(self):
self.remove_junk_code()
self.simplify_arithmetic()
self.optimize_loops()
self.rename_variables()
return self.code
2.3. Handling Environment Access and Function Execution
Ensure that any environment manipulations or dynamic function executions are safely handled or sanitized.
# deobfuscator_engine.py
class EnvironmentHandler:
def __init__(self, code):
self.code = code
def sanitize_environment_access(self):
# Remove or comment out getfenv and similar functions
self.code = re.sub(r"getfenv\s*\(.*?\)", "# Removed getfenv for safety", self.code)
return self.code
def sanitize(self):
self.sanitize_environment_access()
return self.code
3. Developing the GUI
Using tkinter for the GUI to allow users to input obfuscated code, perform deobfuscation, and view/download the deobfuscated code.
# gui.py
import tkinter as tk
from tkinter import filedialog, scrolledtext, messagebox
from deobfuscator_engine import LuaParser, Deobfuscator, EnvironmentHandler
class DeobfuscatorGUI:
def __init__(self, root):
self.root = root
self.root.title("Lua/Luau Deobfuscator")
self.create_widgets()
def create_widgets(self):
# Input Frame
input_frame = tk.Frame(self.root)
input_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
input_label = tk.Label(input_frame, text="Obfuscated Code:")
input_label.pack(anchor='w')
self.input_text = scrolledtext.ScrolledText(input_frame, height=15)
self.input_text.pack(fill=tk.BOTH, expand=True)
# Buttons Frame
buttons_frame = tk.Frame(self.root)
buttons_frame.pack(fill=tk.X, padx=10, pady=5)
load_button = tk.Button(buttons_frame, text="Load File", command=self.load_file)
load_button.pack(side=tk.LEFT, padx=5)
deobfuscate_button = tk.Button(buttons_frame, text="Deobfuscate", command=self.deobfuscate_code)
deobfuscate_button.pack(side=tk.LEFT, padx=5)
save_button = tk.Button(buttons_frame, text="Save Output", command=self.save_file)
save_button.pack(side=tk.LEFT, padx=5)
# Output Frame
output_frame = tk.Frame(self.root)
output_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
output_label = tk.Label(output_frame, text="Deobfuscated Code:")
output_label.pack(anchor='w')
self.output_text = scrolledtext.ScrolledText(output_frame, height=15, state='disabled')
self.output_text.pack(fill=tk.BOTH, expand=True)
def load_file(self):
file_path = filedialog.askopenfilename(filetypes=[("Lua Files", "*.lua"), ("All Files", "*.*")])
if file_path:
with open(file_path, 'r') as file:
code = file.read()
self.input_text.delete(1.0, tk.END)
self.input_text.insert(tk.END, code)
def deobfuscate_code(self):
code = self.input_text.get(1.0, tk.END)
if not code.strip():
messagebox.showwarning("Input Error", "Please provide obfuscated code.")
return
try:
parser = LuaParser()
parsed = parser.parse_code(code)
if not parsed:
messagebox.showerror("Parsing Error", "Failed to parse the Lua code.")
return
env_handler = EnvironmentHandler(code)
sanitized_code = env_handler.sanitize()
deobf = Deobfuscator(sanitized_code)
deobfuscated_code = deobf.deobfuscate()
self.output_text.configure(state='normal')
self.output_text.delete(1.0, tk.END)
self.output_text.insert(tk.END, deobfuscated_code)
self.output_text.configure(state='disabled')
messagebox.showinfo("Success", "Deobfuscation completed successfully.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred during deobfuscation: {e}")
def save_file(self):
file_path = filedialog.asksaveasfilename(defaultextension=".lua",
filetypes=[("Lua Files", "*.lua"), ("All Files", "*.*")])
if file_path:
with open(file_path, 'w') as file:
code = self.output_text.get(1.0, tk.END)
file.write(code)
messagebox.showinfo("Saved", f"Deobfuscated code saved to {file_path}")
def main():
root = tk.Tk()
app = DeobfuscatorGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
4. Integrating Deobfuscation Logic with the GUI
Ensure that the deobfuscation process is clearly separated from the GUI logic for maintainability.
# deobfuscator_engine.py
# (Include previously defined classes: LuaParser, Deobfuscator, EnvironmentHandler)
# main.py
from gui import main
if __name__ == "__main__":
main()
5. Enhancements and Advanced Features
To make the deobfuscator more advanced and effective, consider implementing the following:
5.1. Abstract Syntax Tree (AST) Manipulation
Use AST parsing to accurately interpret and modify the code structure.
# utils.py
import ast
def parse_lua_ast(code):
# Placeholder for Lua AST parsing logic
pass
def manipulate_ast(ast_tree):
# Implement AST manipulation for deobfuscation
pass
5.2. Preserving Code Formatting
After deobfuscation, preserve the original formatting for readability.
# deobfuscator_engine.py
import ast
import textwrap
class Formatter:
def __init__(self, code):
self.code = code
def format_code(self):
# Implement code formatting logic
try:
formatted_code = textwrap.dedent(self.code)
return formatted_code
except Exception as e:
print(f"Formatting Error: {e}")
return self.code
5.3. Handling Complex Obfuscation Patterns
Implement pattern recognition and specific algorithms to handle advanced obfuscation techniques described.
# deobfuscator_engine.py
class AdvancedDeobfuscator(Deobfuscator):
def handle_variable_reassignments(self):
# Implement logic to track and simplify variable reassignments
pass
def handle_random_calculations(self):
# Implement logic to simplify random calculations
pass
def handle_dead_code(self):
# Implement logic to detect and remove dead code blocks
pass
def deobfuscate_advanced(self):
self.handle_variable_reassignments()
self.handle_random_calculations()
self.handle_dead_code()
return self.code
5.4. User Configuration and Custom Rules
Allow users to define custom deobfuscation rules or choose which techniques to apply.
# gui.py (Add options for user configurations)
config_frame = tk.LabelFrame(self.root, text="Deobfuscation Options")
config_frame.pack(fill=tk.X, padx=10, pady=5)
self.remove_dead_code_var = tk.BooleanVar(value=True)
dead_code_cb = tk.Checkbutton(config_frame, text="Remove Dead Code", variable=self.remove_dead_code_var)
dead_code_cb.pack(side=tk.LEFT, padx=5)
# In deobfuscate_code method:
if self.remove_dead_code_var.get():
deobf.remove_junk_code()
# Similarly handle other options
6. Packaging the Application
Once development is complete, package the application for distribution.
6.1. Creating a requirements.txt
lupa
tk
6.2. Using PyInstaller to Create Executable
pip install pyinstaller
pyinstaller --onefile main.py
This will generate an executable file that can be distributed to users without requiring them to install Python or dependencies.
7. Considerations and Best Practices
-
Safety: When executing or parsing Lua code, ensure that the deobfuscator does not inadvertently execute malicious code. Prefer static analysis over dynamic execution.
-
Extensibility: Design the deobfuscator to be easily extendable with new deobfuscation techniques as obfuscation methods evolve.
-
User Feedback: Provide detailed logs or reports to inform users about the deobfuscation steps performed and any issues encountered.
-
Testing: Rigorously test the deobfuscator with various obfuscated code samples to ensure reliability and effectiveness.
8. Example Usage
Input Obfuscated Code
local e, f = 0, 1
while (e-69)%16318 do
f = (f*987)%6500
e = (e+12345)%0x31aa
end
if e % 2 ~= 0 then
print(getfenv())
else
-- Dead code
local h = f + e
end
Deobfuscated Output
local var_0, var_1 = 0, 1
print("# Removed getfenv for safety")
9. Conclusion
Building an advanced deobfuscator with a GUI involves integrating various components, including Lua parsing, deobfuscation logic, and a user-friendly interface. The above guide provides a foundational framework to develop such a tool. Depending on the complexity of the obfuscated code and specific requirements, further enhancements and optimizations may be necessary.
Remember to respect software licenses and intellectual property rights when deobfuscating code. Ensure that you have the appropriate permissions to deobfuscate and analyze the scripts in question.