├── .github
└── workflows
│ ├── lint.yml
│ ├── publish_pyinstaller.yml
│ └── publish_pypi.yml
├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── docs
└── themida-mutation-recon24.pdf
├── poetry.lock
├── pyproject.toml
├── themida-unmutate.spec
└── themida_unmutate
├── __init__.py
├── __main__.py
├── logging.py
├── main.py
├── miasm_utils.py
├── rebuilding.py
├── symbolic_execution
├── __init__.py
└── x86
│ └── __init__.py
└── unwrapping.py
/.github/workflows/lint.yml:
--------------------------------------------------------------------------------
1 | name: Linting - Python
2 |
3 | on: [push]
4 |
5 | jobs:
6 | lint:
7 | name: Linting - Python ${{ matrix.python_version }}
8 | strategy:
9 | fail-fast: false
10 | matrix:
11 | python_version: ["3.11"]
12 | runs-on: ubuntu-latest
13 |
14 | defaults:
15 | run:
16 | shell: bash
17 |
18 | steps:
19 | - uses: actions/checkout@v3
20 | with:
21 | fetch-depth: 1
22 |
23 | - name: Set up Python
24 | uses: actions/setup-python@v4
25 | with:
26 | python-version: ${{ matrix.python_version }}
27 | architecture: x64
28 |
29 | - name: Install Poetry
30 | uses: snok/install-poetry@v1
31 | with:
32 | virtualenvs-create: true
33 | virtualenvs-in-project: true
34 |
35 | - name: Install Dependencies
36 | run: poetry install
37 |
38 | - name: Run yapf
39 | run: poetry run yapf -r -d themida_unmutate
40 |
41 | - name: Run mypy
42 | run: poetry run mypy --strict themida_unmutate
43 |
--------------------------------------------------------------------------------
/.github/workflows/publish_pyinstaller.yml:
--------------------------------------------------------------------------------
1 | name: Publish PyInstaller distribution to Github Artifacts
2 |
3 | on: [push]
4 |
5 | jobs:
6 | check:
7 | name: Check PyInstaller for Python ${{ matrix.python_version }} (${{ matrix.architecture }})
8 | strategy:
9 | fail-fast: false
10 | matrix:
11 | python_version: ["3.11"]
12 | architecture: [x64, x86]
13 | runs-on: windows-latest
14 |
15 | steps:
16 | - uses: actions/checkout@v3
17 | with:
18 | fetch-depth: 1
19 |
20 | - name: Set up Python
21 | uses: actions/setup-python@v4
22 | with:
23 | python-version: ${{ matrix.python_version }}
24 | architecture: ${{ matrix.architecture }}
25 |
26 | - uses: TheMrMilchmann/setup-msvc-dev@v3
27 | with:
28 | arch: ${{ matrix.architecture }}
29 |
30 | - name: Install Poetry
31 | uses: SG60/setup-poetry@v1
32 |
33 | - name: Install Dependencies
34 | run: poetry install
35 |
36 | - name: Install PyInstaller
37 | run: poetry run pip install pyinstaller
38 |
39 | - name: Build PyInstaller package
40 | run: poetry run pyinstaller themida-unmutate.spec
41 |
42 | - name: "Upload PyInstaller Artifact"
43 | uses: actions/upload-artifact@v3
44 | with:
45 | name: themida-unmutate-py${{ matrix.python_version }}-${{ matrix.architecture }}
46 | path: dist/*.exe
47 | retention-days: 3
48 |
--------------------------------------------------------------------------------
/.github/workflows/publish_pypi.yml:
--------------------------------------------------------------------------------
1 | name: Publish Python distribution to PyPI
2 | on: push
3 |
4 | jobs:
5 | build:
6 | name: Build distribution
7 | runs-on: ubuntu-latest
8 | steps:
9 | - uses: actions/checkout@v4
10 |
11 | - name: Set up Python
12 | uses: actions/setup-python@v5
13 | with:
14 | python-version: "3.x"
15 |
16 | - name: Install pypa/build
17 | run: >-
18 | python3 -m
19 | pip install
20 | build
21 | --user
22 |
23 | - name: Build a binary wheel and a source tarball
24 | run: python3 -m build
25 |
26 | - name: Store the distribution packages
27 | uses: actions/upload-artifact@v3
28 | with:
29 | name: python-package-distributions
30 | path: dist/
31 |
32 | publish-to-pypi:
33 | name: >-
34 | Publish Python distribution to PyPI
35 | if: startsWith(github.ref, 'refs/tags/') # only publish to PyPI on tag pushes
36 | needs:
37 | - build
38 | runs-on: ubuntu-latest
39 | environment:
40 | name: pypi
41 | url: https://pypi.org/p/themida-unmutate
42 | permissions:
43 | id-token: write # IMPORTANT: mandatory for trusted publishing
44 | steps:
45 | - name: Download all the dists
46 | uses: actions/download-artifact@v3
47 | with:
48 | name: python-package-distributions
49 | path: dist/
50 |
51 | - name: Publish distribution to PyPI
52 | uses: pypa/gh-action-pypi-publish@release/v1
53 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | # *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/#use-with-ide
110 | .pdm.toml
111 |
112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113 | __pypackages__/
114 |
115 | # Celery stuff
116 | celerybeat-schedule
117 | celerybeat.pid
118 |
119 | # SageMath parsed files
120 | *.sage.py
121 |
122 | # Environments
123 | .env
124 | .venv
125 | env/
126 | venv/
127 | ENV/
128 | env.bak/
129 | venv.bak/
130 |
131 | # Spyder project settings
132 | .spyderproject
133 | .spyproject
134 |
135 | # Rope project settings
136 | .ropeproject
137 |
138 | # mkdocs documentation
139 | /site
140 |
141 | # mypy
142 | .mypy_cache/
143 | .dmypy.json
144 | dmypy.json
145 |
146 | # Pyre type checker
147 | .pyre/
148 |
149 | # pytype static type analyzer
150 | .pytype/
151 |
152 | # Cython debug symbols
153 | cython_debug/
154 |
155 | # PyCharm
156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158 | # and can be added to the global gitignore or merged into this file. For a more nuclear
159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160 | #.idea/
161 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## [Unreleased]
4 |
5 | ## [0.2.1] - 2024-07-29
6 |
7 | ### Changed
8 |
9 | - Bump lief to version 0.15.1
10 |
11 | ## [0.2.0] - 2024-07-28
12 |
13 | ### Added
14 |
15 | - Add support for x86_32 binaries
16 |
17 | ## [0.1.2] - 2024-07-16
18 |
19 | ### Fixed
20 |
21 | - Fix in-place reassembly failing to find the right destination interval in many cases
22 | - Fix broken code generation in certain cases when using in-place reassembly
23 | - Fix broken code generation for certain instructions because of bogus additional info
24 |
25 | ## [0.1.1] - 2024-07-10
26 |
27 | ### Fixed
28 |
29 | - Fix assert triggering when processing trampolines from Themida 3.1.7+
30 | - Fix PyInstaller Github action builds
31 |
32 | ## [0.1.0] - 2024-07-06
33 |
34 | Initial release with support for Themida/Winlicense 3.x.
35 | This release has been tested on Themida up to v3.1.9.0.
36 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # themida-unmutate
2 |
3 | [](https://github.com/ergrelet/themida-unmutate/releases) [](https://www.python.org/downloads/) 
4 |
5 | A Python 3 tool to statically deobfuscate functions protected by Themida,
6 | WinLicense and Code Virtualizer 3.x's mutation-based obfuscation.
7 | The tool has been **tested on Themida up to version 3.1.9**. It's expected to
8 | work on WinLicense and Code Virtualizer as well.
9 |
10 | A Binary Ninja plugin is also available [here](https://github.com/ergrelet/themida-unmutate-bn).
11 |
12 | ## Features
13 |
14 | - Automatically resolve trampolines' destination addresses
15 | - Statically deobfuscate mutated functions
16 | - Rebuild fully working binaries
17 |
18 | ## Known Limitations
19 |
20 | - Doesn't support ARM64 binaries
21 |
22 | ## How to Download
23 |
24 | You can install the project with `pip`:
25 |
26 | ```
27 | pip install themida-unmutate
28 | ```
29 |
30 | A standalone PyInstaller build is available for Windows in "Releases".
31 |
32 | ## How to Use
33 |
34 | Here's what the CLI looks like:
35 |
36 | ```
37 | $ themida-unmutate --help
38 | usage: themida-unmutate [-h] -a ADDRESSES [ADDRESSES ...] -o OUTPUT [--no-trampoline] [--reassemble-in-place] [-v] protected_binary
39 |
40 | Automatic deobfuscation tool for Themida's mutation-based protection
41 |
42 | positional arguments:
43 | protected_binary Protected binary path
44 |
45 | options:
46 | -h, --help show this help message and exit
47 | -a ADDRESSES [ADDRESSES ...], --addresses ADDRESSES [ADDRESSES ...]
48 | Addresses of the functions to deobfuscate
49 | -o OUTPUT, --output OUTPUT
50 | Output binary path
51 | --no-trampoline Disable function unwrapping
52 | --reassemble-in-place
53 | Rewrite simplified code over the mutated code rather than in a new code section
54 | -v, --verbose Enable verbose logging
55 | ```
56 |
--------------------------------------------------------------------------------
/docs/themida-mutation-recon24.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ergrelet/themida-unmutate/5c7a4294e1c9defe242f99df362b9af2908b8153/docs/themida-mutation-recon24.pdf
--------------------------------------------------------------------------------
/poetry.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Poetry 1.5.1 and should not be changed by hand.
2 |
3 | [[package]]
4 | name = "astroid"
5 | version = "3.2.4"
6 | description = "An abstract syntax tree for Python with inference support."
7 | optional = false
8 | python-versions = ">=3.8.0"
9 | files = [
10 | {file = "astroid-3.2.4-py3-none-any.whl", hash = "sha256:413658a61eeca6202a59231abb473f932038fbcbf1666587f66d482083413a25"},
11 | {file = "astroid-3.2.4.tar.gz", hash = "sha256:0e14202810b30da1b735827f78f5157be2bbd4a7a59b7707ca0bfc2fb4c0063a"},
12 | ]
13 |
14 | [[package]]
15 | name = "colorama"
16 | version = "0.4.6"
17 | description = "Cross-platform colored terminal text."
18 | optional = false
19 | python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
20 | files = [
21 | {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"},
22 | {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
23 | ]
24 |
25 | [[package]]
26 | name = "dill"
27 | version = "0.3.8"
28 | description = "serialize all of Python"
29 | optional = false
30 | python-versions = ">=3.8"
31 | files = [
32 | {file = "dill-0.3.8-py3-none-any.whl", hash = "sha256:c36ca9ffb54365bdd2f8eb3eff7d2a21237f8452b57ace88b1ac615b7e815bd7"},
33 | {file = "dill-0.3.8.tar.gz", hash = "sha256:3ebe3c479ad625c4553aca177444d89b486b1d84982eeacded644afc0cf797ca"},
34 | ]
35 |
36 | [package.extras]
37 | graph = ["objgraph (>=1.7.2)"]
38 | profile = ["gprof2dot (>=2022.7.29)"]
39 |
40 | [[package]]
41 | name = "future"
42 | version = "1.0.0"
43 | description = "Clean single-source support for Python 3 and 2"
44 | optional = false
45 | python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*"
46 | files = [
47 | {file = "future-1.0.0-py3-none-any.whl", hash = "sha256:929292d34f5872e70396626ef385ec22355a1fae8ad29e1a734c3e43f9fbc216"},
48 | {file = "future-1.0.0.tar.gz", hash = "sha256:bd2968309307861edae1458a4f8a4f3598c03be43b97521076aebf5d94c07b05"},
49 | ]
50 |
51 | [[package]]
52 | name = "importlib-metadata"
53 | version = "8.2.0"
54 | description = "Read metadata from Python packages"
55 | optional = false
56 | python-versions = ">=3.8"
57 | files = [
58 | {file = "importlib_metadata-8.2.0-py3-none-any.whl", hash = "sha256:11901fa0c2f97919b288679932bb64febaeacf289d18ac84dd68cb2e74213369"},
59 | {file = "importlib_metadata-8.2.0.tar.gz", hash = "sha256:72e8d4399996132204f9a16dcc751af254a48f8d1b20b9ff0f98d4a8f901e73d"},
60 | ]
61 |
62 | [package.dependencies]
63 | zipp = ">=0.5"
64 |
65 | [package.extras]
66 | doc = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-lint"]
67 | perf = ["ipython"]
68 | test = ["flufl.flake8", "importlib-resources (>=1.3)", "jaraco.test (>=5.4)", "packaging", "pyfakefs", "pytest (>=6,!=8.1.*)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-mypy", "pytest-perf (>=0.9.2)", "pytest-ruff (>=0.2.1)"]
69 |
70 | [[package]]
71 | name = "isort"
72 | version = "5.13.2"
73 | description = "A Python utility / library to sort Python imports."
74 | optional = false
75 | python-versions = ">=3.8.0"
76 | files = [
77 | {file = "isort-5.13.2-py3-none-any.whl", hash = "sha256:8ca5e72a8d85860d5a3fa69b8745237f2939afe12dbf656afbcb47fe72d947a6"},
78 | {file = "isort-5.13.2.tar.gz", hash = "sha256:48fdfcb9face5d58a4f6dde2e72a1fb8dcaf8ab26f95ab49fab84c2ddefb0109"},
79 | ]
80 |
81 | [package.extras]
82 | colors = ["colorama (>=0.4.6)"]
83 |
84 | [[package]]
85 | name = "lief"
86 | version = "0.15.1"
87 | description = "Library to instrument executable formats"
88 | optional = false
89 | python-versions = ">=3.8"
90 | files = [
91 | {file = "lief-0.15.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a80246b96501b2b1d4927ceb3cb817eda9333ffa9e07101358929a6cffca5dae"},
92 | {file = "lief-0.15.1-cp310-cp310-macosx_11_0_x86_64.whl", hash = "sha256:84bf310710369544e2bb82f83d7fdab5b5ac422651184fde8bf9e35f14439691"},
93 | {file = "lief-0.15.1-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:8fb58efb77358291109d2675d5459399c0794475b497992d0ecee18a4a46a207"},
94 | {file = "lief-0.15.1-cp310-cp310-manylinux_2_33_aarch64.whl", hash = "sha256:d5852a246361bbefa4c1d5930741765a2337638d65cfe30de1b7d61f9a54b865"},
95 | {file = "lief-0.15.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:12e53dc0253c303df386ae45487a2f0078026602b36d0e09e838ae1d4dbef958"},
96 | {file = "lief-0.15.1-cp310-cp310-win32.whl", hash = "sha256:38b9cee48f42c355359ad7e3ff18bf1ec95e518238e4e8fb25657a49169dbf4c"},
97 | {file = "lief-0.15.1-cp310-cp310-win_amd64.whl", hash = "sha256:ddf2ebd73766169594d631b35f84c49ef42871de552ad49f36002c60164d0aca"},
98 | {file = "lief-0.15.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:20508c52de0dffcee3242253541609590167a3e56150cbacb506fdbb822206ef"},
99 | {file = "lief-0.15.1-cp311-cp311-macosx_11_0_x86_64.whl", hash = "sha256:0750c892fd3b7161a3c2279f25fe1844427610c3a5a4ae23f65674ced6f93ea5"},
100 | {file = "lief-0.15.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:a8634ea79d6d9862297fadce025519ab25ff01fcadb333cf42967c6295f0d057"},
101 | {file = "lief-0.15.1-cp311-cp311-manylinux_2_33_aarch64.whl", hash = "sha256:1e11e046ad71fe8c81e1a8d1d207fe2b99c967d33ce79c3d3915cb8f5ecacf52"},
102 | {file = "lief-0.15.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:674b620cdf1d686f52450fd97c1056d4c92e55af8217ce85a1b2efaf5b32140b"},
103 | {file = "lief-0.15.1-cp311-cp311-win32.whl", hash = "sha256:dbdcd70fd23c90017705b7fe6c716f0a69c01d0d0ea7a2ff653d83dc4a61fefb"},
104 | {file = "lief-0.15.1-cp311-cp311-win_amd64.whl", hash = "sha256:e9b96a37bf11ca777ff305d85d957eabad2a92a6e577b6e2fb3ab79514e5a12e"},
105 | {file = "lief-0.15.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1a96f17c2085ef38d12ad81427ae8a5d6ad76f0bc62a1e1f5fe384255cd2cc94"},
106 | {file = "lief-0.15.1-cp312-cp312-macosx_11_0_x86_64.whl", hash = "sha256:d780af1762022b8e01b613253af490afea3864fbd6b5a49c6de7cea8fde0443d"},
107 | {file = "lief-0.15.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:d0f10d80202de9634a16786b53ba3a8f54ae8b9a9e124a964d83212444486087"},
108 | {file = "lief-0.15.1-cp312-cp312-manylinux_2_33_aarch64.whl", hash = "sha256:864f17ecf1736296e6d5fc38b11983f9d19a5e799f094e21e20d58bfb1b95b80"},
109 | {file = "lief-0.15.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c2ec738bcafee8a569741f4a749f0596823b12f10713306c7d0cbbf85759f51c"},
110 | {file = "lief-0.15.1-cp312-cp312-win32.whl", hash = "sha256:db38619edf70e27fb3686b8c0f0bec63ad494ac88ab51660c5ecd2720b506e41"},
111 | {file = "lief-0.15.1-cp312-cp312-win_amd64.whl", hash = "sha256:28bf0922de5fb74502a29cc47930d3a052df58dc23ab6519fa590e564f194a60"},
112 | {file = "lief-0.15.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:0616e6048f269d262ff93d67c497ebff3c1d3965ffb9427b0f2b474764fd2e8c"},
113 | {file = "lief-0.15.1-cp313-cp313-manylinux_2_33_aarch64.whl", hash = "sha256:6a08b2e512a80040429febddc777768c949bcd53f6f580e902e41ec0d9d936b8"},
114 | {file = "lief-0.15.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:fcd489ff80860bcc2b2689faa330a46b6d66f0ee3e0f6ef9e643e2b996128a06"},
115 | {file = "lief-0.15.1-cp313-cp313-win32.whl", hash = "sha256:0d10e5b22e86bbf2d1e3877b604ffd8860c852b6bc00fca681fe1432f5018fe9"},
116 | {file = "lief-0.15.1-cp313-cp313-win_amd64.whl", hash = "sha256:5af7dcb9c3f44baaf60875df6ba9af6777db94776cc577ee86143bcce105ba2f"},
117 | {file = "lief-0.15.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:f9757ff0c7c3d6f66e5fdcc6a9df69680fad0dc2707d64a3428f0825dfce1a85"},
118 | {file = "lief-0.15.1-cp38-cp38-macosx_11_0_x86_64.whl", hash = "sha256:8ac3cd099be2580d0e15150b1d2f5095c38f150af89993ddf390d7897ee8135f"},
119 | {file = "lief-0.15.1-cp38-cp38-manylinux_2_28_x86_64.whl", hash = "sha256:4dedeab498c312a29b58f16b739895f65fa54b2a21b8d98b111e99ad3f7e30a8"},
120 | {file = "lief-0.15.1-cp38-cp38-manylinux_2_33_aarch64.whl", hash = "sha256:b9217578f7a45f667503b271da8481207fb4edda8d4a53e869fb922df6030484"},
121 | {file = "lief-0.15.1-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:82e6308ad8bd4bc7eadee3502ede13a5bb398725f25513a0396c8dba850f58a1"},
122 | {file = "lief-0.15.1-cp38-cp38-win32.whl", hash = "sha256:dde1c8f8ebe0ee9db4f2302c87ae3cacb9898dc412e0d7da07a8e4e834ac5158"},
123 | {file = "lief-0.15.1-cp38-cp38-win_amd64.whl", hash = "sha256:a079a76bca23aa73c850ab5beb7598871a1bf44662658b952cead2b5ddd31bee"},
124 | {file = "lief-0.15.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:785a3aa14575f046ed9c8d44ea222ea14c697cd03b5331d1717b5b0cf4f72466"},
125 | {file = "lief-0.15.1-cp39-cp39-macosx_11_0_x86_64.whl", hash = "sha256:d7044553cf07c8a2ab6e21874f07585610d996ff911b9af71dc6085a89f59daa"},
126 | {file = "lief-0.15.1-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:13285c3ff5ef6de2421d85684c954905af909db0ad3472e33c475e5f0f657dcf"},
127 | {file = "lief-0.15.1-cp39-cp39-manylinux_2_33_aarch64.whl", hash = "sha256:932f880ee8a130d663a97a9099516d8570b1b303af7816e70a02f9931d5ef4c2"},
128 | {file = "lief-0.15.1-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:de9453f94866e0f2c36b6bd878625880080e7e5800788f5cbc06a76debf283b9"},
129 | {file = "lief-0.15.1-cp39-cp39-win32.whl", hash = "sha256:4e47324736d6aa559421720758de4ce12d04fb56bdffa3dcc051fe8cdd42ed17"},
130 | {file = "lief-0.15.1-cp39-cp39-win_amd64.whl", hash = "sha256:382a189514c0e6ebfb41e0db6106936c7ba94d8400651276add2899ff3570585"},
131 | ]
132 |
133 | [[package]]
134 | name = "mccabe"
135 | version = "0.7.0"
136 | description = "McCabe checker, plugin for flake8"
137 | optional = false
138 | python-versions = ">=3.6"
139 | files = [
140 | {file = "mccabe-0.7.0-py2.py3-none-any.whl", hash = "sha256:6c2d30ab6be0e4a46919781807b4f0d834ebdd6c6e3dca0bda5a15f863427b6e"},
141 | {file = "mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325"},
142 | ]
143 |
144 | [[package]]
145 | name = "miasm"
146 | version = "0.1.5"
147 | description = "Machine code manipulation library"
148 | optional = false
149 | python-versions = "*"
150 | files = [
151 | {file = "miasm-0.1.5.tar.gz", hash = "sha256:e90d5886cdff7601747e8c6ae0e874356436d848e5be2a44642de9d29762dc75"},
152 | ]
153 |
154 | [package.dependencies]
155 | future = "*"
156 | pyparsing = ">=2.0,<3.0"
157 |
158 | [[package]]
159 | name = "mypy"
160 | version = "1.11.0"
161 | description = "Optional static typing for Python"
162 | optional = false
163 | python-versions = ">=3.8"
164 | files = [
165 | {file = "mypy-1.11.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:a3824187c99b893f90c845bab405a585d1ced4ff55421fdf5c84cb7710995229"},
166 | {file = "mypy-1.11.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:96f8dbc2c85046c81bcddc246232d500ad729cb720da4e20fce3b542cab91287"},
167 | {file = "mypy-1.11.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1a5d8d8dd8613a3e2be3eae829ee891b6b2de6302f24766ff06cb2875f5be9c6"},
168 | {file = "mypy-1.11.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:72596a79bbfb195fd41405cffa18210af3811beb91ff946dbcb7368240eed6be"},
169 | {file = "mypy-1.11.0-cp310-cp310-win_amd64.whl", hash = "sha256:35ce88b8ed3a759634cb4eb646d002c4cef0a38f20565ee82b5023558eb90c00"},
170 | {file = "mypy-1.11.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:98790025861cb2c3db8c2f5ad10fc8c336ed2a55f4daf1b8b3f877826b6ff2eb"},
171 | {file = "mypy-1.11.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:25bcfa75b9b5a5f8d67147a54ea97ed63a653995a82798221cca2a315c0238c1"},
172 | {file = "mypy-1.11.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0bea2a0e71c2a375c9fa0ede3d98324214d67b3cbbfcbd55ac8f750f85a414e3"},
173 | {file = "mypy-1.11.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:d2b3d36baac48e40e3064d2901f2fbd2a2d6880ec6ce6358825c85031d7c0d4d"},
174 | {file = "mypy-1.11.0-cp311-cp311-win_amd64.whl", hash = "sha256:d8e2e43977f0e09f149ea69fd0556623919f816764e26d74da0c8a7b48f3e18a"},
175 | {file = "mypy-1.11.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:1d44c1e44a8be986b54b09f15f2c1a66368eb43861b4e82573026e04c48a9e20"},
176 | {file = "mypy-1.11.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:cea3d0fb69637944dd321f41bc896e11d0fb0b0aa531d887a6da70f6e7473aba"},
177 | {file = "mypy-1.11.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a83ec98ae12d51c252be61521aa5731f5512231d0b738b4cb2498344f0b840cd"},
178 | {file = "mypy-1.11.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:c7b73a856522417beb78e0fb6d33ef89474e7a622db2653bc1285af36e2e3e3d"},
179 | {file = "mypy-1.11.0-cp312-cp312-win_amd64.whl", hash = "sha256:f2268d9fcd9686b61ab64f077be7ffbc6fbcdfb4103e5dd0cc5eaab53a8886c2"},
180 | {file = "mypy-1.11.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:940bfff7283c267ae6522ef926a7887305945f716a7704d3344d6d07f02df850"},
181 | {file = "mypy-1.11.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:14f9294528b5f5cf96c721f231c9f5b2733164e02c1c018ed1a0eff8a18005ac"},
182 | {file = "mypy-1.11.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d7b54c27783991399046837df5c7c9d325d921394757d09dbcbf96aee4649fe9"},
183 | {file = "mypy-1.11.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:65f190a6349dec29c8d1a1cd4aa71284177aee5949e0502e6379b42873eddbe7"},
184 | {file = "mypy-1.11.0-cp38-cp38-win_amd64.whl", hash = "sha256:dbe286303241fea8c2ea5466f6e0e6a046a135a7e7609167b07fd4e7baf151bf"},
185 | {file = "mypy-1.11.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:104e9c1620c2675420abd1f6c44bab7dd33cc85aea751c985006e83dcd001095"},
186 | {file = "mypy-1.11.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f006e955718ecd8d159cee9932b64fba8f86ee6f7728ca3ac66c3a54b0062abe"},
187 | {file = "mypy-1.11.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:becc9111ca572b04e7e77131bc708480cc88a911adf3d0239f974c034b78085c"},
188 | {file = "mypy-1.11.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:6801319fe76c3f3a3833f2b5af7bd2c17bb93c00026a2a1b924e6762f5b19e13"},
189 | {file = "mypy-1.11.0-cp39-cp39-win_amd64.whl", hash = "sha256:c1a184c64521dc549324ec6ef7cbaa6b351912be9cb5edb803c2808a0d7e85ac"},
190 | {file = "mypy-1.11.0-py3-none-any.whl", hash = "sha256:56913ec8c7638b0091ef4da6fcc9136896914a9d60d54670a75880c3e5b99ace"},
191 | {file = "mypy-1.11.0.tar.gz", hash = "sha256:93743608c7348772fdc717af4aeee1997293a1ad04bc0ea6efa15bf65385c538"},
192 | ]
193 |
194 | [package.dependencies]
195 | mypy-extensions = ">=1.0.0"
196 | typing-extensions = ">=4.6.0"
197 |
198 | [package.extras]
199 | dmypy = ["psutil (>=4.0)"]
200 | install-types = ["pip"]
201 | mypyc = ["setuptools (>=50)"]
202 | reports = ["lxml"]
203 |
204 | [[package]]
205 | name = "mypy-extensions"
206 | version = "1.0.0"
207 | description = "Type system extensions for programs checked with the mypy type checker."
208 | optional = false
209 | python-versions = ">=3.5"
210 | files = [
211 | {file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"},
212 | {file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"},
213 | ]
214 |
215 | [[package]]
216 | name = "platformdirs"
217 | version = "4.2.2"
218 | description = "A small Python package for determining appropriate platform-specific dirs, e.g. a `user data dir`."
219 | optional = false
220 | python-versions = ">=3.8"
221 | files = [
222 | {file = "platformdirs-4.2.2-py3-none-any.whl", hash = "sha256:2d7a1657e36a80ea911db832a8a6ece5ee53d8de21edd5cc5879af6530b1bfee"},
223 | {file = "platformdirs-4.2.2.tar.gz", hash = "sha256:38b7b51f512eed9e84a22788b4bce1de17c0adb134d6becb09836e37d8654cd3"},
224 | ]
225 |
226 | [package.extras]
227 | docs = ["furo (>=2023.9.10)", "proselint (>=0.13)", "sphinx (>=7.2.6)", "sphinx-autodoc-typehints (>=1.25.2)"]
228 | test = ["appdirs (==1.4.4)", "covdefaults (>=2.3)", "pytest (>=7.4.3)", "pytest-cov (>=4.1)", "pytest-mock (>=3.12)"]
229 | type = ["mypy (>=1.8)"]
230 |
231 | [[package]]
232 | name = "pylint"
233 | version = "3.2.6"
234 | description = "python code static checker"
235 | optional = false
236 | python-versions = ">=3.8.0"
237 | files = [
238 | {file = "pylint-3.2.6-py3-none-any.whl", hash = "sha256:03c8e3baa1d9fb995b12c1dbe00aa6c4bcef210c2a2634374aedeb22fb4a8f8f"},
239 | {file = "pylint-3.2.6.tar.gz", hash = "sha256:a5d01678349454806cff6d886fb072294f56a58c4761278c97fb557d708e1eb3"},
240 | ]
241 |
242 | [package.dependencies]
243 | astroid = ">=3.2.4,<=3.3.0-dev0"
244 | colorama = {version = ">=0.4.5", markers = "sys_platform == \"win32\""}
245 | dill = [
246 | {version = ">=0.3.6", markers = "python_version >= \"3.11\""},
247 | {version = ">=0.3.7", markers = "python_version >= \"3.12\""},
248 | ]
249 | isort = ">=4.2.5,<5.13.0 || >5.13.0,<6"
250 | mccabe = ">=0.6,<0.8"
251 | platformdirs = ">=2.2.0"
252 | tomlkit = ">=0.10.1"
253 |
254 | [package.extras]
255 | spelling = ["pyenchant (>=3.2,<4.0)"]
256 | testutils = ["gitpython (>3)"]
257 |
258 | [[package]]
259 | name = "pyparsing"
260 | version = "2.4.7"
261 | description = "Python parsing module"
262 | optional = false
263 | python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*"
264 | files = [
265 | {file = "pyparsing-2.4.7-py2.py3-none-any.whl", hash = "sha256:ef9d7589ef3c200abe66653d3f1ab1033c3c419ae9b9bdb1240a85b024efc88b"},
266 | {file = "pyparsing-2.4.7.tar.gz", hash = "sha256:c203ec8783bf771a155b207279b9bccb8dea02d8f0c9e5f8ead507bc3246ecc1"},
267 | ]
268 |
269 | [[package]]
270 | name = "tomli"
271 | version = "2.0.1"
272 | description = "A lil' TOML parser"
273 | optional = false
274 | python-versions = ">=3.7"
275 | files = [
276 | {file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"},
277 | {file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"},
278 | ]
279 |
280 | [[package]]
281 | name = "tomlkit"
282 | version = "0.13.0"
283 | description = "Style preserving TOML library"
284 | optional = false
285 | python-versions = ">=3.8"
286 | files = [
287 | {file = "tomlkit-0.13.0-py3-none-any.whl", hash = "sha256:7075d3042d03b80f603482d69bf0c8f345c2b30e41699fd8883227f89972b264"},
288 | {file = "tomlkit-0.13.0.tar.gz", hash = "sha256:08ad192699734149f5b97b45f1f18dad7eb1b6d16bc72ad0c2335772650d7b72"},
289 | ]
290 |
291 | [[package]]
292 | name = "typing-extensions"
293 | version = "4.12.2"
294 | description = "Backported and Experimental Type Hints for Python 3.8+"
295 | optional = false
296 | python-versions = ">=3.8"
297 | files = [
298 | {file = "typing_extensions-4.12.2-py3-none-any.whl", hash = "sha256:04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d"},
299 | {file = "typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8"},
300 | ]
301 |
302 | [[package]]
303 | name = "yapf"
304 | version = "0.40.2"
305 | description = "A formatter for Python code"
306 | optional = false
307 | python-versions = ">=3.7"
308 | files = [
309 | {file = "yapf-0.40.2-py3-none-any.whl", hash = "sha256:adc8b5dd02c0143108878c499284205adb258aad6db6634e5b869e7ee2bd548b"},
310 | {file = "yapf-0.40.2.tar.gz", hash = "sha256:4dab8a5ed7134e26d57c1647c7483afb3f136878b579062b786c9ba16b94637b"},
311 | ]
312 |
313 | [package.dependencies]
314 | importlib-metadata = ">=6.6.0"
315 | platformdirs = ">=3.5.1"
316 | tomli = ">=2.0.1"
317 |
318 | [[package]]
319 | name = "zipp"
320 | version = "3.19.2"
321 | description = "Backport of pathlib-compatible object wrapper for zip files"
322 | optional = false
323 | python-versions = ">=3.8"
324 | files = [
325 | {file = "zipp-3.19.2-py3-none-any.whl", hash = "sha256:f091755f667055f2d02b32c53771a7a6c8b47e1fdbc4b72a8b9072b3eef8015c"},
326 | {file = "zipp-3.19.2.tar.gz", hash = "sha256:bf1dcf6450f873a13e952a29504887c89e6de7506209e5b1bcc3460135d4de19"},
327 | ]
328 |
329 | [package.extras]
330 | doc = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-lint"]
331 | test = ["big-O", "importlib-resources", "jaraco.functools", "jaraco.itertools", "jaraco.test", "more-itertools", "pytest (>=6,!=8.1.*)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-ignore-flaky", "pytest-mypy", "pytest-ruff (>=0.2.1)"]
332 |
333 | [metadata]
334 | lock-version = "2.0"
335 | python-versions = "^3.11"
336 | content-hash = "e9c61dc8a97fd882fbed2314d3ff067a7dfae60d855e88608179065636a88dde"
337 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.poetry]
2 | name = "themida-unmutate"
3 | version = "0.2.1"
4 | description = "Static deobfuscator for Themida's mutation-based obfuscation."
5 | authors = ["ergrelet "]
6 | license = "GPL-3.0-or-later"
7 | readme = "README.md"
8 | packages = [{include = "themida_unmutate"}]
9 |
10 | [tool.poetry.dependencies]
11 | python = "^3.11"
12 | lief = "^0.15.1"
13 | miasm = "^0.1.5"
14 |
15 |
16 | [tool.poetry.group.dev.dependencies]
17 | yapf = "^0.40.2"
18 | mypy = "^1.8.0"
19 | pylint = "^3.0.3"
20 |
21 | [tool.poetry.scripts]
22 | themida-unmutate = 'themida_unmutate.main:entry_point'
23 |
24 | [tool.yapf]
25 | column_limit = 120
26 |
27 | [tool.mypy]
28 | python_version = "3.11"
29 | warn_return_any = true
30 | warn_unused_configs = true
31 | no_implicit_optional = true
32 | ignore_missing_imports = true
33 |
34 | [tool.pylint.'MESSAGES CONTROL']
35 | max-line-length = 120
36 | disable = "C0114, C0115, C0116, I1101"
37 |
38 | [tool.pylint.TYPECHECK]
39 | ignored-classes = "lief"
40 |
41 | [build-system]
42 | requires = ["poetry-core"]
43 | build-backend = "poetry.core.masonry.api"
44 |
--------------------------------------------------------------------------------
/themida-unmutate.spec:
--------------------------------------------------------------------------------
1 | # -*- mode: python ; coding: utf-8 -*-
2 |
3 | from PyInstaller.utils.hooks import collect_data_files
4 |
5 | resource_files = [
6 | ('themida_unmutate/', 'themida_unmutate'),
7 | *collect_data_files("miasm", include_py_files=True),
8 | ]
9 | block_cipher = None
10 |
11 | a = Analysis(['themida_unmutate/__main__.py'],
12 | pathex=[],
13 | binaries=[],
14 | datas=resource_files,
15 | hiddenimports=[],
16 | hookspath=[],
17 | hooksconfig={},
18 | runtime_hooks=[],
19 | excludes=[],
20 | win_no_prefer_redirects=False,
21 | win_private_assemblies=False,
22 | cipher=block_cipher,
23 | noarchive=False)
24 | pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
25 |
26 | exe = EXE(pyz,
27 | a.scripts,
28 | a.binaries,
29 | a.zipfiles,
30 | a.datas, [],
31 | name='themida-unmutate',
32 | debug=False,
33 | bootloader_ignore_signals=False,
34 | strip=False,
35 | upx=False,
36 | upx_exclude=[],
37 | runtime_tmpdir=None,
38 | console=True,
39 | disable_windowed_traceback=False,
40 | target_arch=None,
41 | codesign_identity=None,
42 | entitlements_file=None)
--------------------------------------------------------------------------------
/themida_unmutate/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ergrelet/themida-unmutate/5c7a4294e1c9defe242f99df362b9af2908b8153/themida_unmutate/__init__.py
--------------------------------------------------------------------------------
/themida_unmutate/__main__.py:
--------------------------------------------------------------------------------
1 | from themida_unmutate.main import entry_point
2 |
3 | if __name__ == "__main__":
4 | entry_point()
5 |
--------------------------------------------------------------------------------
/themida_unmutate/logging.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | import lief
4 |
5 | logger = logging.getLogger(__file__)
6 |
7 |
8 | def setup_logger(verbose: bool) -> None:
9 | # Disable logging from `lief`
10 | lief.logging.disable()
11 |
12 | if verbose:
13 | log_level = logging.DEBUG
14 | else:
15 | log_level = logging.INFO
16 | logger.setLevel(log_level)
17 |
18 | # Create a console handler with a higher log level
19 | stream_handler = logging.StreamHandler()
20 | stream_handler.setLevel(log_level)
21 | stream_handler.setFormatter(CustomFormatter())
22 |
23 | logger.addHandler(stream_handler)
24 |
25 |
26 | class CustomFormatter(logging.Formatter):
27 |
28 | grey = "\x1b[38;20m"
29 | green = "\x1b[1;32m"
30 | yellow = "\x1b[33;20m"
31 | red = "\x1b[31;20m"
32 | bold_red = "\x1b[31;1m"
33 | reset = "\x1b[0m"
34 | format_problem_str = "%(levelname)s - %(message)s"
35 |
36 | FORMATS = {
37 | logging.DEBUG: grey + "%(levelname)s - %(message)s" + reset,
38 | logging.INFO: green + "%(levelname)s" + reset + " - %(message)s",
39 | logging.WARNING: yellow + format_problem_str + reset,
40 | logging.ERROR: red + format_problem_str + reset,
41 | logging.CRITICAL: bold_red + format_problem_str + reset
42 | }
43 |
44 | def format(self, record: logging.LogRecord) -> str:
45 | log_fmt = self.FORMATS.get(record.levelno)
46 | formatter = logging.Formatter(log_fmt)
47 | return formatter.format(record)
48 |
--------------------------------------------------------------------------------
/themida_unmutate/main.py:
--------------------------------------------------------------------------------
1 | from argparse import ArgumentParser, Namespace
2 |
3 | from themida_unmutate.logging import setup_logger, logger
4 | from themida_unmutate.miasm_utils import MiasmContext
5 | from themida_unmutate.rebuilding import rebuild_simplified_binary
6 | from themida_unmutate.symbolic_execution import disassemble_and_simplify_functions
7 | from themida_unmutate.unwrapping import unwrap_functions
8 |
9 |
10 | def entry_point() -> None:
11 | # Parse command-line arguments
12 | args = parse_arguments()
13 |
14 | # Setup logging
15 | setup_logger(args.verbose)
16 |
17 | # Setup disassembler and lifter
18 | miasm_ctx = MiasmContext.from_binary_file(args.protected_binary)
19 |
20 | # Resolve mutated functions' addresses if needed
21 | protected_func_addrs = list(map(lambda addr: int(addr, 0), args.addresses))
22 | if not args.no_trampoline:
23 | logger.info("Resolving mutated's functions' addresses...")
24 | mutated_func_addrs = unwrap_functions(miasm_ctx, protected_func_addrs)
25 | else:
26 | # No trampolines to take care of, use target addresses directly
27 | mutated_func_addrs = protected_func_addrs
28 |
29 | # Disassemble mutated functions and simplify them
30 | logger.info("Deobfuscating mutated functions...")
31 | simplified_func_asmcfgs = disassemble_and_simplify_functions(miasm_ctx, mutated_func_addrs)
32 |
33 | # Map protected functions' addresses to their corresponding simplified `AsmCFG`
34 | func_addr_to_simplified_cfg = {
35 | protected_func_addrs[i]: asm_cfg
36 | for i, asm_cfg in enumerate(simplified_func_asmcfgs)
37 | }
38 |
39 | # Rewrite the protected binary with simplified functions
40 | logger.info("Rebuilding binary file...")
41 | rebuild_simplified_binary(miasm_ctx, func_addr_to_simplified_cfg, args.protected_binary, args.output,
42 | args.reassemble_in_place)
43 |
44 | logger.info("Done! You can find your deobfuscated binary at '%s'" % args.output)
45 |
46 |
47 | def parse_arguments() -> Namespace:
48 | """
49 | Parse command-line arguments.
50 | """
51 | parser = ArgumentParser(description="Automatic deobfuscation tool for Themida's mutation-based protection")
52 | parser.add_argument("protected_binary", help="Protected binary path")
53 | parser.add_argument("-a", "--addresses", nargs='+', help="Addresses of the functions to deobfuscate", required=True)
54 | parser.add_argument("-o", "--output", help="Output binary path", required=True)
55 | parser.add_argument("--no-trampoline", action='store_true', help="Disable function unwrapping")
56 | parser.add_argument("--reassemble-in-place",
57 | action='store_true',
58 | help="Rewrite simplified code over the mutated code "
59 | "rather than in a new code section")
60 | parser.add_argument("-v", "--verbose", action='store_true', help="Enable verbose logging")
61 |
62 | return parser.parse_args()
63 |
64 |
65 | if __name__ == "__main__":
66 | entry_point()
67 |
--------------------------------------------------------------------------------
/themida_unmutate/miasm_utils.py:
--------------------------------------------------------------------------------
1 | from dataclasses import dataclass
2 | from typing import Optional, Self
3 |
4 | import miasm.expression.expression as m2_expr
5 | import miasm.core.asmblock as m2_asmblock
6 | from miasm.analysis.binary import Container
7 | from miasm.analysis.machine import Machine
8 | from miasm.core import parse_asm
9 | from miasm.core.asmblock import disasmEngine, AsmCFG, asm_resolve_final
10 | from miasm.core.cpu import cls_mn
11 | from miasm.core.interval import interval
12 | from miasm.core.locationdb import LocationDB
13 | from miasm.ir.ir import Lifter
14 |
15 | MiasmFunctionInterval = interval
16 |
17 |
18 | @dataclass
19 | class MiasmContext:
20 | loc_db: LocationDB
21 | container: Container
22 | machine: Machine
23 | mdis: disasmEngine
24 | lifter: Lifter
25 |
26 | @classmethod
27 | def from_binary_file(cls, target_binary_path: str) -> Self:
28 | """
29 | Initialize our Miasm context from a binary file.
30 | """
31 | loc_db = LocationDB()
32 | with open(target_binary_path, 'rb') as target_binary:
33 | container = Container.from_stream(target_binary, loc_db)
34 | machine = Machine(container.arch)
35 | assert machine.dis_engine is not None
36 |
37 | mdis = machine.dis_engine(container.bin_stream, loc_db=loc_db)
38 | lifter = machine.lifter(loc_db)
39 |
40 | return cls(loc_db, container, machine, mdis, lifter)
41 |
42 | @property
43 | def arch(self) -> str:
44 | return str(self.machine.name)
45 |
46 |
47 | def expr_int_to_int(expr: m2_expr.ExprInt) -> int:
48 | int_size = expr.size
49 | is_signed = expr.arg >= 2**(int_size - 1)
50 | if is_signed:
51 | result = -(2**int_size - expr.arg)
52 | else:
53 | result = expr.arg
54 |
55 | return int(result)
56 |
57 |
58 | def generate_code_redirect_patch(miasm_ctx: MiasmContext, src_addr: int, dst_addr: int) -> tuple[int, bytes]:
59 | """
60 | Generate a single-block AsmCFG with a JMP from `src_addr` to `dst_addr` and return the result patch.
61 | """
62 | X86_JMP_INSTRUCTION = "JMP"
63 |
64 | # Generate a single-block AsmCFG with a JMP to the simplified version
65 | original_loc_str = f"loc_{src_addr:x}"
66 | jmp_unmut_instr_str = f"{original_loc_str}:\n{X86_JMP_INSTRUCTION} 0x{dst_addr:x}"
67 | jmp_unmut_asmcfg = parse_asm.parse_txt(miasm_ctx.mdis.arch, miasm_ctx.mdis.attrib, jmp_unmut_instr_str,
68 | miasm_ctx.mdis.loc_db)
69 |
70 | # Unpin loc_key if it's pinned
71 | original_loc = miasm_ctx.loc_db.get_offset_location(src_addr)
72 | if original_loc is not None:
73 | miasm_ctx.loc_db.unset_location_offset(original_loc)
74 |
75 | # Relocate the newly created block and generate machine code
76 | original_loc = miasm_ctx.loc_db.get_name_location(original_loc_str)
77 | miasm_ctx.loc_db.set_location_offset(original_loc, src_addr)
78 | jmp_patches = asm_resolve_final(miasm_ctx.mdis.arch, jmp_unmut_asmcfg)
79 | jmp_patch: Optional[tuple[int, bytes]] = next(iter(jmp_patches.items()), None)
80 | assert jmp_patch is not None
81 |
82 | return jmp_patch
83 |
84 |
85 | # Custom version of miasm's `asm_resolve_final` which works better for our
86 | # in-place rewriting use case
87 | def asm_resolve_final_in_place(loc_db: LocationDB,
88 | mnemo: cls_mn,
89 | asmcfg: AsmCFG,
90 | dst_interval: Optional[interval] = None) -> dict[int, bytes]:
91 | """Resolve and assemble @asmcfg into interval
92 | @dst_interval"""
93 |
94 | asmcfg.sanity_check()
95 |
96 | merge_cnext_constraints(asmcfg)
97 | guess_blocks_size(loc_db, asmcfg, dst_interval)
98 | freeze_original_instructions(asmcfg)
99 | blockChains = m2_asmblock.group_constrained_blocks(asmcfg)
100 | resolved_blockChains = m2_asmblock.resolve_symbol(blockChains, asmcfg.loc_db, dst_interval)
101 | m2_asmblock.asmblock_final(mnemo, asmcfg, resolved_blockChains, True)
102 | patches = {}
103 | output_interval = interval()
104 |
105 | for block in asmcfg.blocks:
106 | offset = asmcfg.loc_db.get_location_offset(block.loc_key)
107 | for instr in block.lines:
108 | if not instr.data:
109 | # Empty line
110 | continue
111 | assert len(instr.data) == instr.l
112 | patches[offset] = instr.data
113 | instruction_interval = interval([(offset, offset + instr.l - 1)])
114 | if not (instruction_interval & output_interval).empty:
115 | raise RuntimeError("overlapping bytes %X" % int(offset))
116 | output_interval = output_interval.union(instruction_interval)
117 | instr.offset = offset
118 | offset += instr.l
119 | return patches
120 |
121 |
122 | # This is a custom version of miasm's `guess_blocks_size` which simply reuse
123 | # data from the original CFG's interval to compute true basic block sizes so
124 | # that it properly fits inside of the destination interval
125 | def guess_blocks_size(loc_db: LocationDB, asmcfg: AsmCFG, interval: interval) -> None:
126 | for block in asmcfg.blocks:
127 | # Compute block sizes from interval
128 | for start_addr, end_addr in interval.intervals:
129 | block_start_addr = loc_db.get_location_offset(block.loc_key)
130 | if start_addr <= block_start_addr <= end_addr:
131 | block.size = end_addr - block_start_addr
132 | block.max_size = block.size
133 |
134 | # Setup instructions for reassembly
135 | for instr in block.lines:
136 | if instr.b is None:
137 | # This is an instruction we synthesized, init with empty data
138 | instr.b = b""
139 | instr.l = 0
140 |
141 |
142 | # Utility that we use to remove "c_next" constraints from AsmCFGs. This is
143 | # needed because of the way Miasm treats pinned basic blocks when reassembling
144 | # code.
145 | def merge_cnext_constraints(asmcfg: AsmCFG) -> None:
146 | for block in asmcfg.blocks:
147 | cst_next = block.get_next()
148 | if cst_next is not None:
149 | next_block: m2_asmblock.AsmBlock = asmcfg.loc_key_to_block(cst_next)
150 | # Block pointed to by "c_next" constraints should only contain a single
151 | # JMP instruction
152 | assert (len(next_block.lines) == 1)
153 | assert (len(next_block.bto) == 1)
154 |
155 | # Replace "c_next" constraint with a "c_to" constraints taken from the
156 | # next instruction
157 | block.bto = set(filter(lambda cst: cst.c_t != m2_asmblock.AsmConstraint.c_next, block.bto))
158 | c_to = m2_asmblock.AsmConstraint(next(iter(next_block.bto)).loc_key)
159 | block.addto(c_to)
160 | # Update edges
161 | asmcfg.rebuild_edges()
162 |
163 |
164 | # Very dirty utility to prevent Miasm from reassembling instructions that
165 | # we didn't synthesize or relocate. This avoids the case where Miasm tries to
166 | # reassemble an instruction and generates a longer machine instruction than the
167 | # original one. This can lead to issues where the code we generate is too big
168 | # to fit into the original basic blocks and thus in-place rewriting fails.
169 | def freeze_original_instructions(asmcfg: AsmCFG) -> None:
170 | for bb in asmcfg.blocks:
171 | for i, instr in enumerate(bb.lines):
172 | # Check if the instruction as so machine code already associated
173 | # to it. Also avoid freezing JMP/JCC instructions.
174 | if instr.l > 0 and not str(instr).startswith("J"):
175 | # Generate an `AsmRaw` instruction that Miasm will keep as is
176 | bb.lines[i] = m2_asmblock.AsmRaw(instr.b)
177 | bb.lines[i].l = instr.l
178 | bb.lines[i].data = instr.b
179 |
--------------------------------------------------------------------------------
/themida_unmutate/rebuilding.py:
--------------------------------------------------------------------------------
1 | from typing import Optional
2 |
3 | import lief
4 | from miasm.core.asmblock import AsmCFG, asm_resolve_final, bbl_simplifier
5 | from miasm.core.interval import interval
6 |
7 | from themida_unmutate.miasm_utils import (MiasmContext, MiasmFunctionInterval, generate_code_redirect_patch,
8 | asm_resolve_final_in_place)
9 |
10 | NEW_SECTION_NAME = ".unmut"
11 | NEW_SECTION_MAX_SIZE = 2**16
12 |
13 |
14 | def rebuild_simplified_binary(
15 | miasm_ctx: MiasmContext,
16 | func_addr_to_simplified_cfg: dict[int, tuple[int, AsmCFG, MiasmFunctionInterval]],
17 | input_binary_path: str,
18 | output_binary_path: str,
19 | reassemble_in_place: bool,
20 | ) -> None:
21 | """
22 | Reassemble functions' `AsmCFG` and rewrite the input binary with simplified
23 | machine code.
24 | """
25 | if len(func_addr_to_simplified_cfg) == 0:
26 | raise ValueError("`protected_function_addrs` cannot be empty")
27 |
28 | if reassemble_in_place:
29 | __rebuild_simplified_binary_in_place(miasm_ctx, func_addr_to_simplified_cfg, input_binary_path,
30 | output_binary_path)
31 | else:
32 | __rebuild_simplified_binary_in_new_section(miasm_ctx, func_addr_to_simplified_cfg, input_binary_path,
33 | output_binary_path)
34 |
35 |
36 | def __rebuild_simplified_binary_in_new_section(
37 | miasm_ctx: MiasmContext,
38 | func_addr_to_simplified_cfg: dict[int, tuple[int, AsmCFG, MiasmFunctionInterval]],
39 | input_binary_path: str,
40 | output_binary_path: str,
41 | ) -> None:
42 | """
43 | Reassemble functions' `AsmCFG` and rewrite the input binary with simplified
44 | machine code in a new code section.
45 | """
46 | # Open the target binary with LIEF
47 | pe_obj = lief.PE.parse(input_binary_path)
48 | if pe_obj is None:
49 | raise Exception(f"Failed to parse PE '{input_binary_path}'")
50 |
51 | # Create a new code section
52 | unmut_section = lief.PE.Section([0] * NEW_SECTION_MAX_SIZE, NEW_SECTION_NAME,
53 | lief.PE.Section.CHARACTERISTICS.CNT_CODE.value
54 | | lief.PE.Section.CHARACTERISTICS.MEM_READ.value
55 | | lief.PE.Section.CHARACTERISTICS.MEM_EXECUTE.value)
56 | pe_obj.add_section(unmut_section)
57 | unmut_section = pe_obj.get_section(NEW_SECTION_NAME)
58 | unmut_section_base = pe_obj.imagebase + unmut_section.virtual_address
59 |
60 | # Reassemble simplified AsmCFGs
61 | original_to_simplified: dict[int, int] = {}
62 | next_min_offset_for_asm = 0
63 | unmut_section_patches: list[tuple[int, bytes]] = []
64 | for protected_func_addr, val in \
65 | func_addr_to_simplified_cfg.items():
66 | original_code_addr, simplified_asmcfg, _ = val
67 | # Simplify CFG further (by merging basic blocks when possible)
68 | simplified_asmcfg = bbl_simplifier(simplified_asmcfg)
69 |
70 | # Unpin blocks to be able to relocate the whole CFG
71 | head = miasm_ctx.loc_db.get_offset_location(original_code_addr)
72 | for ir_block in simplified_asmcfg.blocks:
73 | miasm_ctx.loc_db.unset_location_offset(ir_block.loc_key)
74 |
75 | # Relocate the function's entry block
76 | miasm_ctx.loc_db.set_location_offset(head, unmut_section_base + next_min_offset_for_asm)
77 |
78 | # Generate the simplified machine code
79 | new_section_patches = asm_resolve_final(
80 | miasm_ctx.mdis.arch,
81 | simplified_asmcfg,
82 | dst_interval=interval([(unmut_section_base + next_min_offset_for_asm,
83 | unmut_section_base + unmut_section.virtual_size - next_min_offset_for_asm)]))
84 |
85 | # Merge patches into the patch list
86 | for patch in new_section_patches.items():
87 | unmut_section_patches.append(patch)
88 |
89 | # Associate original addr to simplified addr
90 | original_to_simplified[protected_func_addr] = min(new_section_patches.keys())
91 | next_min_offset_for_asm = max(new_section_patches.keys()) - unmut_section_base + 15
92 |
93 | # Overwrite the new section's content
94 | new_section_size = next_min_offset_for_asm
95 | new_content = bytearray([0] * new_section_size)
96 | for addr, data in unmut_section_patches:
97 | offset = addr - unmut_section_base
98 | new_content[offset:offset + len(data)] = data
99 | unmut_section.content = memoryview(new_content)
100 |
101 | # Redirect functions to their simplified versions
102 | protected_function_addrs = func_addr_to_simplified_cfg.keys()
103 | unmut_jmp_patches: list[tuple[int, bytes]] = []
104 | for target_addr in protected_function_addrs:
105 | # Generate a single-block AsmCFG with a JMP to the simplified version
106 | simplified_func_addr = original_to_simplified[target_addr]
107 | unmut_jmp_patch = generate_code_redirect_patch(miasm_ctx, target_addr, simplified_func_addr)
108 | unmut_jmp_patches.append(unmut_jmp_patch)
109 |
110 | # Find the section containing the original function
111 | text_section = __section_from_virtual_address(pe_obj, next(iter(protected_function_addrs)))
112 | assert text_section is not None
113 |
114 | # Apply patches
115 | text_section_base = pe_obj.imagebase + text_section.virtual_address
116 | text_section_bytes = bytearray(text_section.content)
117 | for addr, data in unmut_jmp_patches:
118 | offset = addr - text_section_base
119 | text_section_bytes[offset:offset + len(data)] = data
120 | text_section.content = memoryview(text_section_bytes)
121 |
122 | # Invoke the builder
123 | builder = lief.PE.Builder(pe_obj)
124 | builder.build()
125 |
126 | # Save the result
127 | builder.write(output_binary_path)
128 |
129 |
130 | def __rebuild_simplified_binary_in_place(
131 | miasm_ctx: MiasmContext,
132 | func_addr_to_simplified_cfg: dict[int, tuple[int, AsmCFG, MiasmFunctionInterval]],
133 | input_binary_path: str,
134 | output_binary_path: str,
135 | ) -> None:
136 | """
137 | Reassemble functions' `AsmCFG` and rewrite the input binary with simplified
138 | machine code by overwriting the mutated code.
139 | """
140 | # Open the target binary with LIEF
141 | pe_obj = lief.PE.parse(input_binary_path)
142 | if pe_obj is None:
143 | raise Exception(f"Failed to parse PE '{input_binary_path}'")
144 |
145 | # Reassemble simplified AsmCFGs
146 | original_to_simplified: dict[int, int] = {}
147 | unmut_patches: list[tuple[int, bytes]] = []
148 | for protected_func_addr, val in \
149 | func_addr_to_simplified_cfg.items():
150 | original_code_addr, simplified_asmcfg, orignal_asmcfg_interval = val
151 |
152 | # Generate the simplified machine code
153 | new_section_patches = asm_resolve_final_in_place(miasm_ctx.loc_db,
154 | miasm_ctx.mdis.arch,
155 | simplified_asmcfg,
156 | dst_interval=orignal_asmcfg_interval)
157 |
158 | # Merge patches into the patch list
159 | for patch in new_section_patches.items():
160 | unmut_patches.append(patch)
161 |
162 | # Associate original addr to simplified addr
163 | original_to_simplified[protected_func_addr] = original_code_addr
164 |
165 | # Find Themida's section
166 | mutated_func_addr = next(iter(original_to_simplified.values()))
167 | themida_section = __section_from_virtual_address(pe_obj, mutated_func_addr)
168 | assert themida_section is not None
169 |
170 | # Overwrite Themida's section content
171 | themida_section_base = pe_obj.imagebase + themida_section.virtual_address
172 | new_content = bytearray(themida_section.content)
173 | for addr, data in unmut_patches:
174 | offset = addr - themida_section_base
175 | new_content[offset:offset + len(data)] = data
176 | themida_section.content = memoryview(new_content)
177 |
178 | # Redirect functions to their simplified versions
179 | protected_function_addrs = func_addr_to_simplified_cfg.keys()
180 | unmut_jmp_patches: list[tuple[int, bytes]] = []
181 | for target_addr in protected_function_addrs:
182 | # Generate a single-block AsmCFG with a JMP to the simplified version
183 | simplified_func_addr = original_to_simplified[target_addr]
184 | unmut_jmp_patch = generate_code_redirect_patch(miasm_ctx, target_addr, simplified_func_addr)
185 | unmut_jmp_patches.append(unmut_jmp_patch)
186 |
187 | # Find the section containing the original function
188 | text_section = __section_from_virtual_address(pe_obj, next(iter(protected_function_addrs)))
189 | assert text_section is not None
190 |
191 | # Apply patches
192 | text_section_base = pe_obj.imagebase + text_section.virtual_address
193 | text_section_bytes = bytearray(text_section.content)
194 | for addr, data in unmut_jmp_patches:
195 | offset = addr - text_section_base
196 | text_section_bytes[offset:offset + len(data)] = data
197 | text_section.content = memoryview(text_section_bytes)
198 |
199 | # Invoke the builder
200 | builder = lief.PE.Builder(pe_obj)
201 | builder.build()
202 |
203 | # Save the result
204 | builder.write(output_binary_path)
205 |
206 |
207 | def __section_from_virtual_address(lief_bin: lief.Binary, virtual_addr: int) -> Optional[lief.Section]:
208 | rva = virtual_addr - lief_bin.imagebase
209 | return __section_from_rva(lief_bin, rva)
210 |
211 |
212 | def __section_from_rva(lief_bin: lief.Binary, rva: int) -> Optional[lief.Section]:
213 | for s in lief_bin.sections:
214 | if s.virtual_address <= rva < s.virtual_address + s.size:
215 | assert isinstance(s, lief.Section)
216 | return s
217 |
218 | return None
219 |
--------------------------------------------------------------------------------
/themida_unmutate/symbolic_execution/__init__.py:
--------------------------------------------------------------------------------
1 | from miasm.core.asmblock import AsmCFG
2 |
3 | import themida_unmutate.symbolic_execution.x86 as symex_x86
4 | from themida_unmutate.miasm_utils import MiasmContext, MiasmFunctionInterval
5 |
6 |
7 | def disassemble_and_simplify_functions(
8 | miasm_ctx: MiasmContext, mutated_func_addrs: list[int]) -> list[tuple[int, AsmCFG, MiasmFunctionInterval]]:
9 | """
10 | Disassemble mutated functions, simplify their `AsmCFG` and return them.
11 | """
12 | match miasm_ctx.arch:
13 | case "x86_64" | "x86_32":
14 | return symex_x86.disassemble_and_simplify_functions(miasm_ctx, mutated_func_addrs)
15 |
16 | case _:
17 | raise NotImplementedError("Unsupported architecture")
18 |
--------------------------------------------------------------------------------
/themida_unmutate/symbolic_execution/x86/__init__.py:
--------------------------------------------------------------------------------
1 | import itertools
2 | from typing import Optional, Union
3 |
4 | import miasm.arch.x86.arch as x86_arch
5 | import miasm.expression.expression as m2_expr
6 | from miasm.core.asmblock import AsmCFG, disasmEngine
7 | from miasm.core.cpu import instruction
8 | from miasm.core.interval import interval
9 | from miasm.ir.symbexec import SymbolicExecutionEngine
10 |
11 | from themida_unmutate.logging import logger
12 | from themida_unmutate.miasm_utils import MiasmContext, MiasmFunctionInterval, expr_int_to_int
13 |
14 | # AMD64
15 | AMD64_PTR_SIZE = 64
16 | AMD64_SLICES_MAPPING = {v: k for k, v in x86_arch.replace_regs64.items()}
17 | AMD64_SP_REG = "RSP"
18 | AMD64_IP_REG = "RIP"
19 | # X86
20 | X86_PTR_SIZE = 32
21 | X86_SLICES_MAPPING = {v: k for k, v in x86_arch.replace_regs32.items()}
22 | X86_SP_REG = "ESP"
23 | X86_IP_REG = "EIP"
24 | X86_BINARY_OPS_MAPPING = {
25 | "+": "ADD",
26 | "&": "AND",
27 | "|": "OR",
28 | "^": "XOR",
29 | "a>>": "SAR",
30 | ">>": "SHR",
31 | "<<": "SHL",
32 | ">>>": "ROR",
33 | "<<<": "ROL",
34 | }
35 |
36 | MiasmIRAssignment = tuple[m2_expr.Expr, m2_expr.Expr]
37 |
38 |
39 | def disassemble_and_simplify_functions(
40 | miasm_ctx: MiasmContext, mutated_func_addrs: list[int]) -> list[tuple[int, AsmCFG, MiasmFunctionInterval]]:
41 | """
42 | Disassemble mutated functions, simplify their `AsmCFG` and return them.
43 | """
44 | # Iterate through functions, disassemble and simplify them
45 | simplified_func_asmcfgs: list[tuple[int, AsmCFG, MiasmFunctionInterval]] = []
46 | for mutated_code_addr in mutated_func_addrs:
47 | logger.info("Simplifying function at 0x%x..." % mutated_code_addr)
48 |
49 | # Disassemble function
50 | asm_cfg = miasm_ctx.mdis.dis_multiblock(mutated_code_addr)
51 | # Compute function's interval (this is needed when rewriting the binary
52 | # in-place)
53 | original_func_interval: MiasmFunctionInterval = interval(blk.get_range() for blk in asm_cfg.blocks)
54 |
55 | # Lift assembly to IR
56 | ir_cfg = miasm_ctx.lifter.new_ircfg_from_asmcfg(asm_cfg)
57 |
58 | # Process IR basic blocks
59 | for loc_key, ir_block in ir_cfg.blocks.items():
60 | logger.debug("%s:" % str(loc_key))
61 | asm_block = asm_cfg.loc_key_to_block(loc_key)
62 | if asm_block is None:
63 | # Some instructions such `idiv` generate multiple IR basic blocks from a single asm instruction, so we
64 | # skip these
65 | continue
66 |
67 | relevant_assignblks = ir_block.assignblks[:-1]
68 | relevant_blk_count = len(relevant_assignblks)
69 | # No relevant instruction
70 | # -> unmutated, branching instruction -> keep as is
71 | if relevant_blk_count == 0:
72 | logger.debug(ir_block.assignblks[0].instr)
73 | continue
74 |
75 | # Only 1 or 2 relevant instructions
76 | # -> unmutated, no junk code -> no action needed -> keep first instruction as is
77 | if relevant_blk_count <= 2:
78 | logger.debug(ir_block.assignblks[0].instr)
79 | relocatable_instr = fix_rip_relative_instruction(miasm_ctx, asm_cfg, ir_block.assignblks[0].instr)
80 | asm_block.lines[0] = relocatable_instr
81 | continue
82 |
83 | reference_sb = SymbolicExecutionEngine(miasm_ctx.lifter)
84 | for assign_block in relevant_assignblks:
85 | reference_sb.eval_updt_assignblk(assign_block)
86 | # Forget dead stack slots
87 | reference_sb.del_mem_above_stack(miasm_ctx.lifter.sp)
88 |
89 | # Strip FLAGS register (as these are trashed by the mutation)
90 | strip_sym_flags(reference_sb)
91 |
92 | # More than 2 instructions but a single instruction replicates the symbolic state
93 | # -> unmutated, junk code inserted -> keep the one instruction as is
94 | block_simplified = False
95 | for assignblk_subset in itertools.combinations(relevant_assignblks, 1):
96 | sb = SymbolicExecutionEngine(miasm_ctx.lifter)
97 |
98 | for assign_block in assignblk_subset:
99 | sb.eval_updt_assignblk(assign_block)
100 | reference_sb.del_mem_above_stack(miasm_ctx.lifter.sp)
101 |
102 | # Check if instruction replicates the symbolic state
103 | if reference_sb.get_state() == sb.get_state():
104 | for a in assignblk_subset:
105 | logger.debug(a.instr)
106 | # Update block asm block
107 | relocatable_instr = fix_rip_relative_instruction(miasm_ctx, asm_cfg, a.instr)
108 | asm_block.lines = [relocatable_instr, asm_block.lines[-1]]
109 | block_simplified = True
110 | break
111 | if block_simplified:
112 | continue
113 |
114 | # More than 2 instructions but no single instruction replicates the symbolic state
115 | # -> mutated, junk code inserted -> try to "synthetize" instruction manually
116 | modified_variables = dict(reference_sb.modified())
117 | match len(modified_variables):
118 | # No assignment block: RET, JMP
119 | case 0:
120 | # Keep only the last instruction
121 | logger.debug(asm_block.lines[-1])
122 | asm_block.lines = [asm_block.lines[-1]]
123 | continue
124 |
125 | # 1 assignment block: MOV, XCHG, n-ary operators
126 | case 1:
127 | ir_assignment = next(iter(modified_variables.items()))
128 | dst, value = normalize_ir_assigment(miasm_ctx, ir_assignment)
129 | match type(value):
130 | case m2_expr.ExprId | m2_expr.ExprMem | m2_expr.ExprInt | m2_expr.ExprSlice:
131 | # Assignation
132 | # -> MOV
133 | match type(dst):
134 | case m2_expr.ExprId | m2_expr.ExprMem | m2_expr.ExprSlice:
135 | original_instr = handle_mov(miasm_ctx, dst, value)
136 | if original_instr is not None:
137 | # Update block asm block
138 | relocatable_instr = fix_rip_relative_instruction(
139 | miasm_ctx, asm_cfg, original_instr)
140 | asm_block.lines = [relocatable_instr, asm_block.lines[-1]]
141 | continue
142 |
143 | case m2_expr.ExprOp:
144 | # N-ary operation on native-size registers
145 | # -> ADD/SUB/INC/DEC/AND/OR/XOR/NEG/NOT/ROL/ROR/SAR/SHL/SHR
146 | original_instr = handle_nary_op(miasm_ctx, dst, value)
147 | if original_instr is not None:
148 | # Update block asm block
149 | relocatable_instr = fix_rip_relative_instruction(miasm_ctx, asm_cfg, original_instr)
150 | asm_block.lines = [relocatable_instr, asm_block.lines[-1]]
151 | continue
152 |
153 | case m2_expr.ExprCompose:
154 | # MOV, XCHG on single register or n-ary operation on lower-sized registers
155 | original_instr = handle_compose(miasm_ctx, dst, value)
156 | if original_instr is not None:
157 | # Update block asm block
158 | relocatable_instr = fix_rip_relative_instruction(miasm_ctx, asm_cfg, original_instr)
159 | asm_block.lines = [relocatable_instr, asm_block.lines[-1]]
160 | continue
161 |
162 | # 2 assignment blocks
163 | # -> PUSH, POP, XCHG, `SUB RSP, X`
164 | case 2:
165 | modified_variables_iter = iter(modified_variables.items())
166 | assignblk1 = next(modified_variables_iter)
167 | assignblk2 = next(modified_variables_iter)
168 |
169 | # PUSH
170 | original_instr = handle_push(miasm_ctx, assignblk1, assignblk2)
171 | if original_instr is not None:
172 | # Update block asm block
173 | relocatable_instr = fix_rip_relative_instruction(miasm_ctx, asm_cfg, original_instr)
174 | asm_block.lines = [relocatable_instr, asm_block.lines[-1]]
175 | continue
176 | # POP
177 | original_instr = handle_pop(miasm_ctx, assignblk1, assignblk2)
178 | if original_instr is not None:
179 | # Update block asm block
180 | relocatable_instr = fix_rip_relative_instruction(miasm_ctx, asm_cfg, original_instr)
181 | asm_block.lines = [relocatable_instr, asm_block.lines[-1]]
182 | continue
183 | # XCHG
184 | original_instr = handle_xchg(miasm_ctx, assignblk1, assignblk2)
185 | if original_instr is not None:
186 | # Update block asm block
187 | relocatable_instr = fix_rip_relative_instruction(miasm_ctx, asm_cfg, original_instr)
188 | asm_block.lines = [relocatable_instr, asm_block.lines[-1]]
189 | continue
190 |
191 | # `SUB RSP, X`
192 | original_instr = handle_sub_rsp(miasm_ctx, modified_variables)
193 | if original_instr is not None:
194 | # Update block asm block
195 | relocatable_instr = fix_rip_relative_instruction(miasm_ctx, asm_cfg, original_instr)
196 | asm_block.lines = [relocatable_instr, asm_block.lines[-1]]
197 | continue
198 |
199 | # More than 2 assignment blocks
200 | # -> `SUB RSP, X`
201 | case _:
202 | original_instr = handle_sub_rsp(miasm_ctx, modified_variables)
203 | if original_instr is not None:
204 | # Update block asm block
205 | relocatable_instr = fix_rip_relative_instruction(miasm_ctx, asm_cfg, original_instr)
206 | asm_block.lines = [relocatable_instr, asm_block.lines[-1]]
207 | continue
208 |
209 | logger.debug(modified_variables)
210 | logger.warning("Unsupported instruction or unmutated block found. "
211 | "Block will be kept as is.")
212 |
213 | simplified_func_asmcfgs.append((mutated_code_addr, asm_cfg, original_func_interval))
214 |
215 | return simplified_func_asmcfgs
216 |
217 |
218 | def strip_sym_flags(symex: SymbolicExecutionEngine) -> None:
219 | symex.apply_change(m2_expr.ExprId("zf", 1), m2_expr.ExprId("zf", 1))
220 | symex.apply_change(m2_expr.ExprId("nf", 1), m2_expr.ExprId("nf", 1))
221 | symex.apply_change(m2_expr.ExprId("pf", 1), m2_expr.ExprId("pf", 1))
222 | symex.apply_change(m2_expr.ExprId("cf", 1), m2_expr.ExprId("cf", 1))
223 | symex.apply_change(m2_expr.ExprId("of", 1), m2_expr.ExprId("of", 1))
224 | symex.apply_change(m2_expr.ExprId("af", 1), m2_expr.ExprId("af", 1))
225 |
226 |
227 | def handle_mov(
228 | miasm_ctx: MiasmContext,
229 | dst: m2_expr.Expr,
230 | value: Union[m2_expr.ExprId, m2_expr.ExprMem, m2_expr.ExprInt, m2_expr.ExprSlice],
231 | zero_extended: bool = False,
232 | ) -> Optional[instruction]:
233 | if zero_extended:
234 | # Note(ergrelet): in x86, MOVZX only takes r/m8 and r/m16 operands
235 | if value.size <= 16:
236 | original_instr_str = f"MOVZX {ir_to_asm_str(dst)}, {ir_to_asm_str(value)}"
237 | else:
238 | # For other sizes, we simply use MOV and use a subregister as the destination
239 | if value.is_slice() and value.start == 0:
240 | dst = m2_expr.ExprSlice(dst, value.start, value.stop)
241 | original_instr_str = f"MOV {ir_to_asm_str(dst)}, {ir_to_asm_str(value)}"
242 | else:
243 | original_instr_str = f"MOV {ir_to_asm_str(dst)}, {ir_to_asm_str(value)}"
244 | original_instr = miasm_ctx.mdis.arch.fromstring(original_instr_str, miasm_ctx.mdis.loc_db, miasm_ctx.mdis.attrib)
245 | logger.debug(original_instr)
246 | return original_instr
247 |
248 |
249 | def handle_nary_op(miasm_ctx: MiasmContext, dst: m2_expr.Expr, op_expr: m2_expr.ExprOp) -> Optional[instruction]:
250 | match op_expr.op:
251 | # ADD, SUB, INC, DEC, NEG (we treat this separately from other binary operations)
252 | # Note(ergrelet): SUB is lifted as ADD(VAL1, -VAL2), NEG is lifted as ADD(0, -VAL)
253 | case "+":
254 | return handle_add_operation(miasm_ctx, dst, op_expr)
255 | # AND, OR, XOR, NOT, SAR, SHR, SHL, ROR, ROL
256 | # Note(ergrelet): NOT is lifted as XOR(VAL, -1)
257 | case "&" | "|" | "^" | "a>>" | ">>" | "<<" | ">>>" | "<<<":
258 | return handle_binary_operation(miasm_ctx, dst, op_expr)
259 | case _:
260 | return None
261 |
262 |
263 | def handle_compose(miasm_ctx: MiasmContext, dst: m2_expr.Expr,
264 | compose_expr: m2_expr.ExprCompose) -> Optional[instruction]:
265 | inner_value_expr = compose_expr.args[0]
266 |
267 | # Match exprs of the form: '{RAX[0:32] + 0x1 0 32, 0x0 32 64}' (zero extension)
268 | is_zero_extension = len(compose_expr.args) == 2 and \
269 | compose_expr.args[1].is_int() and compose_expr.args[1].arg == 0
270 | # Match exprs of the form: '{RDX[0:8] + 0x1 0 8, RDX[8:64] 8 64}' (subregister)
271 | is_subregister_assign = len(compose_expr.args) == 2 and \
272 | compose_expr.args[1].is_slice() and \
273 | compose_expr.args[1].arg.is_id() and dst == compose_expr.args[1].arg
274 | if is_zero_extension or is_subregister_assign:
275 | match type(inner_value_expr):
276 | case m2_expr.ExprSlice:
277 | return handle_mov(miasm_ctx, dst, inner_value_expr, is_zero_extension)
278 | case m2_expr.ExprOp:
279 | return handle_nary_op(miasm_ctx, dst, inner_value_expr)
280 |
281 | # Handle XCHG cases where DST and SRC are subregisters of the same register
282 | # Match exprs of the form: '{RCX[8:16] 0 8, RCX[0:8] 8 16, RCX[16:64] 16 64}' (subregister swap)
283 | is_subregister_swap = len(compose_expr.args) == 3 and \
284 | all(map(lambda expr: expr.is_slice() and expr.arg.is_id() and expr.arg == dst,
285 | compose_expr.args))
286 | if is_subregister_swap:
287 | compose_lower_part, compose_mid_part, _ = compose_expr.args
288 | # 8-bit subregisters swap
289 | if compose_lower_part.size == compose_mid_part.size == 8:
290 | return handle_xchg(miasm_ctx, (compose_lower_part, compose_mid_part),
291 | (compose_mid_part, compose_lower_part))
292 |
293 | return None
294 |
295 |
296 | def handle_add_operation(miasm_ctx: MiasmContext, dst: m2_expr.Expr, op_expr: m2_expr.ExprOp) -> Optional[instruction]:
297 | lhs = op_expr.args[0]
298 | rhs = op_expr.args[1]
299 |
300 | # Sub
301 | if rhs.is_op() and rhs.op == "-":
302 | if len(rhs.args) == 1 and not rhs.args[0].is_op():
303 | # DST = DST + (-RHS)
304 | if dst == lhs:
305 | original_instr_str = f"SUB {ir_to_asm_str(dst)}, {ir_to_asm_str(rhs.args[0])}"
306 | original_instr = miasm_ctx.mdis.arch.fromstring(original_instr_str, miasm_ctx.mdis.loc_db,
307 | miasm_ctx.mdis.attrib)
308 | logger.debug(original_instr)
309 | return original_instr
310 | # DST = DST[0:XX] + (-RHS)
311 | if is_a_slice_of(lhs, dst):
312 | dst = m2_expr.ExprSlice(dst, lhs.start, lhs.stop)
313 | original_instr_str = f"SUB {ir_to_asm_str(dst)}, {ir_to_asm_str(rhs.args[0])}"
314 | original_instr = miasm_ctx.mdis.arch.fromstring(original_instr_str, miasm_ctx.mdis.loc_db,
315 | miasm_ctx.mdis.attrib)
316 | logger.debug(original_instr)
317 | return original_instr
318 |
319 | # Sub
320 | if lhs.is_op() and lhs.op == "-":
321 | if len(lhs.args) == 1 and not lhs.args[0].is_op():
322 | # DST = (-LHS) + DST
323 | if dst == rhs:
324 | original_instr_str = f"SUB {ir_to_asm_str(dst)}, {ir_to_asm_str(lhs.args[0])}"
325 | original_instr = miasm_ctx.mdis.arch.fromstring(original_instr_str, miasm_ctx.mdis.loc_db,
326 | miasm_ctx.mdis.attrib)
327 | logger.debug(original_instr)
328 | return original_instr
329 | # DST = (-LHS) + DST[0:XX]
330 | if is_a_slice_of(rhs, dst):
331 | dst = m2_expr.ExprSlice(dst, rhs.start, rhs.stop)
332 | original_instr_str = f"SUB {ir_to_asm_str(dst)}, {ir_to_asm_str(lhs.args[0])}"
333 | original_instr = miasm_ctx.mdis.arch.fromstring(original_instr_str, miasm_ctx.mdis.loc_db,
334 | miasm_ctx.mdis.attrib)
335 | logger.debug(original_instr)
336 | return original_instr
337 |
338 | # TODO: handle NEG?
339 |
340 | # Add (regular binary operations)
341 | return handle_binary_operation(miasm_ctx, dst, op_expr)
342 |
343 |
344 | def handle_binary_operation(miasm_ctx: MiasmContext, dst: m2_expr.Expr,
345 | op_expr: m2_expr.ExprOp) -> Optional[instruction]:
346 | op_asm_str = X86_BINARY_OPS_MAPPING.get(op_expr.op)
347 | if op_asm_str is None:
348 | # Unsupported operation
349 | return None
350 |
351 | lhs = op_expr.args[0]
352 | rhs = op_expr.args[1]
353 | if not lhs.is_op() and not rhs.is_op():
354 | # DST = OP(DST, RHS)
355 | if dst == lhs:
356 | original_instr_str = f"{op_asm_str} {ir_to_asm_str(dst)}, {ir_to_asm_str(rhs)}"
357 | original_instr = miasm_ctx.mdis.arch.fromstring(original_instr_str, miasm_ctx.mdis.loc_db,
358 | miasm_ctx.mdis.attrib)
359 | logger.debug(original_instr)
360 | return original_instr
361 | # DST = OP(LHS, DST)
362 | if dst == rhs:
363 | original_instr_str = f"{op_asm_str} {ir_to_asm_str(dst)}, {ir_to_asm_str(lhs)}"
364 | original_instr = miasm_ctx.mdis.arch.fromstring(original_instr_str, miasm_ctx.mdis.loc_db,
365 | miasm_ctx.mdis.attrib)
366 | logger.debug(original_instr)
367 | return original_instr
368 | # DST = OP(DST[0:XX], RHS)
369 | if is_a_slice_of(lhs, dst):
370 | dst = m2_expr.ExprSlice(dst, lhs.start, lhs.stop)
371 | original_instr_str = f"{op_asm_str} {ir_to_asm_str(dst)}, {ir_to_asm_str(rhs)}"
372 | original_instr = miasm_ctx.mdis.arch.fromstring(original_instr_str, miasm_ctx.mdis.loc_db,
373 | miasm_ctx.mdis.attrib)
374 | logger.debug(original_instr)
375 | return original_instr
376 | # DST = OP(LHS, DST[0:XX])
377 | if is_a_slice_of(rhs, dst):
378 | dst = m2_expr.ExprSlice(dst, rhs.start, rhs.stop)
379 | original_instr_str = f"{op_asm_str} {ir_to_asm_str(dst)}, {ir_to_asm_str(lhs)}"
380 | original_instr = miasm_ctx.mdis.arch.fromstring(original_instr_str, miasm_ctx.mdis.loc_db,
381 | miasm_ctx.mdis.attrib)
382 | logger.debug(original_instr)
383 | return original_instr
384 |
385 | return None
386 |
387 |
388 | def handle_xchg(miasm_ctx: MiasmContext, ir_assignment1: MiasmIRAssignment,
389 | ir_assignment2: MiasmIRAssignment) -> Optional[instruction]:
390 | norm_assignment1 = normalize_ir_assigment(miasm_ctx, ir_assignment1)
391 | norm_assignment2 = normalize_ir_assigment(miasm_ctx, ir_assignment2)
392 |
393 | # Handle most XCHG cases where DST and SRC are swapped and aren't part of
394 | # the same register
395 | if norm_assignment1[0] == norm_assignment2[1] and \
396 | norm_assignment2[0] == norm_assignment1[1]:
397 | original_instr_str = f"XCHG {ir_to_asm_str(norm_assignment2[0])}, {ir_to_asm_str(norm_assignment2[1])}"
398 | original_instr = miasm_ctx.mdis.arch.fromstring(original_instr_str, miasm_ctx.mdis.loc_db,
399 | miasm_ctx.mdis.attrib)
400 | logger.debug(original_instr)
401 | return original_instr
402 |
403 | return None
404 |
405 |
406 | def handle_push(miasm_ctx: MiasmContext, ir_assignment1: MiasmIRAssignment,
407 | ir_assignment2: MiasmIRAssignment) -> Optional[instruction]:
408 | _, SP_REG, PTR_SIZE = get_constants_for_architecture(miasm_ctx.arch)
409 |
410 | MAX_USIZE = 2**PTR_SIZE
411 | rsp_decrement_op = m2_expr.ExprOp("+", m2_expr.ExprId(SP_REG, PTR_SIZE),
412 | m2_expr.ExprInt(MAX_USIZE - (PTR_SIZE // 8), PTR_SIZE))
413 | is_rsp_decremented = ir_assignment1[1] == rsp_decrement_op
414 | is_dst1_rsp = ir_assignment1[0].is_id() and ir_assignment1[0].name == SP_REG
415 | is_dst2_on_stack = ir_assignment2[0].is_mem() and \
416 | ir_assignment2[0].ptr == rsp_decrement_op
417 |
418 | if is_dst1_rsp and is_rsp_decremented and is_dst2_on_stack:
419 | original_instr_str = f"PUSH {ir_to_asm_str(ir_assignment2[1])}"
420 | original_instr = miasm_ctx.mdis.arch.fromstring(original_instr_str, miasm_ctx.mdis.loc_db,
421 | miasm_ctx.mdis.attrib)
422 | logger.debug(original_instr)
423 | return original_instr
424 |
425 | return None
426 |
427 |
428 | def handle_pop(miasm_ctx: MiasmContext, ir_assignment1: MiasmIRAssignment,
429 | ir_assignment2: MiasmIRAssignment) -> Optional[instruction]:
430 | _, SP_REG, PTR_SIZE = get_constants_for_architecture(miasm_ctx.arch)
431 |
432 | rsp_increment_op = m2_expr.ExprOp("+", m2_expr.ExprId(SP_REG, PTR_SIZE), m2_expr.ExprInt(PTR_SIZE // 8, PTR_SIZE))
433 | is_rsp_incremented = ir_assignment2[1] == rsp_increment_op
434 | is_value1_on_stack = ir_assignment1[1].is_mem() and \
435 | ir_assignment1[1].ptr.is_id() and ir_assignment1[1].ptr.name == SP_REG
436 | is_dst2_rsp = ir_assignment2[0].is_id() and \
437 | ir_assignment2[0].name == SP_REG
438 |
439 | if is_value1_on_stack and is_rsp_incremented and is_dst2_rsp:
440 | original_instr_str = f"POP {ir_to_asm_str(ir_assignment1[0])}"
441 | original_instr = miasm_ctx.mdis.arch.fromstring(original_instr_str, miasm_ctx.mdis.loc_db,
442 | miasm_ctx.mdis.attrib)
443 | logger.debug(original_instr)
444 | return original_instr
445 |
446 | return None
447 |
448 |
449 | # Note(ergrelet): `SUB RSP, X` is a special case where there might be some residual
450 | # constraints that the symbolic execution cannot discard, because allocated stack
451 | # slots are live and values might have been assigned to some of them by the
452 | # inserted junk code.
453 | # We thus have to differentiate legit PUSH-like instructions from junked
454 | # `SUB RSP, X` instructions.
455 | def handle_sub_rsp(miasm_ctx: MiasmContext, assign_blk: dict[m2_expr.Expr, m2_expr.Expr]) -> Optional[instruction]:
456 | _, SP_REG, _ = get_constants_for_architecture(miasm_ctx.arch)
457 |
458 | def is_sub_rsp_expr(expr: m2_expr.Expr) -> bool:
459 | """
460 | This matches OP expressions of the form "RSP - X"
461 | """
462 | if not expr.is_op():
463 | return False
464 |
465 | is_binary_add = expr.op == "+" and len(expr.args) == 2
466 | if not is_binary_add:
467 | return False
468 |
469 | # One of the operands must be RSP
470 | rsp_in_expr = any(map(lambda arg: arg.is_id() and arg.name == SP_REG, expr.args))
471 | # The other operand must be a negative integer
472 | neg_int_in_expr = any(map(lambda arg: arg.is_int() and expr_int_to_int(arg) < 0, expr.args))
473 |
474 | return rsp_in_expr and neg_int_in_expr
475 |
476 | def is_sub_rsp_blk(ir_assignment: MiasmIRAssignment) -> bool:
477 | """
478 | This matches assignments of the form "RSP - X"
479 | """
480 | dst, src = ir_assignment
481 | if not dst.is_id() or not src.is_op():
482 | return False
483 |
484 | # Destination must be RSP
485 | dst_is_rsp = dst.name == SP_REG
486 | return dst_is_rsp and is_sub_rsp_expr(src)
487 |
488 | # Check if a SUB operation is applied to RSP
489 | sub_rsp_blk = next(filter(is_sub_rsp_blk, assign_blk.items()), None)
490 | if sub_rsp_blk is not None:
491 | # Extract allocated size
492 | allocated_window = (0, expr_int_to_int(sub_rsp_blk[1].args[1]))
493 | # Check if all allocated slots have been written to or not. This
494 | # assumes no PUSH-like x86 instruction allocates more slots than needed to
495 | # write the data it pushes to the stack
496 | #
497 | # FIXME: we're not checking individual stack slots but rather
498 | # the outter boundaries from used stack slots. It would be better
499 | # to track accesses to each stack slot separately.
500 | used_window = [0, 0]
501 | for dst in assign_blk.keys():
502 | if dst.is_mem() and is_sub_rsp_expr(dst.ptr):
503 | dst_offset_in_stack = expr_int_to_int(dst.ptr.args[1])
504 | dst_size_in_bytes = dst.size // 8
505 | used_window[0] = max(used_window[0], dst_offset_in_stack + dst_size_in_bytes)
506 | used_window[1] = min(used_window[1], dst_offset_in_stack)
507 | if tuple(used_window) == allocated_window:
508 | # All allocated slots are used, must be a PUSH-like instruction
509 | return None
510 |
511 | original_instr_str = f"SUB {SP_REG}, {-allocated_window[1]}"
512 | original_instr = miasm_ctx.mdis.arch.fromstring(original_instr_str, miasm_ctx.mdis.loc_db,
513 | miasm_ctx.mdis.attrib)
514 | logger.debug(original_instr)
515 | return original_instr
516 |
517 | return None
518 |
519 |
520 | def ir_to_asm_str(expr: m2_expr.Expr) -> str:
521 | match type(expr):
522 | case m2_expr.ExprMem:
523 | return mem_ir_to_asm_str(expr)
524 | case m2_expr.ExprSlice:
525 | return slice_ir_to_asm_str(expr)
526 | case _:
527 | return str(expr)
528 |
529 |
530 | def mem_ir_to_asm_str(mem_expr: m2_expr.ExprMem) -> str:
531 | match mem_expr.size:
532 | case 128 | 64 | 32 | 16 | 8:
533 | mem_prefix = x86_arch.SIZE2MEMPREFIX[mem_expr.size]
534 | return f"{mem_prefix} PTR [{mem_expr.ptr}]"
535 | case _:
536 | raise ValueError("Invalid ExprMem size")
537 |
538 |
539 | def slice_ir_to_asm_str(slice_expr: m2_expr.ExprSlice) -> str:
540 | match type(slice_expr.arg):
541 | case m2_expr.ExprId:
542 | # Slice of a register
543 | return str(AMD64_SLICES_MAPPING[slice_expr])
544 | case _:
545 | return str(slice_expr)
546 |
547 |
548 | def normalize_ir_assigment(miasm_ctx: MiasmContext, ir_assignment: MiasmIRAssignment) -> MiasmIRAssignment:
549 | """
550 | Normalize IR assignments by transforming `ExprCompose`s in SRC into
551 | `ExprSlice`s in DST when appropriate.
552 | This allows us to properly detect assigments made to subregisters
553 | (e.g., `EAX`, `AX`, `AL`, `AH`).
554 | """
555 | _, _, PTR_SIZE = get_constants_for_architecture(miasm_ctx.arch)
556 | dst, src = ir_assignment
557 |
558 | # Match ExprId(X) = ExprCompose(Y)
559 | if dst.is_id() and src.is_compose():
560 | match len(src.args):
561 | # 2-way compose (e.g., `EAX`, `AX`, `AL`)
562 | case 2:
563 | compose_lower_part, compose_upper_part = src.args
564 | # If upper bits from DST are kept, it means we're dealing with
565 | # a 16-bit or 8-bit subregister
566 | if compose_upper_part.arg == dst and \
567 | compose_upper_part.start == compose_lower_part.size and \
568 | compose_upper_part.stop == dst.size:
569 | # DST -> DST[0:X]
570 | new_dst = m2_expr.ExprSlice(dst, 0, compose_lower_part.size)
571 | # Concat(SRC[0:X], DST[X:]) -> SRC[0:X]
572 | new_src = compose_lower_part
573 | return (new_dst, new_src)
574 |
575 | # If upper bits are zeroed out, it means mean we're dealing with
576 | # a 32-bit subregister
577 | upper_zero_bits = m2_expr.ExprInt(0, PTR_SIZE // 2)
578 | if compose_upper_part == upper_zero_bits:
579 | # DST -> DST[0:32]
580 | new_dst = m2_expr.ExprSlice(dst, 0, compose_lower_part.size)
581 | # Concat(SRC, DST[X:]) -> SRC
582 | new_src = compose_lower_part
583 |
584 | return (new_dst, new_src)
585 |
586 | # 3-way compose (e.g., `AH`, `BH`)
587 | case 3:
588 | compose_lower_part, compose_mid_part, compose_upper_part = src.args
589 | # If lower and upper bits from DST are kept, it means we're
590 | # dealing with a subregister
591 | if compose_lower_part.arg == dst and \
592 | compose_lower_part.start == 0 and \
593 | compose_upper_part.arg == dst and \
594 | compose_upper_part.stop == dst.size:
595 | # DST -> DST[X:Y]
596 | new_dst = m2_expr.ExprSlice(dst, compose_lower_part.size,
597 | compose_lower_part.size + compose_mid_part.size)
598 | # Concat(DST[0:X], SRC, DST[Y:]) -> SRC
599 | new_src = compose_mid_part
600 | return (new_dst, new_src)
601 |
602 | return ir_assignment
603 |
604 |
605 | def is_a_slice_of(slice_expr: m2_expr.Expr, expr: m2_expr.Expr) -> bool:
606 | return slice_expr.is_slice() and slice_expr.arg == expr # type:ignore
607 |
608 |
609 | # Fix RIP relative instructions to make them relocatable
610 | def fix_rip_relative_instruction(miasm_ctx: MiasmContext, asmcfg: AsmCFG, instr: instruction) -> instruction:
611 | IP_REG, _, PTR_SIZE = get_constants_for_architecture(miasm_ctx.arch)
612 |
613 | rip = m2_expr.ExprId(IP_REG, PTR_SIZE)
614 | # Note(ergrelet): see https://github.com/cea-sec/miasm/issues/1258#issuecomment-645640366
615 | # for more information on what the '_' symbol is used for.
616 | new_next_addr_card = m2_expr.ExprLoc(asmcfg.loc_db.get_or_create_name_location('_'), PTR_SIZE)
617 | for i, arg in enumerate(instr.args):
618 | if rip in arg:
619 | assert instr.offset is not None and instr.l is not None
620 | next_instr_addr = m2_expr.ExprInt(instr.offset + instr.l, PTR_SIZE)
621 | fix_dict = {rip: rip + next_instr_addr - new_next_addr_card}
622 | instr.args[i] = arg.replace_expr(fix_dict)
623 |
624 | # Note(ergrelet): reset the instruction's additional info to avoid
625 | # certain assembling issues where instruction prefixes are mixed
626 | # in an illegal way.
627 | reset_additional_instruction_info(instr)
628 |
629 | return instr
630 |
631 |
632 | def reset_additional_instruction_info(instr: instruction) -> None:
633 | instr.additional_info = x86_arch.additional_info()
634 | instr.additional_info.g1.value = 0
635 | instr.additional_info.g2.value = 0
636 |
637 |
638 | def get_constants_for_architecture(architecture: str) -> tuple[str, str, int]:
639 | match architecture:
640 | case "x86_32":
641 | return X86_IP_REG, X86_SP_REG, X86_PTR_SIZE
642 | case "x86_64":
643 | return AMD64_IP_REG, AMD64_SP_REG, AMD64_PTR_SIZE
644 | case _:
645 | raise NotImplementedError("Unsupported architecture")
646 |
--------------------------------------------------------------------------------
/themida_unmutate/unwrapping.py:
--------------------------------------------------------------------------------
1 | import miasm.expression.expression as m2_expr
2 | from miasm.ir.ir import IRCFG, Lifter
3 | from miasm.ir.symbexec import SymbolicExecutionEngine
4 |
5 | from themida_unmutate.logging import logger
6 | from themida_unmutate.miasm_utils import MiasmContext, expr_int_to_int
7 |
8 |
9 | def unwrap_functions(miasm_ctx: MiasmContext, target_function_addrs: list[int]) -> list[int]:
10 | """
11 | Resolve mutated function's addresses from original function addresses.
12 | """
13 | mutated_func_addrs: list[int] = []
14 | for addr in target_function_addrs:
15 | logger.debug("Resolving mutated code portion address for 0x%x..." % addr)
16 | mutated_code_addr = _resolve_mutated_code_address(miasm_ctx, addr)
17 | if mutated_code_addr == addr:
18 | raise Exception("Failure to unwrap function")
19 |
20 | logger.info("Function at 0x%x jumps to 0x%x" % (addr, mutated_code_addr))
21 | mutated_func_addrs.append(mutated_code_addr)
22 |
23 | return mutated_func_addrs
24 |
25 |
26 | def _resolve_mutated_code_address(miasm_ctx: MiasmContext, target_addr: int) -> int:
27 | # Save `follow_call` value and set it to `True`
28 | saved_follow_call = miasm_ctx.mdis.follow_call
29 | miasm_ctx.mdis.follow_call = True
30 | # Disassemble trampoline
31 | asmcfg = miasm_ctx.mdis.dis_multiblock(target_addr)
32 | # Restore `follow_call` value
33 | miasm_ctx.mdis.follow_call = saved_follow_call
34 | # Lift ASM to IR
35 | ircfg = miasm_ctx.lifter.new_ircfg_from_asmcfg(asmcfg)
36 |
37 | return _resolve_mutated_portion_address(miasm_ctx.lifter, ircfg, target_addr)
38 |
39 |
40 | def _resolve_mutated_portion_address(lifter: Lifter, ircfg: IRCFG, call_addr: int) -> int:
41 | # Instantiate a Symbolic Execution engine with default value for registers
42 | symb = SymbolicExecutionEngine(lifter)
43 |
44 | # Emulate until the next address cannot be resolved (`ret`, unresolved condition, etc.)
45 | cur_expr = symb.run_at(ircfg, call_addr)
46 |
47 | # First `cmp` -> eval to zero
48 | if not cur_expr.is_cond() or not cur_expr.cond.is_mem():
49 | logger.warning("Function doesn't behave as expected, considering it unmutated")
50 | return call_addr
51 |
52 | # Value if condition is evaled zero
53 | symb.eval_updt_expr(m2_expr.ExprAssign(cur_expr.cond, m2_expr.ExprInt(0, cur_expr.cond.size)))
54 | target = cur_expr.src2
55 | cur_expr = symb.run_at(ircfg, target)
56 |
57 | # Second `cmp` -> eval to zero
58 | if not cur_expr.is_cond() or not cur_expr.cond.is_mem():
59 | logger.warning("Function doesn't behave as expected, considering it unmutated")
60 | return call_addr
61 |
62 | # Value if condition is evaled zero
63 | symb.eval_updt_expr(m2_expr.ExprAssign(cur_expr.cond, m2_expr.ExprInt(0, cur_expr.cond.size)))
64 | target = cur_expr.src2
65 | cur_expr = symb.run_at(ircfg, target)
66 | if not isinstance(cur_expr, m2_expr.ExprInt):
67 | # If we're here, this might be a Themida 3.1.7+ trampoline, handle the additional JCC
68 | if not cur_expr.is_cond() or not cur_expr.cond.is_mem():
69 | logger.warning("Function doesn't behave as expected, considering it unmutated")
70 | return call_addr
71 |
72 | symb.eval_updt_expr(m2_expr.ExprAssign(cur_expr.cond, m2_expr.ExprInt(0, cur_expr.cond.size)))
73 | target = cur_expr.src2
74 | cur_expr = symb.run_at(ircfg, target)
75 | if not isinstance(cur_expr, m2_expr.ExprInt):
76 | logger.warning("Function doesn't behave as expected, considering it unmutated")
77 | return call_addr
78 |
79 | # This time we should have the real mutated function address
80 | return expr_int_to_int(cur_expr)
81 |
--------------------------------------------------------------------------------