├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── metame ├── __init__.py ├── constants.py ├── r2parser.py └── x86handler.py ├── screens ├── screen1.png └── screen2.png ├── scripts └── metame ├── setup.cfg └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:stable 2 | 3 | RUN apt update && apt install -y \ 4 | build-essential \ 5 | cmake \ 6 | python-pip \ 7 | git \ 8 | time \ 9 | && git clone https://github.com/radare/radare2 \ 10 | && cd radare2 \ 11 | && sys/install.sh \ 12 | && cd && git clone https://github.com/keystone-engine/keystone/ \ 13 | && cd keystone \ 14 | && mkdir build \ 15 | && cd build/ \ 16 | && ../make-share.sh \ 17 | && make install \ 18 | && ldconfig \ 19 | && pip install metame simplejson \ 20 | && rm -rf /var/lib/apt/lists/* 21 | 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Alberto Ortega 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # metame 2 | 3 | metame is a simple metamorphic code engine for arbitrary executables. 4 | 5 | From Wikipedia: 6 | 7 | > Metamorphic code is code that when run outputs a logically equivalent 8 | > version of its own code under some interpretation. 9 | > This is used by computer viruses to avoid the pattern recognition of 10 | > anti-virus software. 11 | 12 | metame implementation works this way: 13 | 14 | 1. Open a given binary and analyze the code 15 | 2. Randomly replace instructions with equivalences in logic and size 16 | 3. Copy and patch the original binary to generate a mutated variant 17 | 18 | It currently supports the following architectures: 19 | 20 | - x86 32 bits 21 | - x86 64 bits 22 | 23 | Also, it supports a variety of file formats, as [radare2][1] is used for 24 | file parsing and code analysis. 25 | 26 | Example of code before and after mutation: 27 | 28 | ![alt text](https://raw.githubusercontent.com/a0rtega/metame/master/screens/screen1.png "Spot the differences") 29 | 30 | Hint: Two instructions have been replaced in this snippet. 31 | 32 | Here another example on how it can mutate a NOP sled into equivalent code: 33 | 34 | ![alt text](https://raw.githubusercontent.com/a0rtega/metame/master/screens/screen2.png "Spot the differences") 35 | 36 | ## Installation 37 | 38 | ``` 39 | pip install metame 40 | ``` 41 | 42 | This should also install the requirements. 43 | 44 | You will also need [radare2][1]. Refer to the official website for 45 | installation instructions. 46 | 47 | `simplejson` is also a "nice to have" for a small performance 48 | boost: 49 | 50 | ``` 51 | pip install simplejson 52 | ``` 53 | 54 | ## Usage 55 | 56 | ``` 57 | metame -i original.exe -o mutation.exe -d 58 | ``` 59 | 60 | Use `metame -h` for help. 61 | 62 | ## License 63 | 64 | This project is released under the terms of the MIT license. 65 | 66 | [1]: http://radare.org/ 67 | 68 | -------------------------------------------------------------------------------- /metame/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | def main(): 3 | import sys 4 | import shutil 5 | import metame.r2parser as r2parser 6 | import argparse 7 | 8 | parser = argparse.ArgumentParser(description="Metamorphic engine that modifies assembly code keeping the same functionality") 9 | parser.add_argument("-i", "--input", help="input file") 10 | parser.add_argument("-o", "--output", help="output file") 11 | parser.add_argument("-d", "--debug", action="store_true", help="print debug information") 12 | parser.add_argument("-f", "--force", action="store_true", help="force instruction replacement when possible (decreases metamorphism entropy!)") 13 | args = parser.parse_args() 14 | 15 | if not args.input or not args.output: 16 | parser.print_help() 17 | sys.exit(1) 18 | 19 | r = r2parser.R2Parser(args.input, True, debug=args.debug, force_replace=args.force) 20 | patches = r.iterate_fcn() 21 | r.close() 22 | 23 | shutil.copy(args.input, args.output) 24 | 25 | r = r2parser.R2Parser(args.output, False, debug=args.debug, write=True) 26 | r.patch_binary(patches) 27 | r.close() 28 | 29 | -------------------------------------------------------------------------------- /metame/constants.py: -------------------------------------------------------------------------------- 1 | 2 | supported_archs = ["x86"] 3 | supported_bits = [32, 64] 4 | -------------------------------------------------------------------------------- /metame/r2parser.py: -------------------------------------------------------------------------------- 1 | 2 | import metame.x86handler as x86handler 3 | import metame.constants as constants 4 | 5 | import r2pipe 6 | try: 7 | import simplejson as json 8 | except: 9 | import json 10 | 11 | class R2Parser: 12 | def __init__(self, filename, anal, debug=False, force_replace=False, write=False): 13 | self.debug = debug 14 | self.force = force_replace 15 | flags = [] 16 | if write: 17 | flags.append("-w") 18 | print("[INFO] Opening file with r2") 19 | self.r2 = r2pipe.open(filename, flags) 20 | info = json.loads(self.r2.cmd("ij").replace("\\", "\\\\")) 21 | if "bin" not in info.keys(): 22 | raise Exception("[ERROR] File type not supported") 23 | if not info["bin"]["bits"] in constants.supported_bits or \ 24 | not info["bin"]["arch"] in constants.supported_archs: 25 | raise Exception("[ERROR] Architecture not supported") 26 | self.arch = info["bin"]["arch"] 27 | self.bits = info["bin"]["bits"] 28 | if anal: 29 | print("[INFO] Analyzing functions with r2") 30 | self.r2.cmd("aaa") 31 | 32 | def iterate_fcn(self): 33 | if self.arch == "x86": 34 | arch = x86handler.X86Handler(self.bits, self.debug, self.force) 35 | replacements = [] 36 | print("[INFO] Loading functions information") 37 | fcns = json.loads(self.r2.cmd("aflj")) 38 | print("[INFO] Replacing instructions") 39 | for f in fcns: 40 | if f["type"] == "fcn": 41 | try: 42 | fcn_ctx = json.loads(self.r2.cmd("pdfj @%s" % f["name"])) 43 | except: 44 | print("[ERROR] Error disassembling function %s" % f["name"]) 45 | replacements += arch.replace_fcn_opcodes(fcn_ctx) 46 | return replacements 47 | 48 | def patch_binary(self, patches): 49 | print("[INFO] Patching binary") 50 | for w in patches: 51 | self.r2.cmd("wx %s @%s" % (w["newbytes"], w["offset"])) 52 | print("[INFO] Done, number of instructions changed: %s" % (len(patches))) 53 | 54 | def close(self): 55 | self.r2.quit() 56 | 57 | -------------------------------------------------------------------------------- /metame/x86handler.py: -------------------------------------------------------------------------------- 1 | 2 | import metame.constants as constants 3 | 4 | import re 5 | import random 6 | from keystone import * 7 | 8 | class X86Handler: 9 | def get_nops(self, size, prev_ins_size=0): 10 | if self.bits == 32: 11 | regs = ["eax", "ebx", "ecx", "edx", "esi", "edi"] 12 | else: 13 | regs = ["rax", "rbx", "rcx", "rdx", "rsi", "rdi"] 14 | if size == 1: 15 | return "nop" 16 | elif size == 2 and self.bits == 32: 17 | r = random.randint(1, 3) 18 | if r == 1: 19 | reg = random.choice(regs) 20 | return "push %s; pop %s" % (reg, reg) 21 | elif r == 2: 22 | return "pushad; popad" 23 | elif r == 3: 24 | return "%s; %s" % (self.get_nops(1), self.get_nops(1)) 25 | elif size == 3 and self.bits == 32: 26 | r = random.randint(1, 5) 27 | if r == 1: 28 | return "jmp %s; inc %s" % (3 + prev_ins_size, random.choice(regs)) 29 | elif r == 2: 30 | return "jmp %s; push %s" % (3 + prev_ins_size, random.choice(regs)) 31 | elif r == 3: 32 | return "jmp %s; pop %s" % (3 + prev_ins_size, random.choice(regs)) 33 | elif r == 4: 34 | return "%s; %s" % (self.get_nops(1), self.get_nops(2)) 35 | elif r == 5: 36 | return "%s; %s" % (self.get_nops(2), self.get_nops(1)) 37 | elif size == 2 and self.bits == 64: 38 | reg = random.choice(regs) 39 | return "push %s; pop %s" % (reg, reg) 40 | elif size == 3 and self.bits == 64: 41 | r = random.randint(1, 4) 42 | if r == 1: 43 | reg = random.choice(regs) 44 | return "push %s; pop %s; %s" % (reg, reg, self.get_nops(1)) 45 | elif r == 2: 46 | reg = random.choice(regs) 47 | return "%s; push %s; pop %s" % (self.get_nops(1), reg, reg) 48 | elif r == 3: 49 | return "%s; %s" % (self.get_nops(1), self.get_nops(2)) 50 | elif r == 4: 51 | return "%s; %s" % (self.get_nops(2), self.get_nops(1)) 52 | elif size == 4 and self.bits == 64: 53 | r = random.randint(1, 5) 54 | if r == 1: 55 | return "jmp %s; pop %s; pop %s" % (4 + prev_ins_size, random.choice(regs), 56 | random.choice(regs)) 57 | elif r == 2: 58 | return "jmp %s; push %s; push %s" % (4 + prev_ins_size, random.choice(regs), 59 | random.choice(regs)) 60 | elif r == 3: 61 | return "jmp %s; push %s; pop %s" % (4 + prev_ins_size, random.choice(regs), 62 | random.choice(regs)) 63 | elif r == 4: 64 | return "jmp %s; pop %s; push %s" % (4 + prev_ins_size, random.choice(regs), 65 | random.choice(regs)) 66 | elif r == 5: 67 | return "%s; %s" % (self.get_nops(2), self.get_nops(2)) 68 | 69 | def __init__(self, bits, debug=False, force_replace=False): 70 | self.bits = bits 71 | self.debug = debug 72 | self.force = force_replace 73 | ks_mode = KS_MODE_32 if self.bits == 32 else KS_MODE_64 74 | self.ks = Ks(KS_ARCH_X86, ks_mode) 75 | self.init_mutations() 76 | 77 | def init_mutations(self): 78 | if self.bits == 32: 79 | self.mutables = frozenset(["nop","acmp","or","xor","sub","mov","push"]) 80 | self.X86_SUBS = [ 81 | ( 82 | ((re.compile(r"^mov (?Pe..), (?P(?P=a))$"),), "mov {a}, {b}", True), 83 | ((), "%s" % self.get_nops(2), False), 84 | ), 85 | ( 86 | ((re.compile(r"^nop$"),re.compile(r"^nop$"),re.compile(r"^nop$")), "nop; nop; nop", True), 87 | ((), "%s" % self.get_nops(3), False), 88 | ), 89 | ( 90 | ((re.compile(r"^nop$"),re.compile(r"^nop$")), "nop; nop", True), 91 | ((), "%s" % self.get_nops(2), False), 92 | ), 93 | ( 94 | ((re.compile(r"^test (?Pe..), (?P(?P=a))$"),), "test {a}, {b}", True), 95 | ((re.compile(r"^or (?Pe..), (?P(?P=a))$"),), "or {a}, {b}", True), 96 | ), 97 | ( 98 | ((re.compile(r"^xor (?Pe..), (?P(?P=a))$"),), "xor {a}, {b}", True), 99 | ((re.compile(r"^sub (?Pe..), (?P(?P=a))$"),), "sub {a}, {b}", True), 100 | ), 101 | ( 102 | ((re.compile(r"^mov (?Pe..), (?Pe..)$"),), "mov {a}, {b}", True), 103 | ((re.compile(r"^push (?Pe..)$"),re.compile(r"^pop (?Pe..)$")), "push {b}; pop {a}", True), 104 | ), 105 | ( 106 | ((re.compile(r"^mov (?Pe..), (?P0?x?0)$"),), "mov {a}, {b}", True), 107 | ((), "pushfd; xor {a}, {a}; popfd; %s" % self.get_nops(1), False), 108 | ((), "pushfd; sub {a}, {a}; popfd; %s" % self.get_nops(1), False), 109 | ((), "pushfd; and {a}, 0; popfd", False), 110 | ), 111 | ( 112 | ((re.compile(r"^mov (?Pe..), (?P0?x?1)$"),), "mov {a}, {b}", True), 113 | ((), "pushfd; xor {a}, {a}; inc {a}; popfd", False), 114 | ), 115 | ( 116 | ((re.compile(r"^mov (?Pe..), (?P0?x?([0-7][0-9A-Fa-f]|[0-9A-Fa-f]))$"),), "mov {a}, {b}", True), 117 | ((), "push {b}; pop {a}; %s" % self.get_nops(2), False), 118 | ((), "%s; push {b}; pop {a}" % self.get_nops(2), False), 119 | ((), "%s; push {b}; %s; pop {a}" % (self.get_nops(1), self.get_nops(1)), False), 120 | ), 121 | ] 122 | else: 123 | self.mutables = frozenset(["nop","acmp","or","xor","sub","mov"]) 124 | self.X86_SUBS = [ 125 | # Variations of 32 bits payloads 126 | ( 127 | ((re.compile(r"^mov (?Pe..), (?P(?P=a))$"),), "mov {a}, {b}", True), 128 | ((), "%s" % self.get_nops(2), False), 129 | ), 130 | ( 131 | ((re.compile(r"^nop$"),re.compile(r"^nop$"),re.compile(r"^nop$")), "nop; nop; nop", True), 132 | ((), "%s" % self.get_nops(3), False), 133 | ), 134 | ( 135 | ((re.compile(r"^nop$"),re.compile(r"^nop$")), "nop; nop", True), 136 | ((), "%s" % self.get_nops(2), False), 137 | ), 138 | ( 139 | ((re.compile(r"^test (?Pe..), (?P(?P=a))$"),), "test {a}, {b}", True), 140 | ((re.compile(r"^or (?Pe..), (?P(?P=a))$"),), "or {a}, {b}", True), 141 | ), 142 | ( 143 | ((re.compile(r"^xor (?Pe..), (?P(?P=a))$"),), "xor {a}, {b}", True), 144 | ((re.compile(r"^sub (?Pe..), (?P(?P=a))$"),), "sub {a}, {b}", True), 145 | ), 146 | # Purely 64 bits payloads 147 | ( 148 | ((re.compile(r"^test (?Pr..), (?P(?P=a))$"),), "test {a}, {b}", True), 149 | ((re.compile(r"^or (?Pr..), (?P(?P=a))$"),), "or {a}, {b}", True), 150 | ), 151 | ( 152 | ((re.compile(r"^xor (?Pr..), (?P(?P=a))$"),), "xor {a}, {b}", True), 153 | ((re.compile(r"^sub (?Pr..), (?P(?P=a))$"),), "sub {a}, {b}", True), 154 | ), 155 | ( 156 | ((re.compile(r"^mov (?Pr.(i|x|p)), (?Pr.(i|x|p))$"),), "mov {a}, {b}", True), 157 | ((), "push {b}; pop {a}; %s" % self.get_nops(1), False), 158 | ((), "%s; push {b}; pop {a}" % self.get_nops(1), False), 159 | ((), "push {b}; %s; pop {a}" % self.get_nops(1), False), 160 | ), 161 | ] 162 | 163 | def assemble_code(self, codestr): 164 | encoding, count = self.ks.asm(codestr) 165 | return "".join(["%02x" % i for i in encoding]) 166 | 167 | def replace_fcn_opcodes(self, fcn_ctx): 168 | replacements = [] 169 | # Iternate instructions 170 | count = -1 171 | n_ops = len(fcn_ctx["ops"]) 172 | while count < n_ops-1: 173 | count += 1 174 | if fcn_ctx["ops"][count].get("type") not in self.mutables: 175 | continue 176 | # Iternate possible substitutions 177 | for x86_sub in self.X86_SUBS: 178 | # Iterate equivalences in substitution 179 | for x86_find in x86_sub: 180 | # Use this equivalence as match, or only as replacement? 181 | if not x86_find[2]: 182 | continue 183 | count_2 = 0 184 | ms = [] 185 | opcodes_len = 0 186 | # Iterate needed matches 187 | for x86_m in x86_find[0]: 188 | try: 189 | # Match 190 | m = x86_m.match(fcn_ctx["ops"][count+count_2]["opcode"]) 191 | if not m: 192 | break 193 | except: 194 | break 195 | # Store matches 196 | ms.append(m) 197 | # Increase opcodes size 198 | opcodes_len += len(fcn_ctx["ops"][count+count_2]["bytes"]) 199 | count_2 += 1 200 | else: 201 | # Previous iteration was completed, so all needed matches matched 202 | # Choose a random substitution 203 | sub = random.choice(x86_sub) 204 | # If forced, force finding a different substitution 205 | while self.force and sub == x86_find: 206 | sub = random.choice(x86_sub) 207 | # Random substitution is the same, do nothing 208 | if sub == x86_find: 209 | continue 210 | res_ass = sub[1] 211 | # Create assembly replacing match groups 212 | for m in ms: 213 | for idx in m.groupdict().keys(): 214 | res_ass = res_ass.replace("{%s}" % idx, m.groupdict()[idx]) 215 | if self.debug: 216 | print("[DEBUG] Replacing instruction at %s (%s) with: %s ... " % ( 217 | hex(fcn_ctx["ops"][count]["offset"]), 218 | fcn_ctx["ops"][count]["opcode"], 219 | res_ass)) 220 | # Assemble new code 221 | new_assembly = self.assemble_code(res_ass) 222 | # Check if new assembly is equal in size 223 | if len(new_assembly) == opcodes_len: 224 | replacements.append({"offset": fcn_ctx["ops"][count]["offset"], 225 | "newbytes": new_assembly}) 226 | # Avoid patching over again 227 | count += count_2 - 1 228 | # Restart mutations to reseed random nops 229 | self.init_mutations() 230 | break 231 | else: 232 | if self.debug: 233 | print("[DEBUG] Instruction opcodes are different in size") 234 | else: 235 | # Previous iteration failed, continue finding substitutions 236 | # for this instruction 237 | continue 238 | # Previous iteration was completed correctly, stop 239 | # finding substitutions for this instruction 240 | break 241 | return replacements 242 | 243 | -------------------------------------------------------------------------------- /screens/screen1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/a0rtega/metame/8d583a0fda1748fa007d0aab9f72739cbcc8bae2/screens/screen1.png -------------------------------------------------------------------------------- /screens/screen2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/a0rtega/metame/8d583a0fda1748fa007d0aab9f72739cbcc8bae2/screens/screen2.png -------------------------------------------------------------------------------- /scripts/metame: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import metame 4 | 5 | metame.main() 6 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | 3 | setup( 4 | name = 'metame', 5 | packages = ['metame'], 6 | version = '0.4', 7 | description = 'metame is a metamorphic code engine for arbitrary executables', 8 | author = 'Alberto Ortega', 9 | author_email = 'aortega.lms+metame@gmail.com', 10 | url = 'https://github.com/a0rtega/metame', 11 | download_url = 'https://github.com/a0rtega/metame/archive/master.tar.gz', 12 | scripts = ['scripts/metame'], 13 | install_requires = ["keystone-engine", "r2pipe"], 14 | keywords = ['metamorphic', 'code', 'engine'], 15 | classifiers = [ 16 | 'Topic :: Security', 17 | 'Environment :: Console', 18 | 'Operating System :: OS Independent', 19 | 'Intended Audience :: Developers' 20 | ], 21 | ) 22 | 23 | --------------------------------------------------------------------------------