├── LICENSE
├── README.md
├── __init__.py
├── deflat2.py
├── deineffective.py
├── dejmpreg.py
├── emulate.py
└── plugin.json
/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 | # detx
2 | 去除libtprt.so中的混淆, 去混淆思路看这两个贴子:
3 | * [使用BinaryNinja去除libtprt.so的混淆 (一)](https://bbs.kanxue.com/thread-282826.htm).
4 | * [使用BinaryNinja去除libtprt.so的混淆 (二)](https://bbs.kanxue.com/thread-282918.htm).
5 |
6 |
7 | ## 1. 安装说明
8 | ### 1.1 安装依赖
9 | 打开BinaryNinja, 按下ctrl+p, 搜索Install python3 module..., 然后安装setuptools和unicorn
10 |
11 | ### 1.2 安装插件
12 | 将本仓库的所有文件放到%APPDATA%\\Binary Ninja\\plugins\\detx中, 此时plugins文件夹内的结构应该是:
13 | ```
14 | .
15 | ├── binexport12_binaryninja.dll
16 | └── detx
17 | ├── LICENSE
18 | ├── README.md
19 | ├── __init__.py
20 | ├── deflat2.py
21 | ├── dejmpreg.py
22 | ├── emulate.py
23 | └── plugin.json
24 | ```
25 |
26 | ## 2. 使用说明
27 | ### 2.1 去\[寄存器间接跳转\]混淆
28 | >代码逻辑在dejmpreg.py中
29 | 1. 找到形如"br x9"的指令, 鼠标点击 -> 鼠标右键Plugins -> detx -> dejmpreg
30 | 2. auto就是自动去混淆, 会自动搜索一个函数内的所有jmpreg混淆, 然后依次去除
31 | 3. once就是只去除鼠标所在的那一处混淆
32 | 4. manual就是自己输入跳转表的偏移, 分析失败的时候调试用
33 |
34 | ### 2.2 去\[控制流平坦化\]混淆
35 | >代码逻辑在deflat2.py中
36 | 1. 从mlil ssa层面找到循环分发开始的那个if (或者在汇编层面找到循环分发开始的那个cmp), 鼠标点击该if (汇编层面要点cmp的下一条指令) -> 鼠标右键Plugins -> detx -> deflat2
37 | 2. 'deflat use this var' 就是正常的去控制流平坦化混淆
38 | 3. 'deflat nested' 是去除嵌套的平坦化 需要手动输入出口地址
39 | 4. 'deflat with check' 会将分发块的后继块当作真实块 并且会记录初始的分发寄存器的值 每次循环开始时都会重新设置寄存器值 **推荐**使用这个方法
40 | 5. 'deflat manual' 就是手动设置switch变量的一个值 调试用
41 |
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 | from binaryninja import PluginCommand, BinaryView
2 | from .deflat2 import deflat_cursor, deflat_nested, deflat_manual, deflat_with_check
3 | from .dejmpreg import dejmpreg_auto, dejmpreg_cursor, dejmpreg_manual
4 |
5 | def is_valid(bv: BinaryView, address: int) -> bool:
6 | return True
7 |
8 | PluginCommand.register_for_address("detx\\deflat2\\deflat use this var", "use the variable on the line where the cursor is located as the switch variable", deflat_cursor, is_valid)
9 | PluginCommand.register_for_address("detx\\deflat2\\deflat nested", "deflat nested at current cursor", deflat_nested, is_valid)
10 | PluginCommand.register_for_address("detx\\deflat2\\deflat manual", "deflat use usr set value", deflat_manual, is_valid)
11 | PluginCommand.register_for_address("detx\\deflat2\\deflat with check", "deflat with extra check", deflat_with_check, is_valid)
12 |
13 | PluginCommand.register_for_address("detx\\dejmpreg\\dejmpreg here once", "remove jump reg obf here once", dejmpreg_cursor, is_valid)
14 | PluginCommand.register_for_address("detx\\dejmpreg\\dejmpreg manual", "remove jump reg manual here once", dejmpreg_manual, is_valid)
15 | PluginCommand.register_for_function("detx\\dejmpreg\\dejmpreg auto", "auto search jump reg insn", dejmpreg_auto, is_valid)
16 |
17 |
--------------------------------------------------------------------------------
/deflat2.py:
--------------------------------------------------------------------------------
1 | from binaryninja import *
2 | from binaryninja.log import Logger
3 | from .emulate import armDeflatEmulate
4 |
5 | from typing import List, Union
6 | from dataclasses import dataclass
7 |
8 | logger = Logger(0, "deflat2_log")
9 |
10 | @dataclass
11 | class PatchInfo:
12 | """一次patch信息
13 | """
14 | start: Optional[int] = None #patch起始地址
15 | pbytes: Optional[bytes] = None #要改成什么字节
16 | next: Optional['PatchInfo'] = None #下一个要改的信息 前向引用
17 |
18 | @dataclass
19 | class AssignBBInfo:
20 | """赋值块信息
21 | 包含块起始地址,
22 | 块对应switch变量值等
23 | """
24 | @dataclass
25 | class VarValueInfoTF:
26 | t_value: int
27 | f_value: int
28 | v_type: int #类型 0正常类型 1判断提前
29 | @dataclass
30 | class VarValueInfoU:
31 | u_value: int
32 |
33 | bb_start: Optional[int] = None #当前块起始地址
34 | set_var_addr: Optional[int] = None #当前块改变switch变量的指令的地址
35 | var_value: Optional[Union[VarValueInfoTF, VarValueInfoU]] = None #switch变量
36 | real_suc: Optional[List[int]] = None #真实后继地址信息 0是True 1是False分支
37 |
38 | #拿到[判断提前]类型的值
39 | def get_ahead_phi_value(arg_insn: MediumLevelILVarPhi):
40 | t_value_ = None
41 | f_value_ = None
42 | phi_insn = arg_insn
43 | while True:
44 | phi_insn_src = phi_insn.src
45 | if not hasattr(phi_insn_src, "src"):
46 | break
47 | phi_insn_src_var = phi_insn_src.src
48 | if not hasattr(phi_insn_src_var, "def_site"):
49 | break
50 | phi_insn = phi_insn_src_var.def_site
51 | if isinstance(phi_insn, MediumLevelILVarPhi) and (len(phi_insn.src) == 2):
52 | for phi_var in phi_insn.src:
53 | phivar_ainsn = phi_var.def_site
54 | branch_type = True if phivar_ainsn.il_basic_block.incoming_edges[0].type == BranchType.TrueBranch else False
55 | if branch_type == True:
56 | t_value_ = phivar_ainsn.src.constant
57 | else:
58 | f_value_ = phivar_ainsn.src.constant
59 | break
60 | return t_value_, f_value_
61 |
62 | #拿到[判断提前]类型的csel指令地址
63 | def get_ahead_csel_addr(func, arg_addr):
64 | csel_addr = None
65 |
66 | assign_insn_index = func.mlil.ssa_form.get_instruction_start(arg_addr)
67 | assign_insn = func.mlil.ssa_form[assign_insn_index]
68 | logger.log_debug(f"[判断提前]: {hex(arg_addr)} => {assign_insn}")
69 |
70 | use_insn_ = assign_insn
71 | if isinstance(use_insn_.il_basic_block[-1], MediumLevelILIf):
72 | use_insn_ = use_insn_.il_basic_block[-1]
73 |
74 | if isinstance(use_insn_, MediumLevelILIf):
75 | insn_index = use_insn_.true
76 | insn_ = func.mlil.ssa_form[insn_index]
77 | if insn_.dest.name == insn_.src.var.name:
78 | insn_index = use_insn_.false
79 | insn_ = func.mlil.ssa_form[insn_index]
80 | use_insn_ = insn_
81 |
82 | phi_insn = use_insn_
83 | while True:
84 | phi_insn_src = phi_insn.src
85 | if not hasattr(phi_insn_src, "src"):
86 | break
87 | phi_insn_src_var = phi_insn_src.src
88 | if not hasattr(phi_insn_src_var, "def_site"):
89 | break
90 | phi_insn = phi_insn_src_var.def_site
91 | if isinstance(phi_insn, MediumLevelILVarPhi) and (len(phi_insn.src) == 2):
92 | csel_addr = phi_insn.src[0].def_site.address
93 | break
94 | return csel_addr
95 |
96 | """
97 | 腾讯的控制流平坦化也是while(true) + switch(var)结构,
98 | 那么流程的分发一定是通过var这个switch变量, 因此反混淆逻辑是:
99 | 通过mlil层面拿到所有给var赋值的语句, 该语句所在的块就是真实块,
100 | 然后获取到当前块把var改成什么值了, 通过模拟执行该值会到达哪个块来确定后继块
101 | """
102 | def deflat2(bv: BinaryView, func: Function, switch_var_ssa: SSAVariable, extra_real_addr = None, manual_value = None, witch_check = False):
103 | #从mlil层面或者mlil ssa层面分析都可以, 我感觉ssa层面更方便一点
104 | loop_phi_var_insn = switch_var_ssa.def_site #循环分发开始的那个获取var值的指令
105 | if not isinstance(loop_phi_var_insn, MediumLevelILVarPhi):
106 | logger.log_error(f"错误的变量{switch_var_ssa}...")
107 | return
108 |
109 | init_sbb = [] #汇编层面的初始化块 初始化块就是初始化分发变量值的块 比如cmp w9, w22中的w22就是在初始化块中分配的值
110 | real_sbb = [] #汇编层面的真实块
111 | ret_sbb = [] #汇编层面的ret块
112 | dispatch_sbb = [] #汇编层面的分发块 (可能的 而且不一定全) 只是patch用
113 | loopEntry_sbb = loop_phi_var_insn.il_basic_block.source_block #汇编层面的循环分发开始的块
114 | assign_bb_infos: List[AssignBBInfo] = [] #存放赋值块对应的switch变量信息
115 |
116 | logger.log_info("[0] 开始获取真实块/初始化块/分发块等信息...")
117 | #用到了switch_var_ssa的if语句就是分发块
118 | for insn in switch_var_ssa.use_sites:
119 | if isinstance(insn, MediumLevelILIf):
120 | cur_mlil_ssa_bb = insn.il_basic_block
121 | dispatch_sbb.append(cur_mlil_ssa_bb.source_block)
122 | b_bb = []
123 | for bb in dispatch_sbb:
124 | for edge in bb.outgoing_edges:
125 | suc_bb = edge.target
126 | if (suc_bb.instruction_count == 1):
127 | insn_token = suc_bb[0][0] #bb的后继块指令
128 | if (insn_token[0].text)[0] == 'b': #如果是一个单独的b(.cc)的话
129 | b_bb.append(suc_bb)
130 | dispatch_sbb.extend(b_bb) #cmp块的下一个块 如果是b(.cc)的话也是分发块
131 |
132 | #循环分发开始块的前继块都是初始化块
133 | pre_bb = loopEntry_sbb
134 | found_bbs = [pre_bb]
135 | while True:
136 | incomes = pre_bb.incoming_edges
137 | if (len(incomes) == 0):
138 | break #没有前继了
139 | if (len(incomes) == 1):
140 | pre_bb = pre_bb.incoming_edges[0].source
141 | else: #如果有多个income, 找地址最小的那一个
142 | min_bb = incomes[0].source
143 | for edge in incomes:
144 | if (edge.source.start < min_bb.start):
145 | min_bb = edge.source
146 | pre_bb = min_bb
147 | if pre_bb in found_bbs:
148 | logger.log_debug("已搜索过的块 可能遇到循环...")
149 | break
150 | else:
151 | found_bbs.append(pre_bb)
152 |
153 | if pre_bb in dispatch_sbb:
154 | break
155 |
156 | last_insn_type = pre_bb[-1][0][0].text
157 | if last_insn_type[0] == 'b': #跳过的来 不是
158 | break
159 |
160 | init_sbb.append(pre_bb)
161 | if len(init_sbb) == 0:
162 | logger.log_error("未搜索到初始化块 分析出错!...")
163 | return
164 | elif len(init_sbb) >= 5:
165 | logger.log_warn(f"搜索到过多的初始化块{[hex(bb.start) for bb in init_sbb]} 分析可能出错!...")
166 | entry_bb = func.basic_blocks[0] #未防止意外情况 把entry块也加上
167 | if entry_bb not in init_sbb:
168 | init_sbb.append(entry_bb)
169 | init_sbb.reverse() #逆序 就是按地址从小到大排序的了
170 |
171 | #当前平坦化可能是嵌套的或者平行的 可能不具有ret块, 这里获取的ret块是全局的, 不影响, 只是为了当作一个可能的真实块
172 | for bb in func.basic_blocks:
173 | if len(bb.outgoing_edges) == 0:
174 | ret_sbb.append(bb) #没有后继就是ret块
175 |
176 | #获取获取赋值块 同时获取真实块的信息
177 | switch_vars = loop_phi_var_insn.src #所有用到的var的ssa变量
178 | logger.log_debug(f"switch变量赋值指令: {[var.def_site for var in switch_vars]}")
179 | for svar in switch_vars:
180 | assign_insn = svar.def_site #给当前ssa变量赋值的指令
181 | if assign_insn == loop_phi_var_insn:
182 | continue
183 | cur_ssa_bb = assign_insn.il_basic_block
184 | disasm_bb = cur_ssa_bb.source_block
185 | real_sbb.append(disasm_bb)
186 | #如果一个赋值块有两个(两个以上的情况还没遇到过)直接前继, 且其前继块不是分发块, 则其前继块也是真实块, 该赋值块是共用的
187 | if (len(disasm_bb.incoming_edges) == 2): #>2块共用也有可能 遇到再改
188 | pre_edge1 = disasm_bb.incoming_edges[0]
189 | pre_edge2 = disasm_bb.incoming_edges[1]
190 | if (pre_edge1.type == BranchType.UnconditionalBranch) and (pre_edge2.type == BranchType.UnconditionalBranch):
191 | pre_bb1 = pre_edge1.source
192 | pre_bb2 = pre_edge2.source
193 | if (pre_bb1 not in dispatch_sbb) and (pre_bb2 not in dispatch_sbb):
194 | real_sbb.append(pre_bb1)
195 | real_sbb.append(pre_bb2)
196 |
197 | cur_bb_info = AssignBBInfo()
198 | cur_bb_info.bb_start = cur_ssa_bb.source_block.start #赋值块起始地址
199 | cur_bb_info.set_var_addr = assign_insn.address #改变var值的指令的地址
200 | if isinstance(assign_insn, MediumLevelILSetVarSsa): #说明不是分支
201 | value_ = None
202 | var_value_info = None
203 | if isinstance(assign_insn.src, MediumLevelILVarSsa): #x9_2 = x9_1; 判断提前
204 | t_value_ = None #需要拿到真正的var值
205 | f_value_ = None
206 | t_value_, f_value_ = get_ahead_phi_value(assign_insn)
207 | if None in [t_value_, f_value_]:
208 | logger.log_error(f"[判断提前]类型指令分析失败:{hex(assign_insn.address)} => {assign_insn}")
209 | return
210 | var_value_info = AssignBBInfo.VarValueInfoTF(t_value=t_value_, f_value=f_value_, v_type=1)
211 | elif isinstance(assign_insn.src, MediumLevelILConst):
212 | value_ = assign_insn.src.constant
213 | var_value_info = AssignBBInfo.VarValueInfoU(u_value=value_)
214 | cur_bb_info.var_value = var_value_info
215 |
216 | elif isinstance(assign_insn, MediumLevelILVarPhi) and (len(assign_insn.src) == 2):#x9_2#20 = ϕ(x9_2#18, x9_2#19)
217 | t_value_ = None
218 | f_value_ = None
219 | var_value_info = None
220 | for phi_var in assign_insn.src:
221 | phivar_ainsn = phi_var.def_site
222 | cur_bb_info.set_var_addr = phivar_ainsn.address #更新改变var值的指令的地址 phi指令用这个地址才是对应的汇编层面的csel或者其他赋值指令
223 | branch_type = True if phivar_ainsn.il_basic_block.incoming_edges[0].type == BranchType.TrueBranch else False
224 | ainsn_src_ope = phivar_ainsn.src.operands[0]
225 | if isinstance(ainsn_src_ope, SSAVariable): #这种类型: [x9#3 = 0x2e3a7efe | x9#4 = x9#2] -> csel w9, w24, w9, eq相当于mov w9, w24
226 | if (phivar_ainsn.dest.name == ainsn_src_ope.name):
227 | continue
228 | else: #这种类型 [x14_1#8 = x15_1#5 | x14_1#9 = x14_1#3] -> csel w14, w15, w14, eq 还是判断提前
229 | t_value_, f_value_ = get_ahead_phi_value(phivar_ainsn)
230 | if None in [t_value_, f_value_]:
231 | logger.log_error(f"[判断提前]类型指令分析失败:{hex(assign_insn.address)} => {assign_insn}")
232 | return
233 | var_value_info = AssignBBInfo.VarValueInfoTF(t_value=t_value_, f_value=f_value_, v_type=1)
234 | break
235 | elif isinstance(ainsn_src_ope, int):
236 | if branch_type == True:
237 | t_value_ = ainsn_src_ope
238 | else:
239 | f_value_ = ainsn_src_ope
240 | if var_value_info == None:
241 | if None in [t_value_, f_value_]: #存在None则说明是直接类型
242 | value_ = t_value_ if t_value_ != None else f_value_
243 | var_value_info = AssignBBInfo.VarValueInfoU(u_value=value_)
244 | else:
245 | var_value_info = AssignBBInfo.VarValueInfoTF(t_value=t_value_, f_value=f_value_, v_type=0)
246 | cur_bb_info.var_value = var_value_info
247 | else:
248 | logger.log_error("未知switch变量赋值指令类型...")
249 | return
250 | assign_bb_infos.append(cur_bb_info)
251 | if (extra_real_addr != None): #添加用户额外设置的真实块地址
252 | extra_sbb = func.get_basic_block_at(extra_real_addr)
253 | real_sbb.append(extra_sbb)
254 |
255 |
256 | #可选 把分发块的后继块当作真实块(如果一个函数有多个平坦化的话就需要这样 但这样获取的信息不一定是正确的)
257 | if witch_check:
258 | for bb in dispatch_sbb:
259 | for edge in bb.outgoing_edges:
260 | suc_bb = edge.target
261 | if (suc_bb not in dispatch_sbb) and (suc_bb not in init_sbb):
262 | if (suc_bb not in real_sbb) and (suc_bb not in ret_sbb):
263 | if (suc_bb != loopEntry_sbb): #且如果是b.ne/b.eq的话 则必须分别是false/true分支
264 | correct_bb = None
265 | bcc_type = dispatch_sbb[-1][0][0]
266 | if bcc_type == 'b.ne':
267 | correct_bb = dispatch_sbb.outgoing_edges[1].target #FalseBranch
268 | elif bcc_type == 'b.eq':
269 | correct_bb = dispatch_sbb.outgoing_edges[0].target #TrueBranch
270 | if (correct_bb == None) or (correct_bb == suc_bb):
271 | real_sbb.append(suc_bb)
272 | logger.log_warn("[!] 当前会使用分发块的后继块当作真实块 此行为可能导致分析错误!")
273 |
274 | logger.log_info("[0] 获取信息完毕!")
275 | logger.log_debug(f"init_sbb: {init_sbb}")
276 | logger.log_debug(f"real_sbb: {real_sbb}")
277 | logger.log_debug(f"ret_sbb: {ret_sbb}")
278 | logger.log_debug(f"dispatch_sbb: {dispatch_sbb}")
279 | logger.log_debug(f"loopEntry_sbb: {loopEntry_sbb}")
280 | logger.log_debug(f"assign_bb_infos: {assign_bb_infos}")
281 | common_sbb = []
282 | for bb in real_sbb:
283 | if bb in dispatch_sbb:
284 | common_sbb.append(bb)
285 | logger.log_debug(f"common_sbb: {common_sbb}")
286 |
287 | i = 0
288 | log_msg_ = ""
289 | for info in assign_bb_infos:
290 | log_msg_ += f"({i:02d}) {hex(info.bb_start)}"
291 | if isinstance(info.var_value, AssignBBInfo.VarValueInfoU):
292 | log_msg_ += f" ---> {hex(info.var_value.u_value)}"
293 | elif isinstance(info.var_value, AssignBBInfo.VarValueInfoTF):
294 | log_msg_ += f" --t-> {hex(info.var_value.t_value)}\n"
295 | log_msg_ += f"({i:02d}) \t╰--f-> {hex(info.var_value.f_value)}"
296 | log_msg_ += "\n"
297 | i += 1
298 | logger.log_debug(f"真实块的switch值:\n{log_msg_}")
299 |
300 | logger.log_info("[1] 开始模拟执行获取块之间后继关系...")
301 | #开始模拟执行!
302 | deflat_emu = armDeflatEmulate() #模拟执行器
303 | # 0. 写入机器码 同时调用init块中的指令进行初始化
304 | func_start_addr = func.start
305 | func_end_addr = func.highest_address + 1
306 | func_bytes = bv.read(func_start_addr, func_end_addr - func_start_addr) #读取当前函数的机器码
307 | asm_bytes_noped = bytearray(func_bytes) #把init块机器码中的call都nop掉
308 | for bb in init_sbb:
309 | insn_addr = bb.start
310 | for insn in bb:
311 | insn_len = insn[-1]
312 | insn_type = insn[0][0].text
313 | if insn_type == 'bl':
314 | offset_in_bytes = insn_addr - func_start_addr
315 | nop_bytes = '\x00' * insn_len
316 | nop_bytes = bv.arch.convert_to_nop(nop_bytes, insn_addr)
317 | i = 0
318 | for b in nop_bytes:
319 | asm_bytes_noped[offset_in_bytes + i] = b
320 | i += 1
321 | insn_addr += insn_len
322 | func_bytes = bytes(asm_bytes_noped)
323 | deflat_emu.init_func_emu(func_start_addr, func_end_addr - func_start_addr)
324 | deflat_emu.write_func_opcode(func_bytes) # 写入到emu内存中
325 |
326 | for bb in init_sbb:#执行init块的指令 (去掉了call)
327 | end_addr = bb.end
328 | last_insn_type = (bb[-1][0][0].text)[0]
329 | if last_insn_type == 'b':
330 | end_addr -= bb[-1][-1]
331 | deflat_emu.init_reg_stack(bb.start, end_addr)
332 |
333 | # 1. 设置分发寄存器 (一般来讲是寄存器, 腾讯这个用的都是cmp w9, w22这种, 没见过用栈的)
334 | mlil_var = switch_var_ssa.var
335 | if (mlil_var.source_type != VariableSourceType.RegisterVariableSourceType):
336 | logger.log_error("未处理的情况{mlil_var}, 分发变量不是寄存器!")
337 | return
338 | dispatch_reg = bv.arch.get_reg_name(mlil_var.storage)
339 | deflat_emu.set_switch_var(dispatch_reg)
340 |
341 | # 2. 设置模拟执行循环开始地址
342 | loopEntry_begin = loopEntry_sbb.start #分发开始的地址
343 | deflat_emu.set_switch_begin_addr(loopEntry_begin) #每次模拟都从此地址开始模拟执行
344 |
345 | # 3. 设置模拟停止地址(真实块地址)
346 | stop_addrs = []
347 | for bb in real_sbb:
348 | stop_addrs.append(bb.start)
349 | for bb in ret_sbb:
350 | stop_addrs.append(bb.start)
351 | deflat_emu.set_stop_addrs(stop_addrs)
352 |
353 | # 4. 获取赋值块的真实后继地址
354 | if (manual_value != None):
355 | deflat_emu.set_switch_var_value(manual_value)
356 | logger.log_info(f"[*] 已设置{dispatch_reg}为: {hex(deflat_emu.reg_value(dispatch_reg))}")
357 | suc_addr = deflat_emu.start_until_stop()
358 | logger.log_info(f"[*] 当值为 {hex(manual_value)} 时 会到达---> {hex(suc_addr)}")
359 | return
360 | else:
361 | cmp_regs = {}
362 | if witch_check: #获取各个分发寄存器的初始值
363 | for bb in dispatch_sbb:
364 | index = 0
365 | for insn_info in bb:
366 | if insn_info[0][0].text == 'cmp':
367 | wreg_name = insn_info[0][-2].text
368 | if (bb[index - 1][0][0].text == 'movk') and (bb[index - 1][0][2].text == wreg_name):
369 | pass #当前分发寄存器的初始值不是在init块中初始化的 是在当前块中赋值的
370 | else:
371 | xreg_name = 'x' + wreg_name[1:]
372 | cmp_regs[xreg_name] = 0
373 | index += 1
374 | for reg in cmp_regs:
375 | cmp_regs[reg] = deflat_emu.reg_value(reg)
376 | logger.log_info(f"[C] {reg} 初始值: {hex(cmp_regs[reg])}")
377 |
378 | for info in assign_bb_infos:
379 | if witch_check: #每次进入分发逻辑之前初始化分发寄存器的值
380 | for reg in cmp_regs:
381 | cur_value = deflat_emu.reg_value(reg)
382 | if cur_value != cmp_regs[reg]:
383 | logger.log_warn(f"[C] 当前分发寄存器{reg}的值为 {hex(cur_value)} =将改为初始值=> {hex(cmp_regs[reg])}")
384 | deflat_emu.reg_value(reg, cmp_regs[reg])
385 |
386 | var_value = info.var_value
387 | real_sucs_ = []
388 | #logger.log_warn(f"在 {hex(info.bb_start)} 前 w10: {hex(deflat_emu.reg_value('w10'))}")
389 | if isinstance(var_value, AssignBBInfo.VarValueInfoU): #只有一条赋值语句
390 | deflat_emu.set_switch_var_value(var_value.u_value)
391 | suc_addr = deflat_emu.start_until_stop()
392 | real_sucs_.append(suc_addr)
393 |
394 | elif isinstance(var_value, AssignBBInfo.VarValueInfoTF): #有两个赋值语句
395 | deflat_emu.set_switch_var_value(var_value.t_value)
396 | suc_addr = deflat_emu.start_until_stop()
397 | real_sucs_.append(suc_addr)
398 |
399 | deflat_emu.set_switch_var_value(var_value.f_value)
400 | suc_addr = deflat_emu.start_until_stop()
401 | real_sucs_.append(suc_addr)
402 | #logger.log_warn(f"在 {hex(info.bb_start)} 后 w10: {hex(deflat_emu.reg_value('w10'))}")
403 | info.real_suc = real_sucs_
404 | # 5. 打印输出
405 | i = 0
406 | log_msg_ = ""
407 | for info in assign_bb_infos:
408 | log_msg_ += f"({i:02d}) {hex(info.bb_start)}"
409 | if isinstance(info.var_value, AssignBBInfo.VarValueInfoU):
410 | log_msg_ += f" ---> {hex(info.real_suc[0])}"
411 | elif isinstance(info.var_value, AssignBBInfo.VarValueInfoTF):
412 | log_msg_ += f" --t-> {hex(info.real_suc[0])}\n"
413 | log_msg_ += f"({i:02d}) \t╰--f-> {hex(info.real_suc[1])}"
414 | log_msg_ += "\n"
415 | i += 1
416 | logger.log_info(f"[1] 模拟执行结束, 块之间后继关系:\n{log_msg_}")
417 |
418 | #如果有后继是loopEntry的 则说明分析失败
419 | for info in assign_bb_infos:
420 | for suc in info.real_suc:
421 | if suc == loopEntry_begin:
422 | logger.log_error(f"[!] 地址: {hex(info.bb_start)} 处后继分析失败! {hex(loopEntry_begin)}")
423 | return
424 |
425 | #开始Patch!
426 | PatchAssignBB(bv, func, assign_bb_infos, real_sbb, dispatch_sbb)
427 |
428 |
429 | def PatchAssignBB(bv: BinaryView, func: Function, abb_infos: List[AssignBBInfo], real_bb, dispatch_bb):
430 | logger.log_info("[2] 开始获取Patch信息...")
431 | #可用的无用块, 可用于提供额外的patch空间
432 | useless_bb = []
433 | for bb in dispatch_bb: #防止分发块和真实块共用的情况
434 | if bb not in real_bb:
435 | useless_bb.append(bb)
436 |
437 | #因为patch会改变CFG图 所以先记录要patch的信息 再统一patch
438 | patch_infos = []
439 | for info in abb_infos:
440 | cur_bb = bv.get_basic_blocks_at(info.bb_start)[0]
441 | suc_addrs = info.real_suc #后继地址
442 | patch_info = PatchInfo()
443 | last_insn_addr = cur_bb.end - cur_bb[-1][-1] #当前块最后一个指令的起始地址
444 | pbytes = b'' #要patch成的字节
445 | if len(suc_addrs) == 1:#一个就直接把末尾的b指令改了
446 | patch_start_addr = None
447 | insn_type = cur_bb[-1][0][0].text
448 | if (insn_type != 'b'): #末尾指令不是跳转指令
449 | next_bb = cur_bb.outgoing_edges[0].target #看看紧邻的后继块是不是在useless块中
450 | if next_bb in useless_bb: #将后继块patch成b ... + nop
451 | relative_addr = suc_addrs[0] - next_bb.start
452 | pbytes = bv.arch.assemble(f"b {hex(relative_addr)}", next_bb.start)
453 | nop_bytes = b'\x00' * (next_bb.length - len(pbytes))
454 | nop_bytes = bv.arch.convert_to_nop(nop_bytes, next_bb.start + len(pbytes))
455 | pbytes += nop_bytes
456 |
457 | useless_bb.remove(next_bb) #删除
458 | else:
459 | logger.log_error(f"未处理情况, 赋值块{cur_bb}的后继{next_bb}不是uesless块, 无法patch!")
460 | return
461 | patch_start_addr = next_bb.start
462 | else:
463 | relative_addr = suc_addrs[0] - last_insn_addr
464 | pbytes = bv.arch.assemble(f"b {hex(relative_addr)}", last_insn_addr)
465 | patch_start_addr = last_insn_addr
466 | patch_info.start = patch_start_addr
467 | patch_info.pbytes = pbytes
468 | elif len(suc_addrs) == 2: #两个要分情况
469 | if (info.var_value.v_type == 0): #正常类型
470 | csel_token = bv.get_disassembly(info.set_var_addr).split() #例如['csel', 'w20,', 'w8,', 'w10,', 'eq']
471 | if csel_token[0] != 'csel': #不是csel的情况还没遇到过
472 | logger.log_error(f"未处理的patch情况!{hex(info.set_var_addr)} => {csel_token}")
473 | return
474 | llast_insn_addr = last_insn_addr - cur_bb[-2][-1] #倒数第二个指令地址
475 | if llast_insn_addr != info.set_var_addr:#如果不是倒数第二个的话就要去移动
476 | logger.log_warn(f"csel指令不是当前块的倒数第二个指令!{hex(info.set_var_addr)} != {hex(llast_insn_addr)}")
477 | logger.log_warn(f"[!] 将会重新移动构造对应指令, 结果可能出错!...")
478 | #拿到csel到b的指令(不包括这两个指令) 相当于把csel-b之间的指令提前了: insns csel b
479 | mid_insn_start = info.set_var_addr + bv.get_instruction_length(info.set_var_addr)
480 | block_insn_bytes = bv.read(mid_insn_start, last_insn_addr - mid_insn_start)
481 | pbytes = block_insn_bytes
482 | bcc_type = "b." + csel_token[-1]
483 | relative_addr = suc_addrs[0] - info.set_var_addr #b.cc t_addr
484 | bcc_insn_bytes = bv.arch.assemble(f"{bcc_type} {hex(relative_addr)}", info.set_var_addr)
485 | relative_addr = suc_addrs[1] - last_insn_addr #b f_addr
486 | b_insn_bytes = bv.arch.assemble(f"b {hex(relative_addr)}", last_insn_addr)
487 | pbytes += bcc_insn_bytes + b_insn_bytes
488 | patch_info.start = info.set_var_addr
489 | patch_info.pbytes = pbytes
490 | elif (info.var_value.v_type == 1): #判断提前
491 | #我的思路是 条件传递:csel改为cset 后面判断01
492 | # 1. 拿到提前的csel指令地址 并改为cset
493 | csel_addr = get_ahead_csel_addr(func, info.set_var_addr)
494 | ahead_csel_token = bv.get_disassembly(csel_addr).split()
495 | ahead_csel_cond = ahead_csel_token[-1] #csel的最后的条件
496 | ahead_csel_reg = ahead_csel_token[1][:-1] #csel设置的寄存器
497 | if ahead_csel_token[0] != 'csel':
498 | logger.log_error(f"分析错误, {hex(csel_addr)}并不是提前的csel指令!")
499 | return
500 | new_cset_bytes = bv.arch.assemble(f"cset {ahead_csel_reg}, {ahead_csel_cond}")
501 | # 2. 找分发块(因为分发块已经无用了) 存放(cmp ahead_csel_reg, #0x1) + (b.ahead_csel_cond t_addr) + (b f_addr)
502 | chain_bb = None
503 | for bb in useless_bb: #先找能存放3个指令的分发块
504 | if bb.instruction_count >= 3:
505 | chain_bb = bb
506 | break
507 | if chain_bb == None: #如果没有的话, 就随便找三个能存放2个指令的分发快(最后一个块可以只存放一个指令)
508 | chain_bb = []
509 | for bb in useless_bb:
510 | if bb.instruction_count >= 2:
511 | chain_bb.append(bb)
512 | if len(chain_bb) == 2:
513 | break
514 | useless_bb = [bb for bb in useless_bb if bb not in chain_bb]#删除对应元素
515 | for bb in useless_bb:
516 | if bb.instruction_count >= 1:
517 | chain_bb.append(bb)
518 | useless_bb.remove(bb)
519 | break
520 | # 3. 获取patch分发块信息
521 | patch_info.start = csel_addr #第一个patch
522 | patch_info.pbytes = new_cset_bytes
523 | if isinstance(chain_bb, list): #一个块放不下就分成三个块
524 | if len(chain_bb) < 3:
525 | logger.log_error(f"分发块的数量不足以提供足够的Patch空间!:{useless_bb}")
526 | return
527 | logger.log_debug(f"[判断提前] 将拆成三个块{[hex(bb.start) for bb in chain_bb]}写入Patch信息...")
528 | chain_bb1 = chain_bb[0]
529 | first_patch = PatchInfo()
530 | first_patch.start = last_insn_addr
531 | first_patch.pbytes = bv.arch.assemble(f"b {hex(chain_bb1.start - last_insn_addr)}", last_insn_addr)
532 | patch_info.next = first_patch
533 |
534 | chain_bb2 = chain_bb[1]
535 | second_patch = PatchInfo()
536 | second_patch.start = chain_bb1.start
537 | new_insn_cur_addr = chain_bb1.start
538 | second_bytes = bv.arch.assemble(f"cmp {ahead_csel_reg}, #0x1", new_insn_cur_addr)
539 | new_insn_cur_addr += len(second_bytes)
540 | second_bytes += bv.arch.assemble(f"b {chain_bb2.start - new_insn_cur_addr}", new_insn_cur_addr)
541 | second_patch.pbytes = second_bytes
542 | first_patch.next = second_patch
543 |
544 | chain_bb3 = chain_bb[2]
545 | third_patch = PatchInfo()
546 | third_patch.start = chain_bb2.start
547 | new_insn_cur_addr = chain_bb2.start
548 | third_bytes = bv.arch.assemble(f"b.{ahead_csel_cond} {hex(suc_addrs[0] - new_insn_cur_addr)}", new_insn_cur_addr)
549 | new_insn_cur_addr += len(third_bytes)
550 | third_bytes += bv.arch.assemble(f"b {chain_bb3.start - new_insn_cur_addr}", new_insn_cur_addr)
551 | third_patch.pbytes = third_bytes
552 | second_patch.next = third_patch
553 |
554 | fourth_patch = PatchInfo()
555 | fourth_patch.start = chain_bb3.start
556 | new_insn_cur_addr = chain_bb3.start
557 | fourth_bytes = bv.arch.assemble(f"b {hex(suc_addrs[1] - new_insn_cur_addr)}", new_insn_cur_addr)
558 | new_insn_cur_addr += len(fourth_bytes)
559 | nop_len = chain_bb3.length - len(fourth_bytes)
560 | nop_bytes = b'\x00' * nop_len
561 | nop_bytes = bv.arch.convert_to_nop(nop_bytes, new_insn_cur_addr)
562 | if nop_bytes != None:
563 | fourth_bytes += nop_bytes
564 | fourth_patch.pbytes = fourth_bytes
565 | third_patch.next = fourth_patch
566 |
567 | else:#一个块就放得下
568 | first_patch = PatchInfo()
569 | first_patch.start = last_insn_addr
570 | first_patch.pbytes = bv.arch.assemble(f"b {hex(chain_bb.start - last_insn_addr)}", last_insn_addr)
571 | patch_info.next = first_patch
572 |
573 | new_insn_cur_addr = chain_bb.start
574 | new_insn = bv.arch.assemble(f"cmp {ahead_csel_reg}, #0x1", new_insn_cur_addr)
575 | new_insn_cur_addr += len(new_insn)
576 | new_insn += bv.arch.assemble(f"b.{ahead_csel_cond} {hex(suc_addrs[0] - new_insn_cur_addr)}", new_insn_cur_addr)
577 | new_insn_cur_addr += len(new_insn)
578 | new_insn += bv.arch.assemble(f"b {hex(suc_addrs[1] - new_insn_cur_addr)}", new_insn_cur_addr)
579 | second_patch = PatchInfo()
580 | second_patch.start = chain_bb.start
581 | second_patch.pbytes = new_insn
582 | first_patch.next = second_patch
583 |
584 | patch_infos.append(patch_info)
585 | #打印输出
586 | i = 0
587 | log_msg_ = ""
588 | for patch_info in patch_infos:
589 | one_patch = f"({i:02d}) [addr: {hex(patch_info.start)} patch: ({patch_info.pbytes})]"
590 | next_info = patch_info.next
591 | while next_info != None:
592 | one_patch += f" --> [addr: {hex(next_info.start)} patch: ({next_info.pbytes})]"
593 | next_info = next_info.next
594 | log_msg_ += (one_patch + "\n")
595 | i += 1
596 | logger.log_info(f"[2] Patch信息获取完毕:\n{log_msg_}")
597 |
598 |
599 | #开始写入!
600 | logger.log_info("[3] 开始写入Patch数据...")
601 | state = bv.begin_undo_actions()
602 | for patch_info in patch_infos:
603 | cur_patch = patch_info
604 | while cur_patch != None:
605 | bv.write(cur_patch.start, cur_patch.pbytes)
606 | cur_patch = cur_patch.next
607 | bv.commit_undo_actions(state)
608 | logger.log_info("[3] 写入Patch数据完成!")
609 |
610 | #以下可写可不写 不影响分析
611 | """
612 | logger.log_info("开始Patch无用块为nop...")
613 | state = bv.begin_undo_actions()
614 | for ubb in useless_bb:
615 | start_addr = ubb.start
616 | nop_bytes = b'\x00' * (ubb.length)
617 | nop_bytes = bv.arch.convert_to_nop(nop_bytes, start_addr)
618 | bv.write(start_addr,nop_bytes)
619 | bv.commit_undo_actions(state)
620 | logger.log_info("Patch无用块为nop完成!")
621 | """
622 |
623 | def get_address_switch_var(func: Function, address: int):
624 | cursor_mlil_ssa_bb = None #当前的mlil ssa视图中的bb
625 | mlil_ssa_func = func.mlil.ssa_form
626 | for bb in mlil_ssa_func.basic_blocks:
627 | bb_addrs = [insn.address for insn in bb]
628 | if address in bb_addrs:
629 | cursor_mlil_ssa_bb = bb
630 | break
631 | if cursor_mlil_ssa_bb != None:
632 | if_insn = None
633 | for insn in cursor_mlil_ssa_bb:#找if指令
634 | if isinstance(insn, MediumLevelILIf):
635 | if_insn = insn
636 | break
637 | if if_insn != None:
638 | ssa_var = None
639 | cond_ = if_insn.condition
640 | if isinstance(cond_, MediumLevelILComparisonBase):#if (x9#2 s>= 0x2e3a7efe)
641 | ssa_var = cond_.vars_read[0]
642 | elif isinstance(cond_, MediumLevelILVarSsa): #if (cond:1#1)
643 | cond_insn = cond_.src.def_site
644 | ssa_var = cond_insn.src.vars_read[0]
645 | if ssa_var != None:
646 | return ssa_var
647 | return None
648 |
649 | def deflat_cursor(bv: BinaryView, address: int):
650 | target_func = bv.get_functions_containing(address)[0]#获取当前用户点击的函数
651 | swtich_ssa_var = get_address_switch_var(target_func, address)
652 | if swtich_ssa_var != None:
653 | deflat2(bv, target_func, swtich_ssa_var)
654 | else:
655 | interaction.show_message_box("提示", "当前位置不存在switch var变量!\n请在Medium Level IL SSA视图中查找")
656 |
657 | # 去除嵌套平坦化 需要手动设置出口地址
658 | def deflat_nested(bv: BinaryView, address: int):
659 | target_func = bv.get_functions_containing(address)[0]#获取当前用户点击的函数
660 | swtich_ssa_var = get_address_switch_var(target_func, address)
661 | if swtich_ssa_var != None:
662 | usr_input = interaction.get_address_input("请在下方输入当前平坦化循环的出口地址:", "输入出口地址")
663 | if usr_input != None:
664 | extra_sbb = target_func.get_basic_block_at(usr_input)
665 | if (extra_sbb != None):
666 | logger.log_info(f"使用用户输入的出口地址: {hex(usr_input)}")
667 | deflat2(bv, target_func, swtich_ssa_var, usr_input)
668 | else:
669 | logger.log_error(f"用户输入{hex(usr_input)}无效 不是一个basicblock")
670 | else:
671 | logger.log_warn("用户取消输入")
672 | else:
673 | interaction.show_message_box("提示", "当前位置不存在switch var变量!\n请在Medium Level IL SSA视图中查找")
674 |
675 | # 每次循环都会将分发变量设置为初始值 且会将分发块的后继块当作真实块
676 | def deflat_with_check(bv: BinaryView, address: int):
677 | target_func = bv.get_functions_containing(address)[0]#获取当前用户点击的函数
678 | swtich_ssa_var = get_address_switch_var(target_func, address)
679 | if swtich_ssa_var != None:
680 | deflat2(bv, target_func, swtich_ssa_var, None, None, True)
681 | else:
682 | interaction.show_message_box("提示", "当前位置不存在switch var变量!\n请在Medium Level IL SSA视图中查找")
683 |
684 | # 手动设置switch变量的值 用于调试
685 | def deflat_manual(bv: BinaryView, address: int):
686 | target_func = bv.get_functions_containing(address)[0]#获取当前用户点击的函数
687 | swtich_ssa_var = get_address_switch_var(target_func, address)
688 | if swtich_ssa_var != None:
689 | switch_var_value = interaction.get_int_input("输入要设置的switch变量的值:", "手动设置switch变量值")
690 | if (switch_var_value == None):
691 | logger.log_error("未输入值 取消执行...")
692 | return
693 |
694 | deflat2(bv, target_func, swtich_ssa_var, None, switch_var_value)
695 | else:
696 | interaction.show_message_box("提示", "当前位置不存在switch var变量!\n请在Medium Level IL SSA视图中查找")
697 |
--------------------------------------------------------------------------------
/deineffective.py:
--------------------------------------------------------------------------------
1 | #待定
--------------------------------------------------------------------------------
/dejmpreg.py:
--------------------------------------------------------------------------------
1 | from binaryninja import *
2 | from binaryninja.log import Logger
3 | from .emulate import armDeJmpRegEmulate
4 |
5 | import time
6 |
7 | logger = Logger(0, "dejmpreg_log")
8 |
9 | #递归通过搜索变量的def_site来拿到所有涉及到的指令
10 | def get_involve_insns(jmp_insn: MediumLevelILJump):
11 | def get_right_ssa_var(expr, vars: list):
12 | if isinstance(expr, SSAVariable):
13 | vars.append(expr)
14 | return
15 | elif isinstance(expr, list):
16 | for ope in expr:
17 | if isinstance(ope, SSAVariable):
18 | vars.append(ope)
19 | return
20 |
21 | if hasattr(expr, 'operands'):
22 | for ope in expr.operands:
23 | get_right_ssa_var(ope, vars)
24 | return
25 |
26 | involve_insns = [] #涉及到的指令
27 | jmp_var = jmp_insn.dest.var
28 | var_stack = []
29 | var_stack.append(jmp_var)
30 | while len(var_stack) != 0: #拿到一次寄存器间接跳转混淆涉及到的所有指令
31 | cur_ssa_var = var_stack.pop()
32 | insn_ = cur_ssa_var.def_site #一条指令 应该是MediumLevelILSetVarSsa或MediumLevelILVarPhi
33 | if insn_ == None:
34 | break
35 |
36 | if isinstance(insn_, MediumLevelILVarPhi): # 如果遇到phi了且不是2个或2个地址不一样, 则取最小的
37 | addr_list = []
38 | for v in insn_.src:
39 | addr_list.append(v.def_site.address)
40 | if (len(addr_list) != 2) or (len(set(addr_list)) != 1):
41 | min_index = addr_list.index(min(addr_list))
42 | insn_ = insn_.src[min_index].def_site
43 | # 或者直接就停止
44 | """
45 | break
46 | """
47 |
48 | if insn_ in involve_insns:
49 | break #如果拿到的指令已经在之前获取到的指令中了, 说明遇到循环了
50 | else:
51 | involve_insns.append(insn_) #添加涉及到的指令
52 |
53 | if 'cond' in insn_.dest.name:#遇到cond:20#1 = x8#2 == 0x586b6221这种就不再继续了 要不然有可能遇到phi节点导致死循环
54 | break
55 |
56 |
57 | insn_right = insn_.src #这条指令=右边的表达式
58 | get_right_ssa_var(insn_right, var_stack) #拿到表达式中的变量
59 |
60 | return involve_insns
61 |
62 | # 这种混淆就是把跳转改为了jmp(var2)
63 | # 其中var2 = mem[var1 (<< num)] + const 这些值其实都是可以确定的, 例如:
64 | # if (Cond)
65 | # var1 = 0;
66 | # else
67 | # var1 = 1;
68 | # var2 = data_1fd630[var1];
69 | # var3 = var2 - 0x7218df2;
70 | # jump(var3);
71 |
72 | # 反混淆的话, 我的思路是静态分析+模拟执行:
73 | # 从mlil ssa层面, 可以获取到jump变量var的指令
74 | # 然后层层向上找, 找到所有涉及到的指令,
75 | # 然后拿到这些指令对应的汇编指令模拟执行.
76 | def dejmpreg(bv: BinaryView, func: Function, jmp_insn: MediumLevelILJump, emulator: armDeJmpRegEmulate, manual_value = None):
77 | mlil_ssa_func = func.mlil.ssa_form
78 | mlil_ssa_bb = jmp_insn.il_basic_block
79 | jmp_dest_var = jmp_insn.dest.var.var
80 | jmp_reg = bv.arch.get_reg_name(jmp_dest_var.storage)
81 | jmp_insn_addr = jmp_insn.address
82 | logger.log_info(f"开始分析 {hex(jmp_insn_addr)}...")
83 |
84 | #拿到涉及到的所有指令
85 | involve_insns = get_involve_insns(jmp_insn)
86 | logger.log_debug(f"involve_insns: {involve_insns}")
87 | # 判断指令中是否有arg字样, 有则说明有大概率是分析错了(可能是ninja把不该识别成函数的地址识别成函数了, 也可能是脚本分析错了), 需要手动分析
88 | if manual_value == None:
89 | arg_insn = None
90 | for insn in involve_insns:
91 | insn_token = insn.tokens
92 | for t in insn_token: #InstructionTextToken
93 | if 'arg' in t.text:
94 | arg_insn = insn
95 | break
96 | if arg_insn != None:
97 | break
98 | if arg_insn != None:
99 | result = interaction.show_message_box("提示", f"发现参数传值:{arg_insn}, 可能分析错误, 是否停止分析?", MessageBoxButtonSet.YesNoButtonSet, MessageBoxIcon.QuestionIcon)
100 | if result == MessageBoxButtonResult.YesButton:
101 | logger.log_warn("停止自动分析, 可手动设置条件选择指令设置的值(dejmpreg_manual)...")
102 | return None, None
103 |
104 | involve_asm_addrs = [] #涉及到的汇编指令的地址 可能少csx赋值指令 后面补上
105 | for mlssa_insn in involve_insns:
106 | llil_insns = mlssa_insn.llils
107 | for insn_ in llil_insns:
108 | if insn_.address not in involve_asm_addrs:
109 | involve_asm_addrs.append(insn_.address)
110 | logger.log_debug(f"involve_asm_addrs: {[hex(x) for x in involve_asm_addrs]}")
111 |
112 | #找到csel/cset/csinc指令以及指令地址
113 | condition_insn_names = ['csel', 'cset', 'csinc', 'cinc', 'csetm', 'csinv', 'csneg']
114 | condition_insn_addr = 0
115 | insn_token = None
116 | for addr in involve_asm_addrs:
117 | tmp_token = (bv.get_disassembly(addr)).split()
118 | if tmp_token[0] in condition_insn_names:
119 | insn_token = tmp_token
120 | condition_insn_addr = addr
121 | break
122 | if insn_token == None:
123 | logger.log_error(f"未找到{condition_insn_names}指令!")
124 | return None, None
125 | # 拿到csel/cset/csinc/cinc等指令设置的三个寄存器
126 | cond_set_value = []#true和false分支 要设置的值/寄存器
127 | cond_set_reg = insn_token[1][:-1] #去掉,
128 | if insn_token[0] == 'cset':
129 | cond_set_value = [1, 0]
130 | elif insn_token[0] == 'cinc':
131 | cond_set_value = [insn_token[2][:-1], insn_token[2][:-1]]
132 | elif insn_token[0] == 'csetm':
133 | cond_set_value = [-1, 0]
134 | else:
135 | cond_set_value = [insn_token[2][:-1], insn_token[3][:-1]]
136 | logger.log_debug(f"csx:{insn_token[0]} | csx addr: {hex(condition_insn_addr)} | csx value: {cond_set_value}")
137 |
138 | #拿到给csx的两个变量赋值的指令地址
139 | csx_var_addrs = []
140 | if (insn_token[0] != 'cset'):
141 | tmp_addrs = []
142 | for insn in involve_insns:
143 | if isinstance(insn, MediumLevelILVarPhi) and (len(insn.src) == 2):
144 | phi_var1 = insn.src[0].def_site
145 | phi_var2 = insn.src[1].def_site
146 | for llil in phi_var1.llils:
147 | tmp_addrs.append(llil.address)
148 | for llil in phi_var2.llils:
149 | tmp_addrs.append(llil.address)
150 | break
151 | for addr in tmp_addrs:
152 | token = (bv.get_disassembly(addr)).split()
153 | if (token[0] == 'mov') and (addr not in csx_var_addrs):
154 | csx_var_addrs.append(addr)
155 | # 如果csx赋值指令为空, 可能是cset, 也可能是某些原因(比如entry块复制)导致拿到的地址不全
156 | if (len(csx_var_addrs) == 0) and (insn_token[0] != 'cset'):
157 | find_over = False
158 | pre_bb = mlil_ssa_bb.source_block #从前继块中搜索'mov x9, #..'这种指令, 找不到就只能手动分析了
159 | if (cond_set_value[0] == cond_set_value[1]) or ('xzr' in [cond_set_value[0], cond_set_value[1]]):
160 | search_count = 1 #如果两个寄存器相同, 或者有一个是xzr寄存器, 则只用搜索一个
161 | else:
162 | search_count = 2
163 | csx_value_reg = ['w' + cond_set_value[0][1:], 'w' + cond_set_value[1][1:]]
164 | found_bbs = [pre_bb]
165 | while True:
166 | incomes = pre_bb.incoming_edges
167 | if (len(incomes) == 0):
168 | break #没有前继了
169 | if (len(incomes) == 1):
170 | pre_bb = pre_bb.incoming_edges[0].source
171 | else: #如果有多个income, 找地址最小的那一个
172 | min_bb = incomes[0].source
173 | for edge in incomes:
174 | if (edge.source.start < min_bb.start):
175 | min_bb = edge.source
176 | pre_bb = min_bb
177 | if pre_bb in found_bbs:
178 | logger.log_debug("已搜索过的块 可能遇到循环...")
179 | break
180 | else:
181 | found_bbs.append(pre_bb)
182 |
183 | cur_find_addr = pre_bb.end - pre_bb[-1][-1] #从后往前搜索
184 | while cur_find_addr >= pre_bb.start:
185 | insn_txt = bv.get_disassembly(cur_find_addr)
186 | token = insn_txt.split()
187 | if (token[0] == 'mov') and ((csx_value_reg[0] == token[1][:-1]) or (csx_value_reg[1] == token[1][:-1])):
188 | csx_var_addrs.append(cur_find_addr)
189 | logger.log_warn(f"使用可能的csx赋值指令 {hex(cur_find_addr)}: {insn_txt}")
190 | cur_find_addr -= bv.get_instruction_length(cur_find_addr)
191 | if len(csx_var_addrs) >= search_count:
192 | find_over = True
193 | break
194 | if find_over:
195 | break
196 | if find_over == False:
197 | logger.log_warn("未能自动搜索到csx赋值指令 分析可能出错...")
198 | if len(csx_var_addrs) > 2:
199 | logger.log_error(f"搜索到过多的csx赋值变量: {[hex(x) for x in csx_var_addrs]}")
200 | return None, None
201 | logger.log_debug(f"csx_var_addrs: {[hex(x) for x in csx_var_addrs]}")
202 |
203 | #补全涉及的指令
204 | for addr in csx_var_addrs:
205 | if addr not in involve_asm_addrs:
206 | involve_asm_addrs.append(addr)
207 |
208 | #把涉及到的指令的整个bb都写入
209 | involve_bbs = []
210 | for addr in involve_asm_addrs:
211 | bb = func.get_basic_block_at(addr)
212 | if bb not in involve_bbs:
213 | involve_bbs.append(bb)
214 | for bb in involve_bbs:
215 | bb_size = bb.end - bb.start
216 | opcodes = bv.read(bb.start, bb_size)
217 | emulator.write_code_part(opcodes, bb.start)
218 |
219 | #找到本次混淆对应的cmp指令地址, cmp指令肯定在条件选择指令附近
220 | cmp_insn_addr = 0
221 | find_bb = func.get_basic_block_at(condition_insn_addr)
222 | find_addr = condition_insn_addr #先从当前bb找, 当前bb没有就往前继bb找
223 | while cmp_insn_addr == 0:
224 | find_token = (bv.get_disassembly(find_addr)).split()
225 | if find_token[0] == 'cmp':
226 | cmp_insn_addr = find_addr
227 | break
228 |
229 | if find_addr <= find_bb.start: #更新bb
230 | pre_edge = find_bb.incoming_edges
231 | if len(pre_edge) != 1:
232 | break #只能有一个前继
233 | find_bb = pre_edge[0].source
234 | find_addr = find_bb.end - find_bb[-1][-1] #[-1]是(token, size)
235 | continue
236 |
237 | op_len = bv.get_instruction_length(find_addr)
238 | find_addr -= op_len
239 |
240 | if cmp_insn_addr == 0:
241 | logger.log_error("未找到cmp指令!")
242 | return None, None
243 | else:
244 | verify_token = (bv.get_disassembly(cmp_insn_addr)).split()
245 | if verify_token[0] != 'cmp':
246 | logger.log_error(f"搜索到错误的cmp指令地址:{hex(cmp_insn_addr)}!")
247 | return None, None
248 | logger.log_debug(f"cmp_insn_addr: {hex(cmp_insn_addr)}")
249 |
250 | #获取jmp表的地址并写入这块内存
251 | jmp_table_addr = 0
252 | for insn in involve_insns:
253 | if isinstance(insn, MediumLevelILSetVarSsa) and isinstance(insn.src, MediumLevelILLoadSsa):
254 | add_insn = insn.src.src
255 | for ope in add_insn.operands:
256 | if isinstance(ope, MediumLevelILConstPtr) or isinstance(ope, MediumLevelILConst):
257 | jmp_table_addr = ope.constant
258 | break
259 | if jmp_table_addr != 0:
260 | break
261 | if jmp_table_addr == 0:
262 | logger.log_error("未找到跳转表地址!")
263 | return cmp_insn_addr, None
264 | hex_bytes = bv.read(jmp_table_addr, 1024)
265 | emulator.write_code_part(hex_bytes, jmp_table_addr)
266 | logger.log_debug(f"jmp_table_addr: {hex(jmp_table_addr)}")
267 |
268 | #设置需要模拟执行的指令
269 | opinfos = []
270 | for addr in involve_asm_addrs:
271 | oplen = bv.get_instruction_length(addr)
272 | opinfos.append((addr, oplen))
273 |
274 | #分别模拟执行不同的值获取对应的跳转地址
275 | jmp_values = []
276 | if manual_value != None:
277 | cond_set_value = manual_value #手动设置的值
278 | index = 0
279 | for value in cond_set_value:
280 | mov_opcode = b''
281 | if manual_value != None:
282 | mov_opcode = bv.arch.assemble(f"mov {cond_set_reg}, {value}", condition_insn_addr)
283 | else:
284 | #如果是csinc指令, 不满足条件应该改为add x24, x1, #1 | csinc是条件不满足则xd=xm+1, cinc是条件满足则xd=xn+1
285 | if ((insn_token[0] == 'csinc' ) and (index == 1)) or ((insn_token[0] == 'cinc') and (index == 0)):
286 | if value == 'xzr':#如果是xzr寄存器就不能用add, 相当于赋值为了1
287 | mov_opcode = bv.arch.assemble(f"mov {cond_set_reg}, #1", condition_insn_addr)
288 | else:
289 | mov_opcode = bv.arch.assemble(f"add {cond_set_reg}, {value}, #1", condition_insn_addr)
290 | elif (insn_token[0] == 'csinv') and (index == 1):
291 | mov_opcode = bv.arch.assemble(f"mvn {cond_set_reg}, {value}", condition_insn_addr) #按位取反
292 | elif (insn_token[0] == 'sneg') and (index == 1):
293 | mov_opcode = bv.arch.assemble(f"neg {cond_set_reg}, {value}", condition_insn_addr) #取负值
294 | else:
295 | mov_opcode = bv.arch.assemble(f"mov {cond_set_reg}, {value}", condition_insn_addr) #汇编mov x4, x9
296 | #将csx reg指令改为mov reg指令
297 | cs_insn_len = bv.get_instruction_length(condition_insn_addr)
298 | emulator.change_select(condition_insn_addr, cs_insn_len, mov_opcode)
299 | reg_value = emulator.run_specific_opcodes(opinfos, jmp_reg)
300 | jmp_values.append(reg_value)
301 | index += 1
302 | logger.log_info(f"{insn_token[0]}->jmp_values: True:{hex(jmp_values[0])}, False:{hex(jmp_values[1])}")
303 | if jmp_values[0] == jmp_values[1]:
304 | logger.log_warn(f"本次分析{hex(jmp_insn_addr)}结果可能出错! 请检查涉及到的地址中是否遗漏了指令:{[hex(x) for x in involve_asm_addrs]}")
305 |
306 | #开始Patch!!
307 | addr_info = {'cmp':cmp_insn_addr, 'cond': condition_insn_addr, 'jmp': jmp_insn_addr, 'involves': involve_asm_addrs}
308 | patch_addr_info = PatchSelect(bv, addr_info, jmp_values[0], jmp_values[1])
309 |
310 | need_nop_addrs = csx_var_addrs
311 | need_nop_addrs.append(cmp_insn_addr)
312 | return need_nop_addrs, patch_addr_info
313 |
314 | def PatchSelect(bv: BinaryView, patch_info: dict, tbr_addr: int, fbr_addr: int):
315 | """不能直接patch csel和br指令为b.cond tbr_addr/b fbr_addr
316 | 因为原逻辑是cmp之后, 还会执行其他指令(因为编译的时候穿插在一块了), 最后再br reg,
317 | 如果直接patch的话逻辑就改成了cmp之后直接跳了, 逻辑就不正确了, 所以将从cmp到br的指令重新移动构造
318 |
319 | Args:
320 | bv (BinaryView): bv
321 | patch_info (dict): 各种指令地址
322 | tbr_addr (int): 满足cmp条件的跳转地址
323 | fbr_addr (int): 不满足条件的跳转地址
324 | Returns:
325 | dict: 所有写入新数据的地址和长度
326 | """
327 |
328 | """
329 | 具体做法为:
330 | 1. 一次混淆至少涉及以下7个指令(中间穿插着其他逻辑的指令):
331 | mov w10, #0x60
332 | ...
333 | mov w11, #0x58
334 | ...
335 | cmp w7, w22
336 | ...
337 | csel x23, x11, x10, lt
338 | ...
339 | ldr x25, [x12, x23]
340 | ...
341 | add x7, x25, x13
342 | ...
343 | br x7
344 | 2. 改为如下:
345 | mov w10, #0x60 <- 可以nop掉 不nop也不影响结果
346 | ...
347 | mov w11, #0x58
348 | ...
349 | nop <- cmp w7, w22 [cmp语句要最后统一nop 因为会可能有多个逻辑共用同一个cmp]
350 | ...
351 | nop <- csel x23, x11, x10, lt
352 | ...
353 | nop <- 其他涉及到的指令
354 | ...
355 | cmp w7, w22 <- ldr x25, [x12, x23]
356 | b.lt ... <- add x7, x25, x13
357 | b ... <- br x7
358 | 大多只有第一次混淆的时候这些混淆指令会穿插在一起, 之后基本都是ldr+add+br一个整体了
359 | """
360 | ret_dict = {} #{地址: 长度}
361 | cmp_addr = patch_info['cmp']
362 | cond_addr = patch_info['cond']
363 | jmp_addr = patch_info['jmp']
364 | involve_addrs = patch_info['involves']
365 | #从csx到br可以存放多少个字节(包括br)
366 | insn_space = jmp_addr - cond_addr + bv.get_instruction_length(jmp_addr)
367 |
368 | #0. 拿到所有要操作的指令
369 | obf_insns_index = [] #指在csx2br_insns_text中的index
370 | csx2br_insns_text = [] #从csx到br中的所有指令文本 (包含csx不包含br)
371 | read_addr = cond_addr
372 | index = 0
373 | while read_addr < jmp_addr:
374 | op_text = bv.get_disassembly(read_addr)
375 | csx2br_insns_text.append(op_text)
376 |
377 | if read_addr in involve_addrs:
378 | obf_insns_index.append(index)
379 |
380 | op_len = bv.get_instruction_length(read_addr)
381 | read_addr += op_len
382 |
383 | index += 1
384 | logger.log_debug(f"cmp2br_insns_text: {csx2br_insns_text}")
385 | #1. 将混淆指令全转为nop, 并删除最后两个nop(一个nop改bcc, 一个nop改cmp)
386 | for i in obf_insns_index:
387 | csx2br_insns_text[i] = 'nop'
388 | csx2br_insns_text.pop(obf_insns_index[-1])
389 | csx2br_insns_text.pop(obf_insns_index[-2]) #index本身就是从小到大排序的, 所以直接pop不影响
390 |
391 | #2. 下沉cmp
392 | cmp_txt = bv.get_disassembly(cmp_addr)
393 | csx2br_insns_text.append(cmp_txt)
394 |
395 | #3. 获取select指令的寄存器 并添加跳转
396 | csx_tokens = (bv.get_disassembly(cond_addr)).split() #获取csel/cset/csinc等的token
397 | csx_cond = csx_tokens[-1] #条件eq/lt等
398 | bcc_cond = 'b.' + csx_cond
399 | bcc_txt = f"{bcc_cond} {hex(tbr_addr)}"
400 | csx2br_insns_text.append(bcc_txt)
401 | b_txt = f"b {hex(fbr_addr)}"
402 | csx2br_insns_text.append(b_txt)
403 | logger.log_info(f"csx2br_insns_text: {csx2br_insns_text}")
404 |
405 | #4. 将重新构造的指令从sex指令开始写入
406 | if (bv.arch.name == "aarch64"): #64位下指令长度固定为4, 对比哪些指令发生了变化再写哪些指令
407 | changed_insns = {}#{地址:opcode}
408 | index = 0
409 | for insn_txt in csx2br_insns_text:
410 | cmp_addr = cond_addr + 4 * index
411 | org_insn_txt = bv.get_disassembly(cmp_addr)
412 | if (org_insn_txt != insn_txt):
413 | opcode = None
414 | insn_tokens = insn_txt.split()
415 | if (insn_tokens[0][0] == 'b') and (insn_tokens[1][0] == '0'): #跳转指令需要写相对地址
416 | bcc_type = insn_tokens[0]
417 | bcc_addr = int(insn_tokens[1], 16)
418 | bcc_opcode = bv.arch.assemble(f"{bcc_type} {hex(bcc_addr - cmp_addr)}", cmp_addr)
419 | opcode = bcc_opcode
420 | else:
421 | opcode = bv.arch.assemble(insn_txt)
422 | changed_insns[cmp_addr] = opcode
423 | index += 1
424 | logger.log_info(f"开始对比写入:{hex(cond_addr)}...")
425 | state = bv.begin_undo_actions()
426 | for addr in changed_insns.keys():
427 | bv.write(addr, changed_insns[addr])
428 | ret_dict[addr] = len(changed_insns[addr])
429 | bv.commit_undo_actions(state)
430 | else:
431 | new_opcodes = b''
432 | begin_addr = cond_addr #开始写的地址
433 | for insn_txt in csx2br_insns_text: #跳转指令需要单独汇编
434 | insn_tokens = insn_txt.split()
435 | if (insn_tokens[0][0] == 'b') and (insn_tokens[1][0] == '0'): #跳转指令需要写相对地址
436 | bcc_type = insn_tokens[0]
437 | bcc_addr = int(insn_tokens[1], 16)
438 | bcc_begin_addr = begin_addr + len(new_opcodes)
439 | bcc_opcode = bv.arch.assemble(f"{bcc_type} {hex(bcc_addr - bcc_begin_addr)}", bcc_begin_addr)
440 | new_opcodes += bcc_opcode
441 | else:
442 | new_opcodes += bv.arch.assemble(insn_txt)
443 |
444 | new_space = len(new_opcodes)
445 | if new_space != insn_space:
446 | logger.log_warn(f"前后机器码大小不一致: {insn_space} -> {new_space} 分析可能出错!")
447 | logger.log_debug(f"space cmp: {insn_space} -> {new_space}")
448 | if new_space > insn_space:
449 | logger.log_error(f"新产生的机器码数量{new_space} > 原先的大小{insn_space}")
450 | return
451 | elif new_space < insn_space:
452 | nop_bytes = b'\x00' * (insn_space - new_space)
453 | nop_bytes = bv.arch.convert_to_nop(nop_bytes, begin_addr + new_space)
454 | new_opcodes += nop_bytes
455 | logger.log_info(f"开始全部写入:{hex(begin_addr)}...")
456 | state = bv.begin_undo_actions()
457 | bv.write(begin_addr, new_opcodes)
458 | ret_dict[begin_addr] = len(new_opcodes)
459 | bv.commit_undo_actions(state)
460 | return ret_dict
461 |
462 | # 循环去混淆
463 | def dejmpreg_auto(bv: BinaryView, func: Function):
464 |
465 | dejmpreg_emu = armDeJmpRegEmulate() #模拟执行器
466 | dejmpreg_emu.init_func_emu(func.start, 4 * 1024) #小于4k都是4k
467 |
468 | deobf_ok = True
469 | patch_infos = {} #{addr: len}被写入的地址信息
470 | need_nop_addrs = [] #被编译优化提前的cmp指令和csx赋值的指令(都有可能被共用), 需要在去混淆完毕后统一nop
471 | #耗时操作弹出进度dialog
472 | def loop_dejmpreg(progress_callback):
473 | nonlocal deobf_ok #外部变量
474 |
475 | progress_total = 45 #给个初始值 动态更新
476 | cur_deobf_count = 0
477 |
478 | last_insn_addr = 0
479 | while True:
480 | mlil_ssa_func = func.mlil.ssa_form
481 |
482 | find_insn = None
483 | #找每一个块的最后一个指令
484 | for bb in mlil_ssa_func:
485 | ssa_insn = bb[-1]
486 | if isinstance(ssa_insn, MediumLevelILJump):
487 | find_insn = ssa_insn
488 | break
489 | if (find_insn != None) and (find_insn.address == last_insn_addr):
490 | deobf_ok = False
491 | break #如果这次找到的指令和上次的一样 说明去混淆失败
492 |
493 | if find_insn != None:
494 | last_insn_addr = find_insn.address #记录指令地址
495 | try: #异常则退出
496 | nop_info, patch_info = dejmpreg(bv, func, find_insn, dejmpreg_emu)
497 | if (nop_info == None) or (patch_info == None):
498 | deobf_ok = False
499 | break
500 |
501 | need_nop_addrs.extend(nop_info)
502 | patch_infos.update(patch_info)
503 | func.reanalyze() # 重新分析函数,以便更新SSA形式
504 | while True: #reanalyze是异步的 不会等待重新分析完毕 我没找到同步的API 先这样写吧
505 | time.sleep(0.2) # 等待一段时间再检查
506 | if func.mlil.ssa_form is not None:
507 | break
508 |
509 | cur_deobf_count += 1 #去除一次
510 | if cur_deobf_count >= progress_total:
511 | progress_total += 20
512 | except Exception as e:
513 | deobf_ok = False
514 | logger.log_error(f"发生异常: {e}")
515 | break
516 | else:
517 | break
518 |
519 | # 调用进度回调函数,参数为已完成和总量
520 | if not progress_callback(cur_deobf_count, progress_total):
521 | return
522 | # 完成
523 | logger.log_info(f"共去除[寄存器间接跳转]混淆[{cur_deobf_count}]次...")
524 | progress_callback(progress_total, progress_total)
525 |
526 | start_time = time.time()
527 | progress_result = interaction.run_progress_dialog("正在去除[寄存器间接跳转]混淆...", True, loop_dejmpreg)
528 | end_time = time.time()
529 |
530 | # 检查任务是否成功完成
531 | if progress_result:
532 | if deobf_ok:
533 | logger.log_debug(f"patch_infos: { {hex(addr): length for addr, length in patch_infos.items()} }")
534 | state = bv.begin_undo_actions() #nop cmp指令
535 | nop_addrs = []
536 | for addr in need_nop_addrs:
537 | in_patch = False #如果地址在我们写入的新patch地址中, 就不要去nop它
538 | for paddr in patch_infos.keys():
539 | if (addr >= paddr) and (addr < paddr + patch_infos[paddr]):
540 | in_patch = True
541 | break
542 |
543 | if not in_patch:
544 | op_len = bv.get_instruction_length(addr)
545 | nop_bytes = b'\x00' * op_len
546 | nop_bytes = bv.arch.convert_to_nop(nop_bytes, addr)
547 | bv.write(addr, nop_bytes)
548 | nop_addrs.append(addr)
549 | logger.log_info(f"nop掉无用指令: {[hex(x) for x in nop_addrs]}")
550 | bv.commit_undo_actions(state)
551 | logger.log_info(f"去除[寄存器间接跳转]混淆完毕! 共耗时 {end_time - start_time} 秒...")
552 | else:
553 | logger.log_error("去除[寄存器间接跳转]混淆失败!...")
554 | else:
555 | logger.log_error("用户取消去除[寄存器间接跳转]操作!...")
556 |
557 | # 去混淆一次
558 | def dejmpreg_cursor(bv: BinaryView, address: int):
559 | target_func = (bv.get_functions_containing(address))[0]
560 | target_mlil_ssa_func = target_func.mlil.ssa_form
561 |
562 | #找到包含该地址的bb
563 | find_bb = None
564 | for mlssa_bb in target_mlil_ssa_func:
565 | start_addr = mlssa_bb[0].address
566 | end_addr = mlssa_bb[-1].address
567 | if (address >= start_addr) and (address <= end_addr):
568 | find_bb = mlssa_bb
569 | break
570 | if (find_bb != None) and (isinstance(find_bb[-1], MediumLevelILJump)):
571 | dejmpreg_emu = armDeJmpRegEmulate() #模拟执行器
572 | dejmpreg_emu.init_func_emu(target_func.start, 4 * 1024) #小于4k都是4k
573 |
574 | find_insn = find_bb[-1]
575 | dejmpreg(bv, target_func, find_insn, dejmpreg_emu)
576 | else:
577 | logger.log_error(f"{hex(address)}: 该地址处未找到jump指令!")
578 |
579 | # 手动设置条件选择指令的值 用于调试
580 | def dejmpreg_manual(bv: BinaryView, address: int):
581 | target_func = (bv.get_functions_containing(address))[0]
582 | target_mlil_ssa_func = target_func.mlil.ssa_form
583 |
584 | #找到包含该地址的bb
585 | find_bb = None
586 | for mlssa_bb in target_mlil_ssa_func:
587 | start_addr = mlssa_bb[0].address
588 | end_addr = mlssa_bb[-1].address
589 | if (address >= start_addr) and (address <= end_addr):
590 | find_bb = mlssa_bb
591 | break
592 | if (find_bb != None) and (isinstance(find_bb[-1], MediumLevelILJump)):
593 | true_res = interaction.get_int_input("输入满足条件时的值:", "手动设置csx指令的值")
594 | false_res = interaction.get_int_input("输入不满足条件时的值:", "手动设置csx指令的值")
595 | if (true_res == None) or (false_res == None):
596 | interaction.show_message_box("提示", "未输入值, 取消执行")
597 | return
598 |
599 | manual_value = [true_res, false_res]
600 | logger.log_info(f"使用手动值: True:{hex(true_res)} False:{hex(false_res)}")
601 | dejmpreg_emu = armDeJmpRegEmulate() #模拟执行器
602 | dejmpreg_emu.init_func_emu(target_func.start, 4 * 1024) #小于4k都是4k
603 |
604 | find_insn = find_bb[-1]
605 | dejmpreg(bv, target_func, find_insn, dejmpreg_emu, manual_value)
606 | else:
607 | logger.log_error(f"{hex(address)}: 该地址处未找到jump指令!")
--------------------------------------------------------------------------------
/emulate.py:
--------------------------------------------------------------------------------
1 | from unicorn import *
2 | from unicorn.x86_const import *
3 | from unicorn.arm_const import *
4 | from unicorn.arm64_const import *
5 |
6 | import importlib
7 | from typing import List, Tuple
8 | from dataclasses import dataclass
9 |
10 | class Emulator:
11 | """用于模拟执行基类
12 | 存在一些公共方法
13 | """
14 | @dataclass
15 | class MemMap:
16 | """存放映射的内存信息
17 | """
18 | mem_start: int
19 | mem_size: int
20 | mem_end: int
21 |
22 | def __init__(self, arch, mode) -> None:
23 | """创建模拟执行引擎
24 |
25 | Args:
26 | arch : 模拟器架构x86|arm|arm64
27 | mode : 模拟器模式32/64|arm/thumb
28 | """
29 | #private
30 | self.__m_uc = None
31 | self.__m_mems: List[Emulator.MemMap] = [] #所有mem_map的内存起始地址和内存大小
32 |
33 | #protected
34 | self._m_arch = None
35 | self._m_mode = None
36 |
37 | self._m_arch = arch
38 | self._m_mode = mode
39 | self.__m_uc = Uc(arch, mode)
40 |
41 | def __del__(self):
42 | for mem_info in self.__m_mems:
43 | self.unmap_mem(mem_info.mem_start, mem_info.mem_size)
44 | #我也不知道映射的内存需不需要手动释放, Uc是不需要手动释放的
45 |
46 | def _is_arch32(self) -> bool:
47 | is32 = False
48 | if (self._m_mode == UC_MODE_32) or (self._m_arch == UC_ARCH_ARM):
49 | is32 = True
50 | return is32
51 |
52 | def __reg2uc(self, reg : str):
53 | """将reg名转为uc常量
54 |
55 | Args:
56 | reg : 寄存器名
57 |
58 | Returns:
59 | int : 失败返回None
60 | """
61 | attr_name = ""
62 | arch_name = ""
63 | module_name = "unicorn."
64 | reg_name = reg.upper()
65 | if (self._m_arch == UC_ARCH_X86):
66 | arch_name = "X86"
67 | module_name += "x86_const"
68 | elif (self._m_arch == UC_ARCH_ARM):
69 | arch_name = "ARM"
70 | module_name += "arm_const"
71 | elif (self._m_arch == UC_ARCH_ARM64):
72 | arch_name = "ARM64"
73 | module_name += "arm64_const"
74 | attr_name = f"UC_{arch_name}_REG_{reg_name}"
75 |
76 | try:
77 | arch_const_module = importlib.import_module(module_name)
78 | return getattr(arch_const_module, attr_name)
79 | except (ModuleNotFoundError, AttributeError):
80 | return None
81 |
82 | def set_reg(self, reg : str, value = 0):
83 | reg_id = self.__reg2uc(reg)
84 | self.__m_uc.reg_write(reg_id, value)
85 |
86 | def get_reg(self, reg : str):
87 | reg_id = self.__reg2uc(reg)
88 | return self.__m_uc.reg_read(reg_id)
89 |
90 | def map_mem(self, addr:int, size: int) -> Tuple[int, int]:
91 | """映射内存
92 |
93 | Args:
94 | addr (int): 地址
95 | size (int): 大小
96 |
97 | Returns:
98 | Tuple[int, int]: (真正的地址, 真正的大小) 因为API要求是4k对齐的
99 | """
100 | #不是4k对齐的 则往前进行4k对齐 预留一段空间
101 | mem_4k_addr = (addr & ~(4095))
102 | mem_4k_num = ((size + addr - mem_4k_addr) // 4096) + 1 # mem要是4kb的倍数
103 | mem_4k_size = mem_4k_num * 4 * 1024
104 | mem_4k_end = mem_4k_addr + mem_4k_size
105 |
106 | new_mem = True
107 | for mem_info in self.__m_mems: #判断是否已经在mems中, 进行合并
108 | index = self.__m_mems.index(mem_info)
109 | if (mem_4k_addr >= mem_info.mem_start) and (mem_4k_end <= mem_info.mem_end):
110 | return mem_4k_addr, mem_4k_size #已经存在
111 | elif (mem_4k_addr <= mem_info.mem_start) and ((mem_4k_end >= mem_info.mem_start) and (mem_4k_end <= mem_info.mem_end)):
112 | new_size = mem_info.mem_size + (mem_info.mem_start - mem_4k_addr)
113 | self.__m_mems[index].mem_start = mem_4k_addr
114 | self.__m_mems[index].mem_size = new_size
115 | new_mem = False
116 | break
117 | elif ((mem_4k_addr >= mem_info.mem_start) and (mem_4k_addr <= mem_info.mem_end)) and (mem_4k_end >= mem_info.mem_end):
118 | new_size = mem_info.mem_size + (mem_4k_end - mem_info.mem_end)
119 | self.__m_mems[index].mem_end = mem_4k_end
120 | self.__m_mems[index].mem_size = new_size
121 | new_mem = False
122 | break
123 | elif (mem_4k_addr <= mem_info.mem_start) and (mem_4k_end >= mem_info.mem_end):
124 | self.__m_mems[index].mem_start = mem_4k_addr
125 | self.__m_mems[index].mem_size = mem_4k_size
126 | self.__m_mems[index].mem_end = mem_4k_end
127 | new_mem = False
128 | break
129 |
130 | self.__m_uc.mem_map(mem_4k_addr, mem_4k_size)
131 |
132 | if new_mem:
133 | mem_info = Emulator.MemMap(mem_start=mem_4k_addr, mem_size=mem_4k_size, mem_end=mem_4k_end)
134 | self.__m_mems.append(mem_info) #添加到__m_mems中
135 | return mem_4k_addr, mem_4k_size
136 |
137 | def unmap_mem(self, addr: int, size: int) -> bool:
138 | """取消内存映射
139 |
140 | Args:
141 | addr (int): 起始地址
142 | size (int): 大小 会自动4k对齐
143 |
144 | Returns:
145 | bool: 是否成功
146 | """
147 | mem_4k_addr = (addr & ~(4095))
148 | mem_4k_num = ((size + addr - mem_4k_addr) // 4096) + 1 # mem要是4kb的倍数
149 | mem_4k_size = mem_4k_num * 4 * 1024
150 | mem_4k_end = mem_4k_addr + mem_4k_size
151 |
152 | find_mem_info = None
153 | for mem_info in self.__m_mems:
154 | if (mem_4k_addr >= mem_info.mem_start) and (mem_4k_end <= mem_info.mem_end):
155 | find_mem_info = mem_info
156 | break
157 | if find_mem_info == None:
158 | return False
159 | else:
160 | if (mem_4k_addr == find_mem_info.mem_start) and (mem_4k_end == find_mem_info.mem_end):
161 | self.__m_mems.remove(find_mem_info)
162 | elif (mem_4k_addr > find_mem_info.mem_start) and (mem_4k_end < find_mem_info.mem_end):
163 | block1_start = find_mem_info.mem_start
164 | block1_size = mem_4k_addr - find_mem_info.mem_start
165 | new_mem_block1 = Emulator.MemMap(mem_start=block1_start, mem_size=block1_size, mem_end=mem_4k_addr)
166 | block2_start = mem_4k_end
167 | block2_size = find_mem_info.mem_end - mem_4k_end
168 | new_mem_block2 = Emulator.MemMap(mem_start=block2_start, mem_size=block2_size, mem_end=find_mem_info.mem_end)
169 | self.__m_mems.remove(find_mem_info)
170 | self.__m_mems.append(new_mem_block1)
171 | self.__m_mems.append(new_mem_block2)
172 |
173 | self.__m_uc.mem_unmap(mem_4k_addr, mem_4k_size)
174 | return True
175 |
176 | def is_inmem(self, addr: int, size: int = 0) -> bool:
177 | """判断给定的内存块是否已经映射
178 |
179 | Args:
180 | addr (int): 地址
181 | size (int): 大小
182 |
183 | Returns:
184 | bool: 已经映射返回True
185 | """
186 | mem_start = addr
187 | mem_end = addr + size
188 |
189 | in_mem = False
190 | for mem_info in self.__m_mems:
191 | if (mem_start >= mem_info.mem_start) and (mem_end <= mem_info.mem_end):
192 | in_mem = True
193 | break
194 | return in_mem
195 |
196 | def write_mem(self, addr, wbytes) -> bool:
197 | """将bytes写入内存
198 |
199 | Args:
200 | addr : 要写入的地址
201 | wbytes : 要写入的数据
202 |
203 | Returns:
204 | bool: 是否成功
205 | """
206 | #print(f"[write_mem] addr:{hex(addr)} | byte_len:{len(bytes)}")
207 |
208 | if self.is_inmem(addr, len(wbytes)):
209 | self.__m_uc.mem_write(addr, wbytes)
210 | return True
211 | return False
212 |
213 | def read_mem(self, addr, size) -> bytes:
214 | """读取内存的值
215 |
216 | Args:
217 | addr : 地址
218 | size : 大小
219 |
220 | Returns:
221 | bytes: 读取的值
222 | """
223 | if self.is_inmem(addr, size):
224 | return self.__m_uc.mem_read(addr, size)
225 | return b''
226 |
227 | def add_hook(self, hook_type, func, usr_data = None):
228 | """添加一个钩子
229 |
230 | Args:
231 | hook_type : UC_HOOK_*
232 | func : 回调函数
233 | usr_data : 用户数据
234 | """
235 | self.__m_uc.hook_add(hook_type, func, usr_data)
236 |
237 | def start_emu(self, start_addr: int, end_addr: int) -> bool:
238 | """开始模拟执行
239 |
240 | Args:
241 | start_addr : 开始执行的地址(ip)
242 | end_addr : 结束地址
243 |
244 | Returns:
245 | bool: 是否开始成功
246 | """
247 | try:
248 | self.__m_uc.emu_start(start_addr, end_addr)
249 | except UcError as e:
250 | pc_id = None
251 | if (self._m_arch == UC_ARCH_ARM64):
252 | pc_id = UC_ARM64_REG_PC
253 | elif (self._m_arch == UC_ARCH_ARM):
254 | pc_id = UC_ARM_REG_PC
255 | elif (self._m_arch == UC_ARCH_X86):
256 | if (self._m_mode == UC_MODE_32):
257 | pc_id = UC_X86_REG_EIP
258 | else:
259 | pc_id = UC_X86_REG_RIP
260 |
261 | print(f"ip: {hex(self.__m_uc.reg_read(pc_id))} | Emu Err: {e}")
262 | return False
263 |
264 | return True
265 |
266 | class FuncEmulate(Emulator):
267 | def __init__(self, arch, mode) -> None:
268 | #protected
269 | self._m_code_size = 0 #机器码大小
270 | self._m_code_start = 0 #start是机器码起始地址
271 | self._m_stack_size = 0
272 | self._m_stack_base = 0
273 | super().__init__(arch, mode)
274 |
275 | def init_func_emu(self, code_addr, code_size):
276 | """初始化.text段等信息
277 |
278 | Args:
279 | code_addr: 机器码开始地址
280 | code_size (int): 机器码大小.
281 |
282 | Returns:
283 | bool: 是否初始化成功
284 | """
285 |
286 | self._m_code_start = code_addr
287 | self._m_code_size = code_size
288 | self.map_mem(code_addr, code_size)
289 |
290 | high_base = 0x0
291 | if (self._m_mode == UC_MODE_64) or (self._m_arch == UC_ARCH_ARM64):
292 | high_base = 0xDE60000000
293 | self._m_stack_base = high_base + 0x11B0000
294 | self._m_stack_size = 1 * 1024 * 1024 #1MB
295 | self.map_mem(self._m_stack_base, self._m_stack_size)
296 |
297 | # 离栈底预留0x100的空间
298 | sp = self._m_stack_base + self._m_stack_size - 0x100
299 | bp = sp
300 | #if self._is_arch32() :
301 | sp -= 0x100 #32位下的栈帧结构 再把sp往上提 预留变量的空间
302 |
303 | if self._m_arch == UC_ARCH_X86:
304 | if self._m_mode == UC_MODE_32:
305 | super().set_reg('ebp', bp)
306 | super().set_reg('esp', sp)
307 | elif self._m_mode == UC_MODE_64:
308 | super().set_reg('rsp', sp)
309 | super().set_reg('rbp', bp)
310 | elif self._m_arch == UC_ARCH_ARM:
311 | super().set_reg('sp', sp) #R13
312 | super().set_reg('fp', bp) #R11
313 | elif self._m_arch == UC_ARCH_ARM64:
314 | super().set_reg('sp', sp)
315 | super().set_reg('fp', bp) #X29
316 | return True
317 |
318 | def write_func_opcode(self, opcodes) -> bool:
319 | """从函数起始地址处写入机器码
320 |
321 | Args:
322 | opcodes (bytes): 机器码
323 |
324 | Returns:
325 | bool: 是否成功
326 | """
327 | write_addr = self._m_code_start
328 | return super().write_mem(write_addr, opcodes)
329 |
330 | def reg_value(self, reg, value = None):
331 | """设置/获取 寄存器的值
332 |
333 | Args:
334 | reg : 寄存器
335 | value (optional): 当此值为None时则获取寄存器值. Defaults to None.
336 | """
337 | ret_value = 0
338 | if value == None:
339 | ret_value = super().get_reg(reg)
340 | else:
341 | super().set_reg(reg, value)
342 | return ret_value
343 |
344 | def stack_value(self, reg, offset, size = None, value = None):
345 | """设置/获取 栈值
346 |
347 | Args:
348 | reg : 寄存器
349 | offset : 偏移
350 | size : 写入大小 4或者8 为None则按当前架构大小
351 | value (optional): 当此值为None时则获取栈值. Defaults to None.
352 | """
353 | ret_value = None
354 | rw_addr = super().get_reg(reg) + offset
355 |
356 | rw_size = size #自动识别size
357 | if rw_size is None:
358 | rw_size = 4 if super()._is_arch32() else 8
359 |
360 | if (value is not None): #写入
361 | value_bytes = value.to_bytes(16, 'little', signed=True) #先转到16个字节再截取rw_size个字节
362 | super().write_mem(rw_addr, value_bytes[:rw_size])
363 | else: #读取
364 | read_bytes = super().read_mem(rw_addr, rw_size)
365 | if (len(read_bytes) == rw_size):
366 | ret_value = int.from_bytes(read_bytes, byteorder='little', signed=True)
367 | return ret_value
368 |
369 | def add_code_hook(self, func, usr_data = None):
370 | """添加代码钩子
371 |
372 | Args:
373 | func: 回调函数
374 | usr_data (optional): 用户数据. Defaults to None.
375 | """
376 | super().add_hook(UC_HOOK_CODE, func, usr_data)
377 |
378 | def start_func_emu(self, start_addr: int, end_addr = None) -> bool:
379 | """开始模拟执行Func
380 |
381 | Args:
382 | start_addr : 开始执行的地址(ip)
383 | end_addr : 结束地址如果为None则一直执行到函数末
384 |
385 | Returns:
386 | bool: 是否开始成功
387 | """
388 | until_addr = None
389 |
390 | code_begin = self._m_code_start
391 | code_end = self._m_code_start + self._m_code_size
392 | if end_addr == None:
393 | until_addr = code_end
394 | else:
395 | until_addr = end_addr
396 | return super().start_emu(start_addr, until_addr)
397 |
398 | class DeflatEmulate(FuncEmulate):
399 | """用于设置deflat相关的模拟执行
400 |
401 | Args:
402 | FuncEmulate: 父类
403 | """
404 | def __init__(self, arch, mode) -> None:
405 | #private
406 | self.__m_switch_info = {'begin_addr' : 0, 'var_reg' : '', 'var_offset' : 0, 'init_value' : 0}
407 | run_info = {'stops': [], 'begin': 0, 'loop_count': 0, 'last': 0, 'insn_size': 0} #1. 需要停止模拟的地址 2. 主分发器开始地址 3. 循环了分发逻辑的次数 4. 最后模拟的一条指令的地址 5. 指令长度
408 | super().__init__(arch, mode)
409 |
410 | self.run_info_var = run_info
411 | super().add_code_hook(DeflatEmulate.hook_code_callback, run_info)
412 |
413 | def init_reg_stack(self, start_addr: int, end_addr: int):
414 | """运行entry bb的指令 初始化寄存器和栈的值
415 |
416 | Args:
417 | start_addr (int): 从哪里开始运行
418 | end_addr (int): 运行到哪里结束
419 | """
420 | result = False
421 | run_addr = start_addr
422 | while result != True:
423 | result = self.start_emu(run_addr, end_addr)
424 | if result != True:
425 | ip = self.run_info_var['last']
426 | opsize = self.run_info_var['insn_size']
427 | run_addr = ip + opsize #遇到发生错误的指令则跳过并继续执行
428 | if run_addr >= end_addr:
429 | break
430 |
431 | def set_stop_addrs(self, addrs : list):
432 | """设置停止仿真地址
433 |
434 | Args:
435 | addrs (_type_): 停止地址
436 | """
437 | for addr in addrs:
438 | self.run_info_var['stops'].append(addr)
439 |
440 | def set_switch_begin_addr(self, addr : int):
441 | self.__m_switch_info['begin_addr'] = addr
442 | self.run_info_var['begin'] = addr
443 |
444 | def set_switch_var(self, reg, offset = None , init_value = None, size = None):
445 | """设置使用哪个作为switch的判断变量
446 |
447 | Args:
448 | reg : 寄存器
449 | offset : 偏移 如果offset=None则使用寄存器作为switch var否则使用栈
450 | init_value : 初始值
451 | size : value是4位还是8位 为None则按32/64大小
452 | """
453 | self.__m_switch_info['var_reg'] = reg
454 | self.__m_switch_info['var_offset'] = offset
455 | if (init_value is not None):
456 | self.__m_switch_info['init_value'] = init_value
457 | if offset == None:
458 | super().reg_value(reg, init_value)
459 | else:
460 | super().stack_value(reg, offset, size, init_value)
461 |
462 | def set_switch_var_value(self, value : int, size = None):
463 | """设置switch变量的值
464 |
465 | Args:
466 | value (int): 值
467 | """
468 | reg = self.__m_switch_info['var_reg']
469 | offset = self.__m_switch_info['var_offset']
470 | if (offset == None):
471 | super().reg_value(reg, value)
472 | else:
473 | super().stack_value(reg, offset, size, value)
474 |
475 | def start_until_stop(self) -> int:
476 | """开始模拟执行直到遇到设置的停止地址
477 |
478 | Returns:
479 | int: 停止在哪个地址处
480 | """
481 | if len(self.run_info_var['stops']) == 0:
482 | return 0
483 |
484 | begin_addr = self.__m_switch_info['begin_addr']
485 | if (begin_addr == 0):
486 | return 0
487 |
488 | #print(f"[Debug] emu_start: {hex(begin_addr)} | user_data : {self.stop_info_var}")
489 |
490 | result = False
491 | run_addr = begin_addr
492 | while result != True:
493 | result = super().start_func_emu(run_addr)
494 | if result != True:
495 | ip = self.run_info_var['last']
496 | opsize = self.run_info_var['insn_size']
497 | run_addr = ip + opsize #遇到发生错误的指令则跳过并继续执行
498 |
499 | #print(f"[Debug] emu_end user_data : {self.stop_info_var}")
500 | return self.run_info_var['last']
501 |
502 | @staticmethod
503 | def hook_code_callback(uc : Uc, address, size, user_data):
504 | #print(f"[Debug] cur_rip: {hex(address)} | {uc.mem_read(address, size)}")
505 | user_data['last'] = address
506 | user_data['insn_size'] = size
507 | if address in user_data['stops']:
508 | uc.emu_stop()
509 |
510 | if (address == user_data['begin']):
511 | user_data['loop_count'] += 1
512 |
513 | if user_data['loop_count'] > 6000:
514 | uc.emu_stop() #循环次数太多了, 说明switch变量或者其他地方出了问题
515 |
516 |
517 | class x86DeflatEmulate(DeflatEmulate):
518 | def __init__(self, is32 = False) -> None:
519 | """x86架构
520 |
521 | Args:
522 | is32 (bool, optional): 是否是32位的. Defaults to False.
523 | """
524 | arch = UC_ARCH_X86
525 | mode = UC_MODE_32 if is32 else UC_MODE_64
526 | super().__init__(arch, mode)
527 |
528 | class armDeflatEmulate(DeflatEmulate):
529 | def __init__(self, is64 = True, isThumb = False, isEB = False) -> None:
530 | """arm架构
531 |
532 | Args:
533 | is64 (bool, optional): 是否是aarch64. Defaults to True.
534 | isThumb (bool, optional): 是否是Thumb指令集. Defaults to False.
535 | isEB (bool, optional): 是否是大端序. Defaults to False.
536 | """
537 | arch = UC_ARCH_ARM64 if is64 else UC_ARCH_ARM
538 | if arch == UC_ARCH_ARM64:
539 | mode = UC_MODE_ARM
540 | else:
541 | mode = UC_MODE_THUMB if isThumb else UC_MODE_ARM
542 | if isEB:
543 | mode |= UC_MODE_BIG_ENDIAN
544 | super().__init__(arch, mode)
545 |
546 |
547 | class DeJmpRegEmulate(FuncEmulate):
548 | def __init__(self, arch, mode) -> None:
549 | super().__init__(arch, mode)
550 |
551 | def write_code_part(self, opcodes: bytes, start_addr: int) -> bool:
552 | """写入一块指令
553 |
554 | Args:
555 | opcodes (bytes): 机器码
556 | start_addr (int): 要写入的地址
557 |
558 | Returns:
559 | bool: 是否成功
560 | """
561 | #先映射一下内存
562 | if super().is_inmem(start_addr, len(opcodes)) != True:
563 | super().map_mem(start_addr, len(opcodes))
564 |
565 | return super().write_mem(start_addr, opcodes)
566 |
567 | def change_select(self, cs_insn_addr: int, cs_insn_len: int, opcode: bytes) -> bool:
568 | """将csel/cset指令转为其他指令(mov), 用于设置固定的值
569 |
570 | Args:
571 | cs_insn_addr (int): csel/cset指令起始地址
572 | cs_insn_len (int): 指令长度
573 | opcode (bytes): 要替换的opcode
574 |
575 | Returns:
576 | bool: 是否成功
577 | """
578 | if (cs_insn_addr + cs_insn_len) < len(opcode):
579 | return False
580 | return super().write_mem(cs_insn_addr, opcode)
581 |
582 | def run_specific_opcodes(self, opinfos: list, rreg: str):
583 | """执行特定的机器码
584 |
585 | Args:
586 | opinfos (list): [(addr, len), ...] 起始地址和长度
587 | rreg (str): 执行结束后需要返回哪个寄存器的值
588 | """
589 | sorted_opinfos = sorted(opinfos, key=lambda x: x[0]) #按照addr从小到大排序
590 | for opinfo in sorted_opinfos:
591 | start_addr = opinfo[0]
592 | end_addr = start_addr + opinfo[1]
593 | super().start_emu(start_addr, end_addr)
594 | return super().reg_value(rreg)
595 |
596 | class armDeJmpRegEmulate(DeJmpRegEmulate):
597 | def __init__(self, is64 = True, isThumb = False, isEB = False) -> None:
598 | """arm架构
599 |
600 | Args:
601 | is64 (bool, optional): 是否是aarch64. Defaults to True.
602 | isThumb (bool, optional): 是否是Thumb指令集. Defaults to False.
603 | isEB (bool, optional): 是否是大端序. Defaults to False.
604 | """
605 | arch = UC_ARCH_ARM64 if is64 else UC_ARCH_ARM
606 | if arch == UC_ARCH_ARM64:
607 | mode = UC_MODE_ARM
608 | else:
609 | mode = UC_MODE_THUMB if isThumb else UC_MODE_ARM
610 | if isEB:
611 | mode |= UC_MODE_BIG_ENDIAN
612 | super().__init__(arch, mode)
--------------------------------------------------------------------------------
/plugin.json:
--------------------------------------------------------------------------------
1 | {
2 | "pluginmetadataversion": 2,
3 | "name": "detx",
4 | "type": [
5 | "core",
6 | "ui",
7 | "architecture",
8 | "binaryview",
9 | "helper"
10 | ],
11 | "api": [
12 | "python3"
13 | ],
14 | "description": "detx",
15 | "longdescription": "deobf tx libtprt's obfuscation",
16 | "license": {
17 | "name": "GPL-3.0",
18 | "text": "Copyright (c) 2024 <0xEEEE>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
19 | },
20 | "platforms": [
21 | "Darwin",
22 | "Linux",
23 | "Windows"
24 | ],
25 | "installinstructions": {
26 | "Darwin": "Install `unicorn` using pip : `pip install setuptools unicorn`",
27 | "Linux": "Install `unicorn` using pip : `pip install setuptools unicorn`",
28 | "Windows": "Install `unicorn` using pip : `pip install setuptools unicorn`"
29 | },
30 | "dependencies": {
31 | },
32 | "version": "1.0.0",
33 | "author": "0xEEEE",
34 | "minimumbinaryninjaversion": 5571
35 | }
36 |
--------------------------------------------------------------------------------