How to use Miasm ?
- User
How to use Miasm ?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
How to use Miasm ?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Miasm is a powerful reverse engineering framework written in Python that allows you to analyze, disassemble, emulate, and manipulate binary code. Below is a step-by-step guide to get started with Miasm, including key concepts and examples.
pip install miasm
git clone https://github.com/cea-sec/miasm
cd miasm
python3 setup.py install --user
Disassemble raw machine code into human-readable assembly.
Example: Disassembling x86 Code
from miasm.analysis.binary import Container
from miasm.analysis.machine import Machine
# Sample x86 machine code for "mov eax, 0x1; ret"
data = b"\xB8\x01\x00\x00\x00\xC3"
# Load the binary
container = Container.from_string(data, Machine("x86_32"))
disasm = container.dis_engine()
# Disassemble
for instr in disasm.dis_multiblock(0):
print(instr)
Output:
0x0: mov eax, 0x1
0x5: ret
Convert assembly to a generic intermediate representation (IR) for analysis.
Example: Lifting x86 to IR
from miasm.core.asmblock import AsmCFG
from miasm.analysis.machine import Machine
machine = Machine("x86_32")
lift_engine = machine.lifter_model_call
# Create an AsmCFG (Control Flow Graph)
asmcfg = AsmCFG()
asmcfg.add_machine_code_block(0, data)
# Lift to IR
ircfg = lift_engine.new_ircfg_from_asmcfg(asmcfg)
for block in ircfg.blocks.values():
print(block)
Track symbolic values through code to analyze behavior.
Example: Symbolic Execution
from miasm.analysis.sandbox import Sandbox
from miasm.analysis.symbolic import SymbolicExecutionEngine
# Load binary
sandbox = Sandbox("path/to/binary", ["arg1", "arg2"])
symbolic = SymbolicExecutionEngine(sandbox.machine)
# Run symbolic execution
symbolic.run(sandbox.entry_point)
print(symbolic.get_all_regs())
Emulate binary code execution in a controlled environment.
Example: Emulating x86 Code
from miasm.core.asmblock import AsmCFG
from miasm.analysis.machine import Machine
machine = Machine("x86_32")
vm = machine.vmm()
# Load code into memory
vm.add_memory(0x0, 0x1000, data)
# Emulate
vm.run(0x0)
print(vm.get_gpregs())
Visualize control flow graphs (CFGs) using Graphviz.
Example: Generate CFG
from miasm.core.graph import DiGraph
from miasm.analysis.machine import Machine
machine = Machine("x86_32")
disasm = machine.dis_engine(data)
cfg = disasm.dis_multiblock(0)
# Generate graph
graph = DiGraph()
for block in cfg:
graph.add_node(block)
for dst in block.bto:
graph.add_edge(block, dst)
# Save as DOT file
graph.to_dot("cfg.dot")
Run dot -Tpng cfg.dot -o cfg.png to generate a PNG image.
Implement custom logic to analyze IR or CFGs. For example, detect XOR operations:
from miasm.ir.symbexec import SymbolicExecutionEngine
def detect_xor(ircfg):
for block in ircfg.blocks.values():
for assign in block.irs:
for op in assign:
if op.op == "XOR":
print(f"XOR found at {block.loc_key}")
Miasm supports multiple architectures:
Example: ARM Disassembly
machine = Machine("arm")
disasm = machine.dis_engine(data)
Use the miasm command-line tool for quick analysis:
miasm
This opens a REPL for disassembly, IR lifting, and scripting.
sudo apt install graphviz) for CFG visualization.x86_32 vs x86_64).With these tools, you can analyze malware, reverse engineer binaries, or build custom analysis tools. Start small, experiment with simple code snippets, and gradually tackle complex binaries! 🛠️
How to use the jitter ?
The Jitter in Miasm is a powerful component for emulating machine code in a controlled environment. It abstracts the execution engine (using backends like Unicorn Engine or QEMU) to allow precise control over CPU state, memory, and hooks. Below is a step-by-step guide to using the Jitter effectively.
The Jitter is Miasm's interface for dynamic binary execution. It supports:
from miasm.analysis.machine import Machine
from miasm.core.locationdb import LocationDB
Use a simple x86 snippet (e.g., mov eax, 0x42; ret):
# x86 machine code for "mov eax, 0x42; ret"
CODE = b"\xB8\x42\x00\x00\x00\xC3"
Choose an architecture and backend (e.g., x86_32 with Unicorn):
machine = Machine("x86_32") # Architecture
loc_db = LocationDB() # Symbolic labels database
jitter = machine.jitter(loc_db, backend="unicorn") # Use "qemu" for QEMU backend
Allocate memory and write the code:
# Map executable memory
jitter.vm.add_memory_page(0x400000, 0x7, b"\x00" * 0x1000) # RWX at 0x400000
jitter.vm.set_code(0x400000, CODE) # Write code at 0x400000
Set initial CPU state:
I get NoneType object is not callable when calling machine.jitter()
The error NoneType object is not callable when calling machine.jitter() typically indicates that the Machine instance failed to initialize the Jitter backend. This can happen due to:
Miasm requires precise architecture identifiers (e.g., x86_32, x86_64, arm, mips32, etc.). Using an unsupported or incorrect name (e.g., x86 instead of x86_32) will result in machine.jitter being None.
Fix:
from miasm.analysis.machine import Machine
# Correct architecture strings
machine = Machine("x86_32") # Valid
# machine = Machine("x86") # Invalid ❌
The Jitter relies on external backends like Unicorn Engine or QEMU. If the backend is not installed, machine.jitter() returns None.
Fix: Install the required backend
# Install Unicorn Engine (required for "unicorn" backend)
pip install unicorn
# Optional: Install QEMU for "qemu" backend (requires Miasm compiled with QEMU support)
Older versions of Miasm (e.g., from PyPI) may lack updates or have bugs. Use the latest version from GitHub.
Fix: Update Miasm
# Clone the latest version
git clone https://github.com/cea-sec/miasm
cd miasm
python3 setup.py install --user
Verify your setup with this minimal script:
jitter.cpu.EAX = 0x0 # Clear EAX
jitter.cpu.EIP = 0x400000 # Set entry point
Execute from the entry point:
jitter.run(0x400000) # Start execution at 0x400000
Verify the outcome:
print(f"EAX = {jitter.cpu.EAX:x}") # Should print "EAX = 42"
Hooks allow you to monitor or modify execution at specific addresses.
Example: Hook at 0x400000
def hook_example(jitter):
print("Hook triggered at 0x400000")
return True # Continue execution
jitter.add_breakpoint(0x400000, hook_example)
Track read/write operations:
def on_memory_access(jitter, access, addr, size, value):
print(f"Memory {access} at 0x{addr:x}, size {size}, value 0x{value:x}")
jitter.vm.set_mem_access(on_memory_access)
Implement custom syscall handlers:
def syscall_handler(jitter):
# Example: Hook int 0x80 (Linux syscall)
if jitter.cpu.EAX == 1: # sys_exit
print("Exit called with code:", jitter.cpu.EBX)
return True
jitter.add_exception_handler(syscall_handler)
Switch to ARM or MIPS:
# ARM example
machine = Machine("arm")
jitter = machine.jitter(loc_db)
Miasm supports multiple execution backends:
Select a Backend:
jitter = machine.jitter(loc_db, backend="unicorn") # or "qemu"
pip install unicorn).jitter.dump_gpregs() to print all registers.jitter.add_breakpoint(addr, hook).jitter.vm.set_trace(True).from miasm.analysis.machine import Machine
from miasm.core.locationdb import LocationDB
# Step 1: Define machine code
CODE = b"\xB8\x42\x00\x00\x00\xC3" # mov eax, 0x42; ret
# Step 2: Initialize Jitter
machine = Machine("x86_32")
loc_db = LocationDB()
jitter = machine.jitter(loc_db, backend="unicorn")
# Step 3: Setup memory
jitter.vm.add_memory_page(0x400000, 0x7, b"\x00" * 0x1000)
jitter.vm.set_code(0x400000, CODE)
# Step 4: Initialize registers
jitter.cpu.EAX = 0x0
jitter.cpu.EIP = 0x400000
# Step 5: Run
jitter.run(0x400000)
# Step 6: Verify
print(f"EAX = {jitter.cpu.EAX:x}") # Output: EAX = 42
By mastering the Jitter, you can dynamically analyze malware, unpack binaries, or build custom exploit analysis tools. Start with simple snippets and expand to complex scenarios! 🚀
from miasm.analysis.machine import Machine
from miasm.core.locationdb import LocationDB
# Step 1: Use a valid architecture
machine = Machine("x86_32") # Valid architecture
# Step 2: Ensure Jitter is available
if machine.jitter is None:
raise RuntimeError("Jitter backend not initialized. Check architecture/backend.")
# Step 3: Initialize Jitter
loc_db = LocationDB()
jitter = machine.jitter(loc_db, backend="unicorn") # Ensure "unicorn" is installed
# Step 4: Setup memory and registers
jitter.vm.add_memory_page(0x400000, 0x7, b"\x00" * 0x1000)
jitter.vm.set_code(0x400000, b"\xB8\x42\x00\x00\x00\xC3") # mov eax, 0x42; ret
jitter.cpu.EIP = 0x400000
# Step 5: Run
jitter.run(0x400000)
# Step 6: Check result
print(f"EAX = {jitter.cpu.EAX:x}") # Should print "EAX = 42"
print(machine) # Should show "Machine('x86_32')"
print(machine._jitter_backends) # Lists supported backends (e.g., ['unicorn', 'qemu'])
import unicorn # If this fails, install Unicorn: pip install unicorn
| Issue | Solution |
|---|---|
machine = Machine("x86") | Use x86_32 or x86_64 |
backend="unicorn" fails | Install Unicorn: pip install unicorn |
machine.jitter is None | Ensure architecture and backend are valid |
ImportError: No module named 'unicorn' | Install Unicorn Engine |
By addressing these issues, you should resolve the NoneType error and successfully initialize the Jitter. If problems persist, test with a known-good environment (e.g., Docker or VM) to rule out local configuration issues. 🛠️