├── .deepsource.toml
├── .github
└── workflows
│ └── build.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── requirements.in
├── requirements.txt
├── sonar-project.properties
├── t-brop.py
├── tbrop
├── arch.py
├── collection.py
├── gadget.py
└── graph.py
└── tests
├── test_dumbGadget.py
└── test_gadget.py
/.deepsource.toml:
--------------------------------------------------------------------------------
1 | version = 1
2 |
3 | test_patterns = [
4 | 'tests/test_*.py'
5 | ]
6 |
7 | exclude_patterns = [
8 |
9 | ]
10 |
11 | [[analyzers]]
12 | name = 'python'
13 | enabled = true
14 | runtime_version = '3.x.x'
15 |
16 | [[analyzers]]
17 | name = "test-coverage"
18 | enabled = true
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: Build
2 | on:
3 | push:
4 | branches:
5 | - master
6 | pull_request:
7 | types: [opened, synchronize, reopened]
8 | jobs:
9 | sonarcloud:
10 | name: SonarCloud
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v3
14 | with:
15 | fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
16 | - name: SonarCloud Scan
17 | uses: SonarSource/sonarcloud-github-action@master
18 | env:
19 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any
20 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
21 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | *.exe
3 | *.i64
4 | *.id0
5 | *.id1
6 | *.id2
7 | *.nam
8 | *.til
9 | *.db
10 | *.db-journal
11 | *../.vscode
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.11.4-slim-bookworm
2 |
3 | WORKDIR /app/tbrop
4 |
5 | COPY requirements.txt /app/tbrop/.
6 | RUN pip install -r requirements.txt
7 |
8 | COPY t-brop.py /app/tbrop/.
9 | COPY tbrop /app/tbrop/tbrop/.
10 |
11 | ENTRYPOINT ["python3", "t-brop.py"]
12 | CMD ["-h"]
--------------------------------------------------------------------------------
/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 |
676 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://travis-ci.com/clslgrnc/tbrop)
2 | [](https://sonarcloud.io/dashboard?id=clslgrnc_tbrop)
3 | [](https://sonarcloud.io/dashboard?id=clslgrnc_tbrop)
4 | [](https://sonarcloud.io/dashboard?id=clslgrnc_tbrop)
5 | [](https://deepsource.io/gh/clslgrnc/tbrop/?ref=repository-badge)
6 |
7 | # TBrop
8 | > Taint-Based Return Oriented Programming
9 | ---
10 |
11 | This is an implementation of the taint-based gadget management approach presented at [SSTIC](https://www.sstic.org/2018/presentation/T-Brop/) ([paper](https://www.sstic.org/media/SSTIC2018/SSTIC-actes/T-Brop/SSTIC2018-Article-T-Brop-le-guernic_khourbiga.pdf), [slides](https://www.sstic.org/media/SSTIC2018/SSTIC-actes/T-Brop/SSTIC2018-Slides-T-Brop-le-guernic_khourbiga.pdf), [talk](https://static.sstic.org/videos2018/SSTIC_2018-06-13_P03.mp4), in french) and [REcon](https://recon.cx/2018/montreal/schedule/events/129.html) in 2018.
12 |
13 | This is still a PoC, and the code is still ugly as can be attested by the various badges at the top of this README.
14 |
15 | ## Background
16 | There are roughly two kinds of tools for return oriented programming (ROP):
17 | _syntactic_ tools that return the disassembly of gadgets and sometimes perform
18 | template based automatic chaining, and _symbolic_ tools that compute a symbolic
19 | representation of the output state for each gadget and allow more powerful
20 | manipulations.
21 | The former are very fast but only allow regex queries, the latter allow symbolic
22 | queries but are much slower.
23 |
24 | Taint-based ROP is an alternative approach, faster than symbolic tools and allowing more expressive queries than syntactic tools.
25 | TBrop uses a coarse semantic of instructions. Instead of a precise symbolic I/O
26 | relationship, it only relies on a dependency matrix reflecting how a taint would
27 | be propagated by a given gadget.
28 |
29 | As an example, from the following gadget:
30 |
31 | ```nasm
32 | xchg rax, rbx
33 | xor rcx, rcx
34 | add rcx, rax
35 | jmp rcx
36 | ```
37 |
38 | TBrop compute the following (sparse boolean) matrix:
39 |
40 | | | ... | rax | rbx | rcx | ...
41 | |:---:|:---:|:---:|:---:|:---:|:---:
42 | | ... | | | | |
43 | | rax | | . | <┘ | . |
44 | | rbx | | <┘ | . | . |
45 | | rcx | | . | <┘ | . |
46 | | ... | | | | |
47 |
48 | which reads as `rax` is influenced by `rbx`, `rbx` is influenced by `rax`, and `rcx` is influenced by `rbx`. The matrix also contains indices corresponding to `rip` (chain condition), some of the stack cells, and dereferencing among others.
49 |
50 | ## Getting Started
51 |
52 | To build with docker:
53 | ```
54 | sudo docker build -t tbrop .
55 | ```
56 |
57 | Otherwise, just `pip install` the dependencies:
58 | - [capstone](https://pypi.org/project/capstone/) to disassemble opcodes;
59 | - [lief](https://pypi.org/project/lief/) to load various executable formats;
60 | - [numpy](https://pypi.org/project/numpy/) and [scipy](https://pypi.org/project/scipy/) for sparse boolean matrices;
61 | - [ipython](https://pypi.org/project/ipython/) if you want to use the TBrop script, as opposed to just using TBrop as a lib.
62 | ## Usage
63 |
64 | To analyse ```/FULL/LOCAL/PATH/FILE```:
65 | ```
66 | sudo docker run --rm -it -v /FULL/LOCAL/PATH/FILE:/app/FILE:ro tbrop /app/FILE
67 | ```
68 |
69 | It should (eventually) bring you to an ipython shell where you can do stuff like:
70 | ```python
71 | for g in gdgtCollection.gadgets:
72 | if g.gadgetMatrix.matrix[X86_REG_RSP,X86_REG_RAX] \
73 | and g.gadgetMatrix.chainCond[0,X86_REG_RCX]:
74 | print(hex(g.getAddress()),g)
75 | ```
76 |
77 | All the gadgets are in the `gadgets` attribute of the `gdgtCollection` object (some refactoring is needed...). Each gadget as a `gadgetMatrix` attribute that can be queried in the following way:
78 | - `g.gadgetMatrix.matrix[X86_REG_RSP,X86_REG_RAX]` is `True` if and only if there is a dependency from `X86_REG_RAX` before the execution of the gadget to `X86_REG_RSP` after its execution
79 | - `g.gadgetMatrix.chainCond[0,X86_REG_RCX]` is `True` if and only if there is a dependency from `X86_REG_RCX` before the execution of the gadget to `rip` after its execution. In other word: if you control `rcx` before the execution of the gadget, you might be able to control its destination and chain it with other gadgets or code.
80 |
81 | Thus, the previous snippet of code will print all gadgets that overwrite `rsp` to a value influenced by `rax` and jump to an address influenced by `rcx`.
82 |
83 | Since we import [x86_const](https://github.com/aquynh/capstone/blob/4.0.1/bindings/python/capstone/x86_const.py), all the `X86_REG_*` can be directly used as indices to `gadgetMatrix.matrix` and `gadgetMatrix.chainCond`. Other indices can be used:
84 | - `deref`: as an example `g.gadgetMatrix.matrix[deref,X86_REG_RAX]` selects gadgets for which a value influenced by `rax` is dereferenced;
85 | - `memR`: as an example `g.gadgetMatrix.matrix[X86_REG_RBX, memR]` selects gadgets that modify the value of `rbx` with something taken from memory (together with `g.gadgetMatrix.matrix[deref,X86_REG_RAX]` and `g.gadgetMatrix.matrix[X86_REG_RBX,X86_REG_RAX]`, it would select gadgets that modify the value of `rbx` with something pointed to by `rax`);
86 | - `stackTop + `: as an example `g.gadgetMatrix.matrix[X86_REG_RCX, stackTop+2]` selects gadgets that modify the value of `rcx` with something influenced by the second cell of the stack (i.e. `[rsp+0X10]`). Just make sure that `stackTop+x` is between `sF` and `sL` as the size of the pseudo-stack is limited. Negative values of `x` refer to cells out of the stack.
87 |
88 | ## When to use TBrop
89 | When you feel desperate. Seriously, start with [rp++](https://github.com/0vercl0k/rp) or [ROPGenerator](https://github.com/Boyan-MILANOV/ropgenerator).
90 |
91 | If you cannot grep your way out of a huge gadgets listing, or cannot express your constraints, or load your target binary, with a semantic tool, then you might want to give TBrop a try.
92 |
93 | As an example, if you control `rip` and the buffer pointed to by `rsp+8`, TBrop might help you find a stack pivot (along with a few silly suggestions):
94 | ```nasm
95 | mov rcx, qword ptr [rsp + 8]; # rcx now points to the buffer you control
96 | mov byte ptr [rsp], dl;
97 | mov rax, qword ptr [rcx]; # thus you control rax
98 | mov rdi, rcx;
99 | call qword ptr [rax + 0x48]; # and can jump wherever you want, while rcx points to your buffer
100 |
101 | mov rsp, rcx;
102 | ret
103 | ```
104 |
105 | Another use case is if you find yourself working with an exotic architecture and do not want to encode the whole precise semantic of instructions, you can try to retrieve the taint propagation rules of instructions (with [TaintInduce](https://github.com/melynx/taintinduce) or another approach) and implement the corresponding architecture for TBrop (good luck with that).
106 |
107 | ---
108 | Originally developped by [@iNod3](https://github.com/iNod3) and [@clslgrnc]() at [@DGA-MI-SSI](https://github.com/DGA-MI-SSI/T-Brop).
--------------------------------------------------------------------------------
/requirements.in:
--------------------------------------------------------------------------------
1 | capstone
2 | ipython
3 | lief
4 | networkx
5 | numpy
6 | scipy
7 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | #
2 | # This file is autogenerated by pip-compile with Python 3.10
3 | # by the following command:
4 | #
5 | # pip-compile
6 | #
7 | asttokens==2.2.1
8 | # via stack-data
9 | backcall==0.2.0
10 | # via ipython
11 | capstone==5.0.0.post1
12 | # via -r requirements.in
13 | decorator==5.1.1
14 | # via ipython
15 | executing==1.2.0
16 | # via stack-data
17 | ipython==8.14.0
18 | # via -r requirements.in
19 | jedi==0.18.2
20 | # via ipython
21 | lief==0.13.2
22 | # via -r requirements.in
23 | matplotlib-inline==0.1.6
24 | # via ipython
25 | networkx==3.1
26 | # via -r requirements.in
27 | numpy==1.25.1
28 | # via
29 | # -r requirements.in
30 | # scipy
31 | parso==0.8.3
32 | # via jedi
33 | pexpect==4.8.0
34 | # via ipython
35 | pickleshare==0.7.5
36 | # via ipython
37 | prompt-toolkit==3.0.39
38 | # via ipython
39 | ptyprocess==0.7.0
40 | # via pexpect
41 | pure-eval==0.2.2
42 | # via stack-data
43 | pygments==2.15.1
44 | # via ipython
45 | scipy==1.11.1
46 | # via -r requirements.in
47 | six==1.16.0
48 | # via asttokens
49 | stack-data==0.6.2
50 | # via ipython
51 | traitlets==5.9.0
52 | # via
53 | # ipython
54 | # matplotlib-inline
55 | wcwidth==0.2.6
56 | # via prompt-toolkit
57 |
--------------------------------------------------------------------------------
/sonar-project.properties:
--------------------------------------------------------------------------------
1 | sonar.projectKey=clslgrnc_tbrop
2 | sonar.organization=clslgrnc-github
3 |
4 | # This is the name and version displayed in the SonarCloud UI.
5 | sonar.projectName=tbrop
6 | sonar.projectVersion=0.1
7 |
8 | # Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
9 | sonar.sources=tbrop
10 |
11 | # Encoding of the source code. Default is default system encoding
12 | sonar.sourceEncoding=UTF-8
13 |
--------------------------------------------------------------------------------
/t-brop.py:
--------------------------------------------------------------------------------
1 | import argparse
2 |
3 | import lief
4 | from capstone.x86_const import *
5 | from IPython import embed
6 |
7 | from tbrop.collection import GadgetsCollection
8 |
9 | parser = argparse.ArgumentParser()
10 | parser.add_argument("file")
11 |
12 | group = parser.add_mutually_exclusive_group()
13 | group.add_argument(
14 | "-b", "--bytes", metavar="N", type=int, help="search gadgets up to N bytes"
15 | )
16 | group.add_argument(
17 | "-c",
18 | "--cost",
19 | metavar="N",
20 | type=int,
21 | help="search gadgets up to a cost of N (default)",
22 | )
23 | group.add_argument(
24 | "-i", "--instr", metavar="N", type=int, help="search gadgets up to N instructions"
25 | )
26 |
27 |
28 | REG64_codes = [
29 | X86_REG_RAX,
30 | X86_REG_RBX,
31 | X86_REG_RCX,
32 | X86_REG_RDX,
33 | X86_REG_RSI,
34 | X86_REG_RDI,
35 | X86_REG_RBP,
36 | X86_REG_R8,
37 | X86_REG_R9,
38 | X86_REG_R10,
39 | X86_REG_R11,
40 | X86_REG_R12,
41 | X86_REG_R13,
42 | X86_REG_R14,
43 | X86_REG_R15,
44 | ]
45 | REG64_strings = [
46 | "X86_REG_RAX",
47 | "X86_REG_RBX",
48 | "X86_REG_RCX",
49 | "X86_REG_RDX",
50 | "X86_REG_RSI",
51 | "X86_REG_RDI",
52 | "X86_REG_RBP",
53 | "X86_REG_R8",
54 | "X86_REG_R9",
55 | "X86_REG_R10",
56 | "X86_REG_R11",
57 | "X86_REG_R12",
58 | "X86_REG_R13",
59 | "X86_REG_R14",
60 | "X86_REG_R15",
61 | ]
62 |
63 |
64 | def limit(gdgtCol, gadget, bound, context):
65 | if bound < context:
66 | gdgtcpy = gadget.copy()
67 | gdgtCol.add_gadget(gdgtcpy)
68 | return True
69 | elif bound == context:
70 | gdgtCol.add_gadget(gadget)
71 | return False
72 | else:
73 | return False
74 |
75 |
76 | def limitNbrInsts(gdgtCol, gadget, context):
77 | bound = gadget.gadgetMatrix.nbrInsts
78 | return limit(gdgtCol, gadget, bound, context)
79 |
80 |
81 | def limitNbrBytes(gdgtCol, gadget, context):
82 | bound = len(gadget.bytes())
83 | return limit(gdgtCol, gadget, bound, context)
84 |
85 |
86 | def limitCost(gdgtCol, gadget, context):
87 | bound = gadget.cost()
88 | return limit(gdgtCol, gadget, bound, context)
89 |
90 |
91 | if __name__ == "__main__":
92 | args = parser.parse_args()
93 |
94 | print("\nParsing", args.file)
95 | binary = lief.parse(args.file)
96 |
97 | sctext = None
98 |
99 | for section in binary.sections:
100 | if section.name == ".text":
101 | sctext = section
102 | break
103 |
104 | gdgtCollection = GadgetsCollection("x64", bytearray(sctext.content))
105 |
106 | callback = limitCost
107 | context = 64
108 |
109 | if args.bytes != None:
110 | callback = limitNbrBytes
111 | context = args.bytes
112 | elif args.instr != None:
113 | callback = limitNbrInsts
114 | context = args.instr
115 | elif args.cost != None:
116 | context = args.cost
117 |
118 | print("\nGathering gadgets")
119 | gdgtCollection.collect(callback=callback, context=context)
120 |
121 | print("\n", len(gdgtCollection.gadgets), " gadgets found.\n")
122 |
123 | sF = gdgtCollection.arch.stackFirst
124 | stackTop = gdgtCollection.arch.stackTop
125 | sL = gdgtCollection.arch.stackLast
126 |
127 | STACK_codes = [i for i in range(sF, sL + 1)]
128 | STACK_strings = ["stack_" + str(i - stackTop) for i in range(sF, sL + 1)]
129 |
130 | deref = gdgtCollection.arch.deref
131 | memR = gdgtCollection.arch.memRead
132 |
133 | embed()
134 |
--------------------------------------------------------------------------------
/tbrop/arch.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import numpy as np
4 | from scipy import sparse
5 |
6 | import capstone
7 | from capstone.x86_const import *
8 |
9 | # must be at least 1 for shared mem/stack
10 | # at least 2 for separate mem/stack
11 | MEM_RESERVED_INDICES = 58
12 |
13 | STACK_PROP = 4 # stack proportions: 1/n over top, (n-1)/n under top
14 |
15 |
16 | STACK_MAX_DIFF = 0x8000 # if we look further than that, we are not in the stack anymore
17 |
18 |
19 | class Arch:
20 | def __init__(self, dependencies):
21 | assert MEM_RESERVED_INDICES > 6 + STACK_PROP
22 |
23 | self.matrix = dependencies
24 | self.size, _ = dependencies.shape
25 |
26 | self.deref = self.size - MEM_RESERVED_INDICES
27 |
28 | self.memRead = self.deref + 1
29 | self.memWrite = self.memRead + 1
30 |
31 | self.stackRead = self.size - 2
32 | self.stackWrite = self.size - 1
33 | self.stackOverRead = self.memWrite + 1
34 | self.stackOverWrite = self.stackOverRead + 1
35 | self.stackSize = self.stackRead - self.stackOverWrite - 1
36 |
37 | self.stackTop = self.stackOverWrite + 1 + (self.stackSize // STACK_PROP)
38 |
39 | self.stackFirst = self.stackOverWrite + 1
40 | self.stackLast = self.stackRead - 1
41 |
42 | assert (
43 | self.stackOverWrite
44 | < self.stackFirst
45 | < self.stackTop
46 | < self.stackLast
47 | < self.stackRead
48 | )
49 | assert self.stackFirst + self.stackSize == self.stackLast + 1
50 |
51 | self.stackREG = 0
52 | self.flagREG = 0
53 | self.opTypeINVALID = None
54 | self.opTypeREG = None
55 | self.opTypeIMM = None
56 | self.opTypeMEM = None
57 | self.opTypeFP = None
58 |
59 | self.addrSize = 8 # in bytes
60 |
61 | self.regDepDict = {}
62 |
63 | def getRegDependencies(self, id_):
64 | result = self.regDepDict.get(id_)
65 | if result is not None:
66 | return result
67 |
68 | _, childrens = self.matrix.getrow(id_).nonzero()
69 | parents, _ = self.matrix.getcol(id_).nonzero()
70 | parents = list(parents)
71 | childrens = list(childrens)
72 | parents.remove(id_)
73 | childrens.remove(id_)
74 | self.regDepDict[id_] = parents, childrens
75 | return parents, childrens
76 |
77 | # return index of stack cell at offset (in number of cells)
78 | def indexStackRead(self, offsetCell):
79 | index = self.stackTop + offsetCell
80 | if index < self.stackFirst:
81 | return self.stackOverRead
82 | elif index > self.stackLast:
83 | return self.stackRead
84 | else:
85 | return index
86 |
87 | # return index of stack cell at offset (in number of cells)
88 | def indexStackWrite(self, offsetCell):
89 | index = self.stackTop + offsetCell
90 | if index < self.stackFirst:
91 | return self.stackOverWrite
92 | elif index > self.stackLast:
93 | return self.stackWrite
94 | else:
95 | return index
96 |
97 | def shiftStack(self, offsetByte):
98 | stackDispl = offsetByte // self.addrSize
99 | reg_reset = set(range(self.stackFirst, self.stackLast + 1))
100 | flows = []
101 | flows.append(([self.stackREG], [self.stackREG]))
102 |
103 | for i in range(self.stackFirst, self.stackLast + 1):
104 |
105 | srcs = [self.indexStackRead(i - self.stackTop + stackDispl)]
106 | if offsetByte % self.addrSize != 0:
107 | srcs.append(self.indexStackRead(i - self.stackTop + stackDispl + 1))
108 | flows.append(([i], srcs))
109 |
110 | dsts = [self.indexStackWrite(i - self.stackTop - stackDispl)]
111 | if offsetByte % self.addrSize != 0:
112 | dsts.append(self.indexStackWrite(i - self.stackTop - (stackDispl + 1)))
113 | flows.append((dsts, [i]))
114 |
115 | if offsetByte > self.addrSize * self.stackSize:
116 | flows.append(([self.stackOverWrite], [self.stackRead]))
117 | elif offsetByte < -self.addrSize * self.stackSize:
118 | flows.append(([self.stackWrite], [self.stackOverRead]))
119 |
120 | flows.append(([self.deref], [self.stackREG]))
121 |
122 | return reg_reset, flows
123 |
124 | def killStack(self, killer=None):
125 | if killer is None:
126 | killer = []
127 | reg_reset = set(range(self.stackFirst, self.stackLast + 1))
128 | reg_reset.update(
129 | [self.stackOverRead, self.stackOverWrite, self.stackRead, self.stackWrite]
130 | )
131 | flows = [
132 | (list(reg_reset), [self.memRead] + killer),
133 | ([self.memWrite], list(reg_reset)),
134 | ]
135 | return reg_reset, flows
136 |
137 | def corruptedStack(self, instW):
138 | if self.stackREG in instW:
139 | return True
140 | _, childrens = self.getRegDependencies(self.stackREG)
141 | for reg in childrens:
142 | if reg in instW:
143 | return True
144 | return False
145 |
146 | def getOperandIndices(self, op):
147 | opR = []
148 | opW = []
149 | deref = []
150 |
151 | op_type = op.type
152 | op_access = op.access
153 | op_reg = op.reg
154 | if op_type == self.opTypeREG:
155 | if op_access & capstone.CS_AC_READ:
156 | opR.append(op_reg)
157 | if op_access & capstone.CS_AC_WRITE:
158 | opW.append(op_reg)
159 | elif op_type == self.opTypeMEM:
160 | # TODO: check if base (and/or index?) is RSP
161 |
162 | op_mem_base = op.mem.base
163 | op_mem_index = op.mem.index
164 | if op_mem_base != 0:
165 | deref.append(op_mem_base)
166 | if op_mem_index != 0:
167 | deref.append(op_mem_index)
168 |
169 | # Are we in the stack?
170 | op_mem_disp = op.mem.disp
171 | if (
172 | op_mem_base == self.stackREG
173 | and op_mem_index == 0
174 | and abs(op_mem_disp) < STACK_MAX_DIFF
175 | ):
176 | stackDispl = op_mem_disp // self.addrSize
177 | if op_access & capstone.CS_AC_READ or op_access == 0:
178 | opR.append(self.indexStackRead(stackDispl))
179 | if op_mem_disp % self.addrSize != 0:
180 | opR.append(self.indexStackRead(stackDispl + 1))
181 | if op_access & capstone.CS_AC_WRITE:
182 | opW.append(self.indexStackWrite(stackDispl))
183 | if op_mem_disp % self.addrSize != 0:
184 | opW.append(self.indexStackWrite(stackDispl + 1))
185 | else:
186 | if op_access & capstone.CS_AC_READ or op_access == 0:
187 | opR.append(self.memRead)
188 | opR.extend(deref)
189 | # We only consider deref as interesting flows on memory reads
190 | if op_access & capstone.CS_AC_WRITE:
191 | opW.append(self.memWrite)
192 | return opW, opR, deref
193 |
194 | def checkInstFlows(self, inst, reg_reset, flows):
195 | for index in reg_reset:
196 | if index < 0 or index >= self.size:
197 | print(inst.mnemonic, inst.op_str)
198 | raise IndexError
199 |
200 | for dst, src in flows:
201 | for index in dst:
202 | if index < 0 or index >= self.size:
203 | print(inst.mnemonic, inst.op_str)
204 | raise IndexError
205 | for index in src:
206 | if index < 0 or index >= self.size:
207 | print(inst.mnemonic, inst.op_str)
208 | raise IndexError
209 |
210 | return reg_reset, flows
211 |
212 | def getInstFlows(self, inst):
213 | src, dst = inst.regs_access()
214 | # if src == (): src = []
215 | # if dst == (): dst = []
216 | reg_reset = set(dst)
217 | dst = set(dst)
218 | src = set(src)
219 | ##################
220 | # HORRIBLE HACK
221 | # self.stackREG is implicitely used only in pop/push/ret/call (right?)
222 | # they should be properly handled
223 | # this is necessary if I do not want:
224 | # mov qword ptr [rsp], rax
225 | # to imply a dependency stack_0 <--- rax, _rsp_
226 | src.discard(self.stackREG)
227 | dst.discard(self.stackREG)
228 | reg_reset.discard(self.stackREG)
229 | ##################
230 | allDeref = set()
231 | for op in inst.operands:
232 | opW, opR, deref = self.getOperandIndices(op)
233 | src.update(opR)
234 | dst.update(opW)
235 | reg_reset.update(opW)
236 | allDeref.update(deref)
237 | stackReset = set(opW).intersection(
238 | range(self.stackFirst, self.stackLast + 1)
239 | )
240 | # if a write span several stack cells, they should not be reseted
241 | if len(stackReset) == 1:
242 | reg_reset.update(stackReset)
243 | # this is not a satisfying solution, we do not know here the size of the write!
244 | flows = [(dst, src), ([self.deref], allDeref)]
245 | if self.corruptedStack(dst):
246 | reg_resetStack, flowStack = self.killStack(list(src))
247 | reg_reset.update(reg_resetStack)
248 | flows = flows + flowStack
249 | # return self.checkInstFlows(inst, reg_reset, flows)
250 | return reg_reset, flows
251 |
252 | def __str__(self):
253 |
254 | _str = ""
255 |
256 | for i in range(self.size):
257 | _str += "%.3d" % i
258 | for j in range(self.size):
259 | if (i, j) in self.matrix:
260 | _str += "x"
261 | else:
262 | _str += "."
263 | _str += "\n"
264 |
265 |
266 | class Arch_x86_64(Arch):
267 | def __init__(self):
268 | size = (
269 | X86_REG_ENDING + MEM_RESERVED_INDICES
270 | ) # 1 reserved for mem dependencies 1 for bottom of stack, the rest for top of stack
271 | dependencies = sparse.lil_matrix((size, size), dtype=bool)
272 |
273 | for i in range(size):
274 | dependencies[i, i] = True
275 |
276 | # RAX
277 | dependencies[X86_REG_RAX, X86_REG_EAX] = True
278 | dependencies[X86_REG_RAX, X86_REG_AX] = True
279 | dependencies[X86_REG_RAX, X86_REG_AH] = True
280 | dependencies[X86_REG_RAX, X86_REG_AL] = True
281 | dependencies[X86_REG_EAX, X86_REG_AX] = True
282 | dependencies[X86_REG_EAX, X86_REG_AH] = True
283 | dependencies[X86_REG_EAX, X86_REG_AL] = True
284 | dependencies[X86_REG_AX, X86_REG_AH] = True
285 | dependencies[X86_REG_AX, X86_REG_AL] = True
286 | # RBX
287 | dependencies[X86_REG_RBX, X86_REG_EBX] = True
288 | dependencies[X86_REG_RBX, X86_REG_BX] = True
289 | dependencies[X86_REG_RBX, X86_REG_BH] = True
290 | dependencies[X86_REG_RBX, X86_REG_BL] = True
291 | dependencies[X86_REG_EBX, X86_REG_BX] = True
292 | dependencies[X86_REG_EBX, X86_REG_BH] = True
293 | dependencies[X86_REG_EBX, X86_REG_BL] = True
294 | dependencies[X86_REG_BX, X86_REG_BH] = True
295 | dependencies[X86_REG_BX, X86_REG_BL] = True
296 | # RCX
297 | dependencies[X86_REG_RCX, X86_REG_ECX] = True
298 | dependencies[X86_REG_RCX, X86_REG_CX] = True
299 | dependencies[X86_REG_RCX, X86_REG_CH] = True
300 | dependencies[X86_REG_RCX, X86_REG_CL] = True
301 | dependencies[X86_REG_ECX, X86_REG_CX] = True
302 | dependencies[X86_REG_ECX, X86_REG_CH] = True
303 | dependencies[X86_REG_ECX, X86_REG_CL] = True
304 | dependencies[X86_REG_CX, X86_REG_CH] = True
305 | dependencies[X86_REG_CX, X86_REG_CL] = True
306 | # RDX
307 | dependencies[X86_REG_RDX, X86_REG_EDX] = True
308 | dependencies[X86_REG_RDX, X86_REG_DX] = True
309 | dependencies[X86_REG_RDX, X86_REG_DH] = True
310 | dependencies[X86_REG_RDX, X86_REG_DL] = True
311 | dependencies[X86_REG_EDX, X86_REG_DX] = True
312 | dependencies[X86_REG_EDX, X86_REG_DH] = True
313 | dependencies[X86_REG_EDX, X86_REG_DL] = True
314 | dependencies[X86_REG_DX, X86_REG_DH] = True
315 | dependencies[X86_REG_DX, X86_REG_DL] = True
316 | # R8
317 | dependencies[X86_REG_R8, X86_REG_R8D] = True
318 | dependencies[X86_REG_R8, X86_REG_R8W] = True
319 | dependencies[X86_REG_R8, X86_REG_R8B] = True
320 | dependencies[X86_REG_R8D, X86_REG_R8W] = True
321 | dependencies[X86_REG_R8D, X86_REG_R8B] = True
322 | dependencies[X86_REG_R8W, X86_REG_R8B] = True
323 | # R9
324 | dependencies[X86_REG_R9, X86_REG_R9D] = True
325 | dependencies[X86_REG_R9, X86_REG_R9W] = True
326 | dependencies[X86_REG_R9, X86_REG_R9B] = True
327 | dependencies[X86_REG_R9D, X86_REG_R9W] = True
328 | dependencies[X86_REG_R9D, X86_REG_R9B] = True
329 | dependencies[X86_REG_R9W, X86_REG_R9B] = True
330 | # R10
331 | dependencies[X86_REG_R10, X86_REG_R10D] = True
332 | dependencies[X86_REG_R10, X86_REG_R10W] = True
333 | dependencies[X86_REG_R10, X86_REG_R10B] = True
334 | dependencies[X86_REG_R10D, X86_REG_R10W] = True
335 | dependencies[X86_REG_R10D, X86_REG_R10B] = True
336 | dependencies[X86_REG_R10W, X86_REG_R10B] = True
337 | # R11
338 | dependencies[X86_REG_R11, X86_REG_R11D] = True
339 | dependencies[X86_REG_R11, X86_REG_R11W] = True
340 | dependencies[X86_REG_R11, X86_REG_R11B] = True
341 | dependencies[X86_REG_R11D, X86_REG_R11W] = True
342 | dependencies[X86_REG_R11D, X86_REG_R11B] = True
343 | dependencies[X86_REG_R11W, X86_REG_R11B] = True
344 | # R12
345 | dependencies[X86_REG_R12, X86_REG_R12D] = True
346 | dependencies[X86_REG_R12, X86_REG_R12W] = True
347 | dependencies[X86_REG_R12, X86_REG_R12B] = True
348 | dependencies[X86_REG_R12D, X86_REG_R12W] = True
349 | dependencies[X86_REG_R12D, X86_REG_R12B] = True
350 | dependencies[X86_REG_R12W, X86_REG_R12B] = True
351 | # R13
352 | dependencies[X86_REG_R13, X86_REG_R13D] = True
353 | dependencies[X86_REG_R13, X86_REG_R13W] = True
354 | dependencies[X86_REG_R13, X86_REG_R13B] = True
355 | dependencies[X86_REG_R13D, X86_REG_R13W] = True
356 | dependencies[X86_REG_R13D, X86_REG_R13B] = True
357 | dependencies[X86_REG_R13W, X86_REG_R13B] = True
358 | # R14
359 | dependencies[X86_REG_R14, X86_REG_R14D] = True
360 | dependencies[X86_REG_R14, X86_REG_R14W] = True
361 | dependencies[X86_REG_R14, X86_REG_R14B] = True
362 | dependencies[X86_REG_R14D, X86_REG_R14W] = True
363 | dependencies[X86_REG_R14D, X86_REG_R14B] = True
364 | dependencies[X86_REG_R14W, X86_REG_R14B] = True
365 | # R15
366 | dependencies[X86_REG_R15, X86_REG_R15D] = True
367 | dependencies[X86_REG_R15, X86_REG_R15W] = True
368 | dependencies[X86_REG_R15, X86_REG_R15B] = True
369 | dependencies[X86_REG_R15D, X86_REG_R15W] = True
370 | dependencies[X86_REG_R15D, X86_REG_R15B] = True
371 | dependencies[X86_REG_R15W, X86_REG_R15B] = True
372 | # RSP
373 | dependencies[X86_REG_RSP, X86_REG_ESP] = True
374 | dependencies[X86_REG_RSP, X86_REG_SP] = True
375 | dependencies[X86_REG_RSP, X86_REG_SPL] = True
376 | dependencies[X86_REG_ESP, X86_REG_SP] = True
377 | dependencies[X86_REG_ESP, X86_REG_SPL] = True
378 | dependencies[X86_REG_SP, X86_REG_SPL] = True
379 | # RBP
380 | dependencies[X86_REG_RBP, X86_REG_EBP] = True
381 | dependencies[X86_REG_RBP, X86_REG_BP] = True
382 | dependencies[X86_REG_RBP, X86_REG_BPL] = True
383 | dependencies[X86_REG_EBP, X86_REG_BP] = True
384 | dependencies[X86_REG_EBP, X86_REG_BPL] = True
385 | dependencies[X86_REG_BP, X86_REG_BPL] = True
386 | # RSI
387 | dependencies[X86_REG_RSI, X86_REG_ESI] = True
388 | dependencies[X86_REG_RSI, X86_REG_SI] = True
389 | dependencies[X86_REG_RSI, X86_REG_SIL] = True
390 | dependencies[X86_REG_ESI, X86_REG_SI] = True
391 | dependencies[X86_REG_ESI, X86_REG_SIL] = True
392 | dependencies[X86_REG_SI, X86_REG_SIL] = True
393 | # RDI
394 | dependencies[X86_REG_RDI, X86_REG_EDI] = True
395 | dependencies[X86_REG_RDI, X86_REG_DI] = True
396 | dependencies[X86_REG_RDI, X86_REG_DIL] = True
397 | dependencies[X86_REG_EDI, X86_REG_DI] = True
398 | dependencies[X86_REG_EDI, X86_REG_DIL] = True
399 | dependencies[X86_REG_DI, X86_REG_DIL] = True
400 | # RIP
401 | # dependencies[X86_REG_RIP, X86_REG_EIP] = True
402 | # dependencies[X86_REG_RIP, X86_REG_IP] = True
403 | # dependencies[X86_REG_EIP, X86_REG_IP] = True
404 |
405 | matrix = dependencies.tocsr(True)
406 |
407 | Arch.__init__(self, matrix)
408 |
409 | self.opTypeINVALID = X86_OP_INVALID
410 | self.opTypeREG = X86_OP_REG
411 | self.opTypeIMM = X86_OP_IMM
412 | self.opTypeMEM = X86_OP_MEM
413 | # self.opTypeFP = X86_OP_FP
414 |
415 | self.stackREG = X86_REG_RSP
416 | self.flagREG = X86_REG_EFLAGS
417 |
418 | self.addrSize = 8
419 |
420 | def getInstFlows(self, inst):
421 |
422 | # print "%s %s" % (inst.mnemonic, inst.op_str)
423 | if inst.mnemonic == "lea":
424 | src, dst = inst.regs_access()
425 | if src == ():
426 | src = []
427 | if dst == ():
428 | dst = []
429 | return set(dst), [(dst, src)]
430 |
431 | elif inst.mnemonic.startswith("pusha") or inst.mnemonic.startswith("popa"):
432 | # raise Exception("TODO: deal with pusha/popa")
433 | return Arch.getInstFlows(self, inst)
434 |
435 | elif inst.mnemonic.startswith("push") or capstone.CS_GRP_CALL in inst.groups:
436 | reg_reset = set(range(self.stackFirst, self.stackLast + 1))
437 | flows = [([], []) for i in range(self.stackSize + 3)]
438 |
439 | flows[0] = ([self.stackFirst], [self.stackOverRead])
440 | for i in range(1, self.stackTop - self.stackFirst):
441 | flows[i] = ([self.stackFirst + i], [self.stackFirst + i - 1])
442 |
443 | if capstone.CS_GRP_CALL in inst.groups:
444 | # TODO: should we ignore RIP dependencies? (because RIP is a constant at a given address...)
445 | # flowSTop = [self.stackTopIndex],[X86_REG_RIP]
446 | # reg_reset.add(X86_REG_RIP)
447 | opW, opR, deref = self.getOperandIndices(inst.operands[0])
448 | assert opW == []
449 | flowSTop = [self.stackTop], []
450 | flows[self.stackSize + 2] = [self.deref], deref + [self.stackREG]
451 | elif inst.mnemonic.startswith("pushf"):
452 | flowSTop = [self.stackTop], [self.flagREG]
453 | flows[self.stackSize + 2] = [self.deref], [self.stackREG]
454 | else:
455 | opW, opR, deref = self.getOperandIndices(inst.operands[0])
456 | assert opW == []
457 | flowSTop = ([self.stackTop] + opW), opR + deref
458 | flows[self.stackSize + 2] = [self.deref], deref + [self.stackREG]
459 | flows[self.stackTop - self.stackFirst] = flowSTop
460 |
461 | for i in range(self.stackTop - self.stackFirst + 1, self.stackSize):
462 | flows[i] = ([self.stackFirst + i], [self.stackFirst + i - 1])
463 |
464 | flows[self.stackSize] = [self.stackWrite], [self.stackLast]
465 |
466 | flows[self.stackSize + 1] = [self.stackREG, self.deref], [self.stackREG]
467 | reg_reset.add(self.stackREG)
468 |
469 | return reg_reset, flows
470 |
471 | elif inst.mnemonic.startswith("popf") or inst.mnemonic == "pop":
472 | reg_reset = set(range(self.stackFirst, self.stackLast + 1))
473 | flows = [([], []) for i in range(self.stackSize + 3)]
474 |
475 | flows[0] = ([self.stackOverWrite], [self.stackFirst])
476 | for i in range(1, self.stackTop - self.stackFirst):
477 | flows[i] = ([self.stackFirst + i - 1], [self.stackFirst + i])
478 |
479 | if inst.mnemonic.startswith("popf"):
480 | opW = [self.flagREG]
481 | deref = []
482 | else:
483 | opW, opR, deref = self.getOperandIndices(inst.operands[0])
484 | assert opR == []
485 | # We only consider deref as interesting flows on memory reads
486 | reg_reset.update(opW)
487 | flows[self.stackSize + 2] = [self.deref], deref + [self.stackREG]
488 | flows[self.stackTop - self.stackFirst] = (
489 | opW + [self.stackTop - 1],
490 | [self.stackTop],
491 | )
492 |
493 | for i in range(self.stackTop - self.stackFirst + 1, self.stackSize):
494 | flows[i] = ([self.stackFirst + i - 1], [self.stackFirst + i])
495 |
496 | flows[self.stackSize] = [self.stackLast], [self.stackRead]
497 |
498 | flows[self.stackSize + 1] = [self.stackREG, self.deref], [self.stackREG]
499 | reg_reset.add(self.stackREG)
500 |
501 | return reg_reset, flows
502 |
503 | elif (
504 | inst.mnemonic == "xor"
505 | and inst.operands[0].type == inst.operands[1].type == self.opTypeREG
506 | and inst.operands[0].reg == inst.operands[1].reg
507 | ):
508 | if self.corruptedStack([inst.operands[0].reg]):
509 | reg_resetStack, flowStack = self.killStack()
510 | reg_resetStack.update([inst.operands[0].reg, self.flagREG])
511 | return reg_resetStack, flowStack
512 | else:
513 | return set([inst.operands[0].reg, self.flagREG]), []
514 |
515 | elif inst.mnemonic == "xchg":
516 | regReset = set()
517 | if inst.operands[0].type == self.opTypeREG:
518 | regReset.add(inst.operands[0].reg)
519 | if inst.operands[1].type == self.opTypeREG:
520 | regReset.add(inst.operands[1].reg)
521 | opW0, opR0, deref0 = self.getOperandIndices(inst.operands[0])
522 | opW1, opR1, deref1 = self.getOperandIndices(inst.operands[1])
523 |
524 | flows = [
525 | (opW0, opR1 + deref1),
526 | (opW1, opR0 + deref0),
527 | ([self.deref], deref0 + deref1),
528 | ]
529 |
530 | if self.corruptedStack(opW0 + opW1):
531 | reg_resetStack, flowStack = self.killStack()
532 | regReset.update(reg_resetStack)
533 | flows = flows + flowStack
534 | return regReset, flows
535 |
536 | elif capstone.CS_GRP_RET in inst.groups:
537 | displ = self.addrSize
538 | if len(inst.operands) == 1 and inst.operands[0].type == self.opTypeIMM:
539 | displ += inst.operands[0].imm
540 | return self.shiftStack(displ)
541 |
542 | elif (
543 | (inst.mnemonic == "add" or inst.mnemonic == "sub")
544 | and inst.operands[0].type == self.opTypeREG
545 | and (
546 | inst.operands[0].reg == X86_REG_RSP
547 | or inst.operands[0].reg == X86_REG_ESP
548 | )
549 | and inst.operands[1].type == self.opTypeIMM
550 | and abs(inst.operands[1].imm) < STACK_MAX_DIFF
551 | ):
552 | displ = inst.operands[1].imm
553 | if inst.mnemonic == "sub":
554 | displ = -displ
555 |
556 | reg_reset, flows = self.shiftStack(displ)
557 |
558 | reg_reset.add(self.flagREG)
559 | flows.append(([self.flagREG], [self.stackREG]))
560 |
561 | return reg_reset, flows
562 |
563 | else:
564 | return Arch.getInstFlows(self, inst)
565 |
566 |
567 | class Arch_x86_32(Arch_x86_64):
568 | def __init__(self):
569 |
570 | Arch_x86_64.__init__(self)
571 |
572 | # RAX
573 | self.matrix[X86_REG_RAX, X86_REG_EAX] = False
574 | self.matrix[X86_REG_RAX, X86_REG_AX] = False
575 | self.matrix[X86_REG_RAX, X86_REG_AH] = False
576 | self.matrix[X86_REG_RAX, X86_REG_AL] = False
577 | # RBX
578 | self.matrix[X86_REG_RBX, X86_REG_EBX] = False
579 | self.matrix[X86_REG_RBX, X86_REG_BX] = False
580 | self.matrix[X86_REG_RBX, X86_REG_BH] = False
581 | self.matrix[X86_REG_RBX, X86_REG_BL] = False
582 | # RCX
583 | self.matrix[X86_REG_RCX, X86_REG_ECX] = False
584 | self.matrix[X86_REG_RCX, X86_REG_CX] = False
585 | self.matrix[X86_REG_RCX, X86_REG_CH] = False
586 | self.matrix[X86_REG_RCX, X86_REG_CL] = False
587 | # RDX
588 | self.matrix[X86_REG_RDX, X86_REG_EDX] = False
589 | self.matrix[X86_REG_RDX, X86_REG_DX] = False
590 | self.matrix[X86_REG_RDX, X86_REG_DH] = False
591 | self.matrix[X86_REG_RDX, X86_REG_DL] = False
592 | # RSP
593 | self.matrix[X86_REG_RSP, X86_REG_ESP] = False
594 | self.matrix[X86_REG_RSP, X86_REG_SP] = False
595 | self.matrix[X86_REG_RSP, X86_REG_SPL] = False
596 | # RBP
597 | self.matrix[X86_REG_RBP, X86_REG_EBP] = False
598 | self.matrix[X86_REG_RBP, X86_REG_BP] = False
599 | self.matrix[X86_REG_RBP, X86_REG_BPL] = False
600 | # RSI
601 | self.matrix[X86_REG_RSI, X86_REG_ESI] = False
602 | self.matrix[X86_REG_RSI, X86_REG_SI] = False
603 | self.matrix[X86_REG_RSI, X86_REG_SIL] = False
604 | # RDI
605 | self.matrix[X86_REG_RDI, X86_REG_EDI] = False
606 | self.matrix[X86_REG_RDI, X86_REG_DI] = False
607 | self.matrix[X86_REG_RDI, X86_REG_DIL] = False
608 |
609 | self.addrSize = 4
610 | self.stackREG = X86_REG_ESP
611 |
612 |
613 | SUPPORTED_ARCH = {"x64": Arch_x86_64, "x86": Arch_x86_32}
614 |
--------------------------------------------------------------------------------
/tbrop/collection.py:
--------------------------------------------------------------------------------
1 | # Replacement for dumbGadget.py
2 |
3 | from capstone import *
4 |
5 | from tbrop.arch import SUPPORTED_ARCH
6 | from tbrop.gadget import *
7 | from tbrop.graph import build_graph_from_bytes, clean_up_graph
8 |
9 | X86_MAX_INST_LEN = 16
10 |
11 |
12 | class GadgetsCollection:
13 | def __init__(self, target_arch, data, offset=0, gentryPoints=None):
14 | self.data = data
15 |
16 | arch_class = SUPPORTED_ARCH.get(target_arch)
17 | if arch_class is None:
18 | raise Exception("ArchitectureNotSupported")
19 |
20 | self.arch = arch_class()
21 |
22 | if self.arch.addrSize == 8:
23 | self.md = Cs(CS_ARCH_X86, CS_MODE_64)
24 | self.mdfast = Cs(CS_ARCH_X86, CS_MODE_64)
25 | if self.arch.addrSize == 4:
26 | self.md = Cs(CS_ARCH_X86, CS_MODE_64)
27 | self.mdfast = Cs(CS_ARCH_X86, CS_MODE_64)
28 |
29 | self.md.detail = True
30 | self.mdfast.detail = False
31 |
32 | self.gentryPoints = gentryPoints
33 |
34 | self.disasm_cache = {}
35 | self.offset = offset
36 |
37 | self.init_graph()
38 |
39 | if self.gentryPoints == None:
40 | self.InitEntryPoints()
41 |
42 | self.gadgets = []
43 | self.by_address = {}
44 | self.by_bytes = {}
45 |
46 | self.instCache = {}
47 |
48 | def init_graph(self):
49 | self.graph = build_graph_from_bytes(self.data)
50 | clean_up_graph(self.graph)
51 |
52 | def InitEntryPoints(self):
53 | self.gentryPoints = []
54 | for node in self.graph:
55 | if next(self.graph.successors(node), None) is None:
56 | # no successors
57 | self.gentryPoints.append(node)
58 |
59 | def getPredecessors(self, address, max_ins_size=X86_MAX_INST_LEN):
60 | predecessors = []
61 | for predecessor_address in self.graph.predecessors(address):
62 | for pred in self.md.disasm(
63 | self.data[predecessor_address:],
64 | predecessor_address,
65 | 1,
66 | ):
67 | predecessors.append(pred)
68 | return predecessors
69 |
70 | def add_gadget(self, gadget):
71 | gadget_bytes = gadget.bytes()
72 | duplicate = self.by_bytes.get(gadget_bytes)
73 |
74 | if duplicate is not None:
75 | duplicate.addresses_of_duplicates |= gadget.addresses_of_duplicates
76 | else:
77 | self.by_bytes[gadget_bytes] = gadget
78 | self.gadgets.append(gadget)
79 |
80 | def defaultCallback(self, gadget, context):
81 | # print(str(gadget.max_cost))
82 | if gadget.cost() > gadget.max_cost:
83 | return False
84 | else:
85 | gdgtcpy = gadget.copy()
86 | self.add_gadget(gdgtcpy)
87 | return True
88 |
89 | # @profile
90 | def collect(self, callback=defaultCallback, context=None, max_cost=64):
91 | worklist = {}
92 |
93 | # Init worklist
94 | for address in self.gentryPoints:
95 | gadget = Gadget(
96 | self.arch,
97 | [next(self.md.disasm(self.data[address:], address, 1))],
98 | max_cost=max_cost,
99 | )
100 | gadget_bytes = gadget.bytes()
101 | duplicate = worklist.get(gadget_bytes)
102 |
103 | if duplicate is not None:
104 | duplicate.addresses_of_duplicates |= gadget.addresses_of_duplicates
105 | else:
106 | worklist[gadget_bytes] = gadget
107 |
108 | while worklist != {}:
109 | gadget_bytes, gadget = worklist.popitem()
110 |
111 | if not callback(self, gadget, context):
112 | # We do not want to extend this gadget
113 | continue
114 |
115 | if not gadget.canBeExtended():
116 | # We can not to extend this gadget
117 | continue
118 |
119 | predecessors = []
120 | for first_addr in gadget.addresses_of_duplicates:
121 | # pred = self.getPredecessors(firstInst.address-self.offset)
122 | predecessors.extend(self.getPredecessors(first_addr))
123 |
124 | for inst in predecessors:
125 | new_gadget_bytes = bytes(inst.bytes) + gadget_bytes
126 | new_gadget = worklist.get(new_gadget_bytes)
127 |
128 | if new_gadget is not None:
129 | new_gadget.addresses_of_duplicates.add(inst.address)
130 | else:
131 | new_gadget = gadget.copy()
132 | new_gadget.extend(inst)
133 |
134 | worklist[new_gadget_bytes] = new_gadget
135 |
136 | return
137 |
--------------------------------------------------------------------------------
/tbrop/gadget.py:
--------------------------------------------------------------------------------
1 | from time import time
2 |
3 | import capstone
4 | import numpy as np
5 | from scipy import sparse
6 |
7 | instMatrixDict = {}
8 |
9 |
10 | class InstMatrix(object):
11 | @property
12 | def matrix(self):
13 | return self._matrix
14 |
15 | @matrix.setter
16 | def matrix(self, value):
17 | self._cache_matrix_last_modification = time()
18 | self._matrix = value
19 |
20 | def __init__(self, arch, inst=None):
21 |
22 | self.arch = arch
23 | self.inst = inst
24 |
25 | if inst == None:
26 | self.matrix = None
27 | self.reg_reset = set()
28 | self.flows = []
29 | else:
30 | self.matrix = sparse.identity(arch.size, dtype=bool).tolil()
31 | self.reg_reset, self.flows = self.arch.getInstFlows(inst)
32 | self.initDependencies()
33 |
34 | def removeIdDependencies(self):
35 | for reg in self.reg_reset:
36 | self.matrix[reg, reg] = False
37 | _, childrens = self.arch.getRegDependencies(reg)
38 | for i in childrens:
39 | self.matrix[i, i] = False
40 |
41 | def addCrossDependencies(self, dstList, srcList):
42 | for dst in dstList:
43 | for src in srcList:
44 | self.matrix[dst, src] = True
45 |
46 | def addDependencies(self):
47 | for (dstFlow, srcFlow) in self.flows:
48 | for src in srcFlow:
49 | _, srcChilds = self.arch.getRegDependencies(src)
50 | srcList = [src] + srcChilds
51 | for dst in dstFlow:
52 | dstParents, dstChilds = self.arch.getRegDependencies(dst)
53 | dstList = dstParents + [dst] + dstChilds
54 | self.addCrossDependencies(dstList, srcList)
55 |
56 | def initDependencies(self):
57 | self.removeIdDependencies()
58 | self.addDependencies()
59 | self.matrix = self.matrix.tocsc()
60 |
61 | def printIndexName(self, index, postfix=""):
62 |
63 | if index < self.arch.deref:
64 | return self.inst.reg_name(index) + postfix
65 | elif index == self.arch.deref:
66 | return "deref"
67 | elif index == self.arch.memRead:
68 | return "mem_r"
69 | elif index == self.arch.memWrite:
70 | return "mem_w"
71 | elif index == self.arch.stackRead:
72 | return "stack_r"
73 | elif index == self.arch.stackWrite:
74 | return "stack_w"
75 | elif index == self.arch.stackOverRead:
76 | return "stackOver_r"
77 | elif index == self.arch.stackOverWrite:
78 | return "stackOver_w"
79 | else:
80 | index = index - self.arch.stackTop
81 | if index < 0:
82 | return "stack_{" + str(index) + "}" + postfix
83 | else:
84 | return "stack_" + str(index) + postfix
85 |
86 | def lookupRegisterIndexByName(self, name):
87 |
88 | if name in self.RegisterIndexByNameCache:
89 | return self.RegisterIndexByNameCache[name]
90 |
91 | for index in range(self.arch.deref):
92 | RegisterName = self.inst.reg_name(index)
93 | if name == RegisterName:
94 | self.RegisterIndexByNameCache[RegisterName] = index
95 | return index
96 |
97 | return None
98 |
99 | def lookupDependenceIndexByName(self, name):
100 |
101 | if self.lookupRegisterIndexByName(name):
102 | return self.lookupRegisterIndexByName(name)
103 | elif name == "deref":
104 | return self.arch.deref
105 | elif name == "mem_r":
106 | return self.arch.memRead
107 | elif name == "mem_w":
108 | return self.arch.memWrite
109 | elif name == "stack_r":
110 | return self.arch.stackRead
111 | elif name == "stack_w":
112 | return self.arch.stackWrite
113 | elif name == "stackOver_r":
114 | return self.arch.stackOverRead
115 | elif name == "stackOver_w":
116 | return self.arch.stackOverWrite
117 | else:
118 | pass
119 | # if "stack_" in name:
120 |
121 | # index = index - self.arch.stackTop
122 | # if index < 0:
123 | # return "stack_{"+str(index)+"}" + postfix
124 | # else:
125 | # return "stack_"+str(index) + postfix
126 |
127 | def printRegistersIo(self, verbose=False):
128 |
129 | _str = ""
130 |
131 | depStrings = [None for i in range(self.arch.size)]
132 | for dst, src in zip(*self.matrix.nonzero()):
133 | if dst != src:
134 | SRCparents, _ = self.arch.getRegDependencies(src)
135 | DSTparents, _ = self.arch.getRegDependencies(dst)
136 | bparents = False
137 | for dstP in DSTparents:
138 | bparents = bparents or self.matrix[dstP, src]
139 | for srcP in SRCparents:
140 | bparents = bparents or self.matrix[dst, srcP]
141 | for dstP in DSTparents:
142 | bparents = bparents or self.matrix[dstP, srcP]
143 | if not bparents and (
144 | verbose or dst < self.arch.memRead or src <= self.arch.memRead
145 | ):
146 | if depStrings[dst] == None:
147 | depStrings[dst] = self.printIndexName(src)
148 | else:
149 | depStrings[dst] = (
150 | depStrings[dst] + ", " + self.printIndexName(src)
151 | )
152 | for i in range(self.arch.size):
153 | if depStrings[i] == None:
154 | parents, _ = self.arch.getRegDependencies(i)
155 | if not self.matrix[i, i] and not parents and verbose:
156 | _str += "%s <-/- %s\n" % (
157 | self.printIndexName(i),
158 | self.printIndexName(i),
159 | )
160 | else:
161 | if self.matrix[i, i]:
162 | depStrings[i] = self.printIndexName(i) + ", " + depStrings[i]
163 | _str += "%s <--- %s\n" % (self.printIndexName(i), depStrings[i])
164 |
165 | return _str
166 |
167 | def toStrings(self):
168 | accDiagFalse = ";"
169 | accNDiagTrue = ";"
170 | for i in range(self.arch.size):
171 | if not self.matrix[i, i]:
172 | accDiagFalse += "!" + str(i) + ";"
173 | for i, j in zip(*self.matrix.nonzero()):
174 | if i != j:
175 | accNDiagTrue += str(i) + "," + str(j) + ";"
176 | return accDiagFalse, accNDiagTrue
177 |
178 | def toSets(self):
179 | def UpdateToSets(self):
180 | accDiagFalse = set()
181 | accNDiagTrue = set()
182 |
183 | diagonal = self.matrix.diagonal()
184 | for State, Index in zip(diagonal, range(len(diagonal))):
185 | if State == False:
186 | accDiagFalse.add(Index)
187 |
188 | for i, j in zip(*self.matrix.nonzero()):
189 | if i != j:
190 | accNDiagTrue.add((i, j))
191 | return accDiagFalse, accNDiagTrue
192 |
193 | if "_cache_to_sets" not in self.__dict__:
194 | self._cache_to_sets = UpdateToSets(self)
195 | elif self._cache_matrix_last_modification > time():
196 | self._cache_to_sets = UpdateToSets(self)
197 |
198 | return self._cache_to_sets
199 |
200 |
201 | class GadgetMatrix(InstMatrix):
202 | def __init__(self, arch, chainInst=None):
203 | InstMatrix.__init__(self, arch, None)
204 |
205 | self.chainCond = None
206 |
207 | # we do not need those for gadgets
208 | self.reg_access_read = None
209 | self.reg_access_write = None
210 | self.flows = None
211 | self.nbrInsts = 0
212 | self.nbrBytes = 0
213 |
214 | if chainInst != None:
215 | self.addInst(chainInst)
216 |
217 | def initChainCond(self, chainInst):
218 |
219 | if self.inst == None:
220 | self.inst = chainInst
221 | self.matrix = sparse.identity(self.arch.size, dtype=bool).tocsr()
222 | # groups = chainInst.groups
223 | self.chainCond = sparse.lil_matrix((1, self.arch.size), dtype=bool)
224 | len_chainInst_operands = len(chainInst.operands)
225 | if capstone.CS_GRP_RET in chainInst.groups:
226 | if len_chainInst_operands == 0:
227 | self.chainCond[0, self.arch.stackTop] = True
228 | # I am not sure we still are arch independent
229 | elif (
230 | len_chainInst_operands == 1
231 | and chainInst.operands[0].type == self.arch.opTypeIMM
232 | ):
233 | offset = chainInst.operands[0].imm // self.arch.addrSize
234 | index = self.arch.indexStackRead(offset)
235 | self.chainCond[0, index] = True
236 | if chainInst.operands[0].imm % self.arch.addrSize != 0:
237 | index = self.arch.indexStackRead(offset + 1)
238 | self.chainCond[0, index] = True
239 | else:
240 | raise ValueError("RET with more than one operands")
241 | elif (
242 | capstone.CS_GRP_JUMP in chainInst.groups
243 | or capstone.CS_GRP_CALL in chainInst.groups
244 | ):
245 | _, opr, deref = self.arch.getOperandIndices(chainInst.operands[0])
246 | for src in opr + deref:
247 | _, srcChilds = self.arch.getRegDependencies(src)
248 | self.chainCond[0, src] = True
249 | for child in srcChilds:
250 | self.chainCond[0, child] = True
251 | else:
252 | raise ValueError(
253 | "invalid chainInst: " + chainInst.mnemonic + " " + chainInst.op_str
254 | )
255 |
256 | def updateChainCond(self, instMatrix):
257 | self.chainCond *= instMatrix.matrix
258 |
259 | def lookupFromCache(self, inst):
260 | bytes_str = inst.bytes.hex()
261 | if bytes_str not in instMatrixDict:
262 | instMatrixDict[bytes_str] = InstMatrix(self.arch, inst)
263 | return instMatrixDict[bytes_str]
264 |
265 | def addInst(self, inst):
266 |
267 | instMatrix = self.lookupFromCache(inst)
268 |
269 | # init chain cond or update
270 | if self.chainCond == None:
271 | self.initChainCond(inst)
272 | else:
273 | # TODO: Hypothesis no side effect on chainInst
274 | self.updateChainCond(instMatrix)
275 |
276 | self.matrix *= instMatrix.matrix
277 | self.nbrBytes += len(inst.bytes)
278 | self.nbrInsts += 1
279 |
280 | def copy(self):
281 | gdgtCpy = GadgetMatrix(self.arch)
282 | if self.chainCond != None:
283 | gdgtCpy.chainCond = self.chainCond.copy()
284 | gdgtCpy.matrix = self.matrix.copy()
285 | gdgtCpy.inst = self.inst
286 | gdgtCpy.nbrBytes = self.nbrBytes
287 | gdgtCpy.nbrInsts = self.nbrInsts
288 | return gdgtCpy
289 |
290 | def printDep(self):
291 | _str = "\n++++ DepMatrix ++++\n"
292 | _str += self.printRegistersIo()
293 | _str += "\n++++ chainCond ++++\n"
294 | chainCond = []
295 | for src in self.chainCond.nonzero()[1]:
296 | parents, _ = self.arch.getRegDependencies(src)
297 | bparents = False
298 | for parent in parents:
299 | bparents = bparents or self.chainCond[0, parent]
300 | if not bparents:
301 | chainCond.append(self.printIndexName(src))
302 |
303 | _str += ", ".join(chainCond) + "\n"
304 |
305 | return _str
306 |
307 | def toStrings(self):
308 | strDiagFalse, strNDiagTrue = InstMatrix.toStrings(self)
309 | accChCo = ";"
310 | for j in self.chainCond.nonzero()[1]:
311 | accChCo += str(j) + ";"
312 | return strDiagFalse, strNDiagTrue, accChCo
313 |
314 | def toSets(self):
315 | def UpdateToSets(self):
316 |
317 | DiagFalse, NDiagTrue = InstMatrix.toSets(self)
318 | accChCo = set()
319 | for j in self.chainCond.nonzero()[1]:
320 | accChCo.add(j)
321 | return DiagFalse, NDiagTrue, accChCo
322 |
323 | if "_cache_to_sets" not in self.__dict__:
324 | self._cache_to_sets = UpdateToSets(self)
325 | elif self._cache_matrix_last_modification > time():
326 | self._cache_to_sets = UpdateToSets(self)
327 |
328 | return self._cache_to_sets
329 |
330 |
331 | class Gadget(GadgetMatrix):
332 | def __init__(self, arch, instList=None, max_cost=64):
333 |
334 | self.instList = instList or []
335 | self.firstInst = instList[0] if instList else None
336 | self.addresses_of_duplicates = {inst.address for inst in self.instList[:1]}
337 |
338 | self.arch = arch
339 | self.max_cost = max_cost
340 |
341 | self.gadgetMatrix = GadgetMatrix(arch)
342 |
343 | # self.gadgetMatrix.matrix = sparse.identity(arch.size, dtype=bool).tocsr()
344 |
345 | for i in range(len(self.instList) - 1, -1, -1):
346 | self.gadgetMatrix.addInst(self.instList[i])
347 |
348 | def __str__(self):
349 | result = ""
350 |
351 | for inst in self.instList:
352 | result += inst.mnemonic
353 | if inst.op_str != "":
354 | result += " " + inst.op_str
355 | result += "; "
356 |
357 | return result
358 |
359 | def bytes(self):
360 | result = b""
361 |
362 | for inst in self.instList:
363 | result += inst.bytes
364 |
365 | return result
366 |
367 | def getString(self):
368 | return self.__str__()
369 |
370 | def getAddress(self):
371 | return self.instList[0].address
372 |
373 | def getLength(self):
374 | return len(self.instList)
375 |
376 | def getRegisterAccess(self, frm=None, to=None, rflags=False):
377 | # TODO: use self.gadgetMatrix
378 | return None
379 |
380 | def getChainCondition(self):
381 | return set(self.gadgetMatrix.chainCond.nonzero()[1])
382 |
383 | def getReturnCondition(self, to):
384 | # TODO: use self.gadgetMatrix
385 | return None
386 |
387 | def countDep(self):
388 | self._cache_countDep = self.gadgetMatrix.matrix.count_nonzero()
389 | return self._cache_countDep
390 |
391 | def getChainCondDep(self):
392 | def UpdateChainCondDep(self):
393 |
394 | chainCond_maxDep = set()
395 | for i in self.gadgetMatrix.chainCond.nonzero()[1]:
396 | parents, _ = self.arch.getRegDependencies(i)
397 | bparents = False
398 | for parent in parents:
399 | if self.gadgetMatrix.chainCond[0, parent]:
400 | bparents = True
401 | break
402 |
403 | if not bparents:
404 | chainCond_maxDep.add(i)
405 | return chainCond_maxDep
406 |
407 | self._cache_chain_cond_dep = UpdateChainCondDep(self)
408 | return self._cache_chain_cond_dep
409 |
410 | def countChainCondDep(self):
411 | chainCond_maxDep = self.getChainCondDep()
412 | chainCond_maxDep.discard(self.arch.memRead)
413 | return len(chainCond_maxDep)
414 |
415 | def getDerefDep(self):
416 | def UpdateDerefDep(self):
417 | deref_maxDep = set()
418 | derefRow = self.gadgetMatrix.matrix.getrow(self.arch.deref)
419 | for i in derefRow.nonzero()[1]:
420 | parents, _ = self.arch.getRegDependencies(i)
421 | bparents = False
422 | for parent in parents:
423 | if derefRow[0, parent]:
424 | bparents = True
425 | break
426 |
427 | if not bparents:
428 | deref_maxDep.add(i)
429 | deref_maxDep.discard(self.arch.deref)
430 | return deref_maxDep
431 |
432 | self._cache_deref_dep = UpdateDerefDep(self)
433 | return self._cache_deref_dep
434 |
435 | def countDerefDep(self):
436 | deref_maxDep = self.getDerefDep()
437 | count = len(deref_maxDep)
438 | if self.arch.stackREG in deref_maxDep:
439 | count -= 0.5
440 | return count
441 |
442 | def cost(self):
443 | # cost linked to non-trivial dependencies, penalties = 10/dim
444 | dim, _ = self.gadgetMatrix.matrix.get_shape()
445 | matNotZ = max(0, self.countDep() - dim) # -dim because diag is ok
446 | costMat = (10 * matNotZ) // dim
447 | # cost linked to chain condition, penalties = 10
448 | costChainCond = max(0, 10 * (self.countChainCondDep() - 1))
449 | # -1 because 1 dep is ok
450 | # should we drop gadget if chainCond is empty?
451 | # cost associated to deref, penalties = 10
452 | costDeref = int(10 * self.countDerefDep())
453 | costLength = self.getLength() * 8
454 |
455 | totalcost = costMat + costChainCond + costDeref + costLength
456 |
457 | # if totalcost > self.max_cost:
458 | # print(str(costMat), str(costChainCond), str(costDeref), str(costLength))
459 |
460 | return totalcost
461 |
462 | def canBeExtended(self, max_cost=None):
463 | if max_cost == None:
464 | max_cost = self.max_cost
465 | return self.cost() < max_cost
466 |
467 | def copy(self):
468 | gdgt = Gadget(self.arch)
469 | gdgt.instList = [i for i in self.instList]
470 | gdgt.firstInst = self.firstInst
471 | gdgt.gadgetMatrix = self.gadgetMatrix.copy()
472 | gdgt.max_cost = self.max_cost
473 | return gdgt
474 |
475 | def extend(self, inst):
476 | self.instList.insert(0, inst)
477 | self.firstInst = inst
478 | self.addresses_of_duplicates = {inst.address}
479 | self.gadgetMatrix.addInst(inst)
480 |
--------------------------------------------------------------------------------
/tbrop/graph.py:
--------------------------------------------------------------------------------
1 | # Use full graph to capture branching gadgets
2 | # as in ROPGadget --multibr
3 | # and "Return-Oriented Programming on RISC-V" Jaloyan et al.
4 |
5 | from typing import Any, Iterator, Optional, cast
6 |
7 | import capstone as cs
8 | import networkx as nx
9 |
10 | INSTR_MAX_SIZE = 16
11 |
12 |
13 | def node_from_instruction(instruction: cs.CsInsn) -> dict[str, Any]:
14 | """
15 | Builds a node from an instruction
16 | """
17 | branch_to = None
18 | if cs.x86.X86_GRP_BRANCH_RELATIVE in instruction.groups:
19 | assert len(instruction.operands) > 0
20 | destination = instruction.operands[0]
21 | assert destination.type == cs.CS_OP_IMM
22 | branch_to = destination.imm # capstone resolves addresses
23 |
24 | return {
25 | # "instruction": instruction,
26 | "mnemonic": instruction.mnemonic,
27 | "groups": instruction.groups,
28 | "branch_to": branch_to,
29 | }
30 |
31 |
32 | def skip_instruction(
33 | instruction: cs.CsInsn,
34 | skippable_groups: Optional[set[int]] = None,
35 | skippable_mnemonics: Optional[set[str]] = None,
36 | ) -> bool:
37 | """
38 | Returns true iff instruction should not be taken into account
39 | """
40 | if skippable_groups is None:
41 | skippable_groups = {
42 | cs.CS_GRP_INVALID,
43 | cs.CS_GRP_INT,
44 | cs.CS_GRP_IRET,
45 | cs.CS_GRP_PRIVILEGE, # remove line for kernel ROP
46 | }
47 | if skippable_mnemonics is None:
48 | skippable_mnemonics = {"retf"}
49 |
50 | instruction_groups = set(instruction.groups)
51 |
52 | return (
53 | not instruction_groups.isdisjoint(skippable_groups)
54 | or instruction.mnemonic in skippable_mnemonics
55 | )
56 |
57 |
58 | def successors(instruction: cs.CsInsn) -> list[int]:
59 | instruction_groups = set(instruction.groups)
60 | next_address = instruction.address + instruction.size
61 |
62 | # No know successors for RET like instructions
63 | if instruction_groups & {
64 | cs.CS_GRP_RET,
65 | cs.CS_GRP_IRET,
66 | }:
67 | return []
68 |
69 | # We do not consider the return path of interrupts (TODO?)
70 | if cs.CS_GRP_INT in instruction_groups and instruction.mnemonic not in {
71 | "into",
72 | }:
73 | # into is a conditional interrupt
74 | return []
75 |
76 | # Regular non-branching instructions
77 | if instruction_groups.isdisjoint(
78 | {
79 | cs.CS_GRP_JUMP,
80 | cs.CS_GRP_CALL,
81 | }
82 | ):
83 | return [next_address]
84 |
85 | # we now either have a jump or a call
86 | offsets: list[int] = []
87 |
88 | # TODO: the remaining of the function is too x86 specific
89 |
90 | # for conditional jumps, we can jump to `next_address`
91 | # for calls, we ignore the return path (TODO?)
92 | if cs.CS_GRP_JUMP in instruction_groups and instruction.mnemonic != "jmp":
93 | offsets.append(next_address)
94 |
95 | if cs.x86.X86_GRP_BRANCH_RELATIVE not in instruction_groups:
96 | # call/jmp to register or memory
97 | return offsets
98 |
99 | # all that remain are call/jmp to imm
100 | assert len(instruction.operands) > 0
101 | destination = instruction.operands[0]
102 | assert destination.type == cs.CS_OP_IMM
103 |
104 | offsets.append(destination.imm) # capstone resolves addresses
105 |
106 | return offsets
107 |
108 |
109 | def build_graph_from_bytes(
110 | code: bytes,
111 | arch: int = cs.CS_ARCH_X86,
112 | mode: int = cs.CS_MODE_64,
113 | ) -> nx.DiGraph:
114 | graph = nx.DiGraph()
115 |
116 | code_analyzer = cs.Cs(arch, mode)
117 | code_analyzer.detail = True
118 |
119 | for i in range(len(code)):
120 | instr: Optional[cs.CsInsn] = next(
121 | code_analyzer.disasm(code[i : i + INSTR_MAX_SIZE], i), None
122 | )
123 | if instr is None or skip_instruction(instr):
124 | continue
125 |
126 | graph.add_node(i, **node_from_instruction(instr))
127 |
128 | for dst in successors(instr):
129 | graph.add_edge(i, dst)
130 |
131 | return graph
132 |
133 |
134 | def hidden_successors(groups: set[int]) -> bool:
135 | if (
136 | groups
137 | & {
138 | cs.CS_GRP_JUMP,
139 | cs.CS_GRP_CALL,
140 | }
141 | and cs.x86.X86_GRP_BRANCH_RELATIVE not in groups
142 | ):
143 | # instruction has an unknown successor
144 | return True
145 | if groups & {
146 | cs.CS_GRP_INT,
147 | cs.CS_GRP_RET,
148 | cs.CS_GRP_IRET,
149 | }:
150 | # instruction has an unknown successor
151 | return True
152 |
153 | return False
154 |
155 |
156 | def remove_node_and_get_predecessors(graph: nx.DiGraph, node: int) -> set[int]:
157 | # remove node and return predecessors without successors
158 | output: set[int] = set()
159 | predecessors = cast(Iterator[int], graph.predecessors(node))
160 |
161 | # only remove predecessors without alternatives
162 | # do not remove jcc with one valid branch or
163 | # calls that may not return (anyway, we do not consider return paths for now)
164 | graph.remove_node(node)
165 | for pred in predecessors:
166 | pred_groups = set(graph.nodes[pred]["groups"])
167 | if hidden_successors(pred_groups):
168 | # pred has another unknown successor
169 | continue
170 | if {
171 | cs.CS_GRP_CALL,
172 | cs.x86.X86_GRP_BRANCH_RELATIVE,
173 | } <= pred_groups and node == graph.nodes[pred]["branch_to"]:
174 | output.add(pred)
175 | continue
176 | if next(graph.successors(pred), None) is None:
177 | # no successors
178 | output.add(pred)
179 | continue
180 |
181 | return output
182 |
183 |
184 | def clean_up_graph(graph: nx.DiGraph) -> None:
185 | worklist = set()
186 | for node, attributes in graph.nodes.items():
187 | if len(attributes) == 0:
188 | worklist.add(node)
189 |
190 | while worklist:
191 | node = worklist.pop()
192 | if node not in graph:
193 | continue
194 | worklist |= remove_node_and_get_predecessors(graph, node)
195 |
--------------------------------------------------------------------------------
/tests/test_dumbGadget.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 |
4 | from tbrop.collection import GadgetsCollection
5 |
6 | data = b""
7 |
8 | data += b"\x41\x56\x45\x33\xc0\x48\x8b\xf9\x48\x8b\xd7\x57\x48\x8B\x91\x88\x00\x00\x00\x48\x8D\x05\x4F\x41\xF8\xFF\x48\x85\xD2\x48\x0F\x44\xD0\x48\x89\x91\x88\x00\x00\x00\x4C\x8B\xD2\x48\x81\xEA\x80\x01\x00\x00\x48\x89\x52\x18\x4C\x89\x52\x20\x41\x0F\x20\xC0\x4C\x89\x82\xC0\x01\x00\x00\x41\x0F\x20\xD0\x4C\x89\x82\xC8\x01\x00\x00\x41\x0F\x20\xD8\x4C\x89\x82\xD0\x01\x00\x00\x41\x0F\x20\xE0\x4C\x89\x82\xD8\x01\x00\x00\xc3"
9 |
10 | data += b"\x4d\x85\xff\x0F\x84\xC7\x01\x00\x00\xFF\xE0"
11 |
12 | data += b"\x41\x56\x45\x33\xc0\x48\xff\x25\xa2\x46\x27\x00"
13 |
14 | data += b"\x00\x00\x00\x48\x8b\xd3\x48\x8b\xff\x57\x30"
15 | data += b"\x20\xB9\x02\x00\x00\x00\x48\x0B\xC2\x48\x8D\x97\x78\x01\x00\x00\x48\x8B\xE8\x41\xFF\x91\xA0\x00\x00\x00"
16 | data += b"\x44\x87\x3d\x4c\xdd\x3c\x00\x4c\x87\xc2\xff\xe0"
17 | data += b"\x91\x9E\xFF\x4C\x8D\x5C\x24\x60\x49\x8B\x5B\x38\x49\x8B\x6B\x40\x49\x8B\x73\x48\x49\x8B\xE3\x41\x5F\x41\x5E\x41\x5D\x41\x5C\x5F\xC3"
18 |
19 | data += b"\x48\x81\xc4\x40\x01\x00\x00\xff\xe0"
20 | data += b"\x8b\x5c\x24\x30\x48\x83\xc4\x20\x5f\xc3"
21 | data += b"\x48\x81\xc4\xE0\xFF\xFF\xFF\xc2\x18\x00"
22 | data += b"\x01\xe8\xa4\xc3"
23 | data += b"\x41\x56\x45\x33\xc0\x48\x8b\xf9\x48\x8b\xd7\x57\x48\x8B\x91\x88\x00\x00\x00\x48\x8D\x05\x4F\x41\xF8\xFF\x48\x85\xD2\x48\x0F\x44\xD0\x48\x89\x91\x88\x00\x00\x00\x4C\x8B\xD2\x48\x81\xEA\x80\x01\x00\x00\x48\x89\x52\x18\x4C\x89\x52\x20\x41\x0F\x20\xC0\x4C\x89\x82\xC0\x01\x00\x00\x41\x0F\x20\xD0\x4C\x89\x82\xC8\x01\x00\x00\x41\x0F\x20\xD8\x4C\x89\x82\xD0\x01\x00\x00\x41\x0F\x20\xE0\x4C\x89\x82\xD8\x01\x00\x00\xc3"
24 |
25 | data += b"\x4d\x85\xff\x0F\x84\xC7\x01\x00\x00\xFF\xE0"
26 |
27 | data += b"\x41\x56\x45\x33\xc0\x48\xff\x25\xa2\x46\x27\x00"
28 |
29 | data += b"\x00\x00\x00\x48\x8b\xd3\x48\x8b\xff\x57\x30"
30 | data += b"\x20\xB9\x02\x00\x00\x00\x48\x0B\xC2\x48\x8D\x97\x78\x01\x00\x00\x48\x8B\xE8\x41\xFF\x91\xA0\x00\x00\x00"
31 | data += b"\x44\x87\x3d\x4c\xdd\x3c\x00\x4c\x87\xc2\xff\xe0"
32 | data += b"\x91\x9E\xFF\x4C\x8D\x5C\x24\x60\x49\x8B\x5B\x38\x49\x8B\x6B\x40\x49\x8B\x73\x48\x49\x8B\xE3\x41\x5F\x41\x5E\x41\x5D\x41\x5C\x5F\xC3"
33 | data += b"\x92\xC2\xE8\xb8"
34 | data += b"\x40\x48\x8B\x74\x24\x48\x48\x83\xC4\x30\x5F\xC3"
35 | data += b"\x48\x89\x74\x24\x48\x48\x83\xC4\x30\x5F\xC3"
36 | data += b"\x48\x8b\xe0\x48\x89\x74\x24\x48\x48\x83\xC4\x30\x5F\xC3"
37 | data += b"\x48\x89\x74\x24\x48\xff\xe0"
38 | data += b"\x48\x89\x74\x24\x48\x48\x83\xC4\x48\x5f\xff\xe0"
39 | data += b"\x58\xc3"
40 | data += b"\x03\x48\x89\x58\x08\x0F\xB6\x45\x01\x41\x3B\xC2\x0F\x85"
41 | data += b"\x00\x00\x00\xE9\x9B\xE4\xFF\xFF\x49\x8B\xC2\xE9\xB6"
42 | data += b"\x48\x8B\xCB\x4C\x8B\x05\x23\x02\x1F\x00\x41\xFF\xD0"
43 | data += b"\x5e\x5b\xC3"
44 | data += b"\x01\xe8\xa4\xC3"
45 | data += b"\x8D\x97\x78\x01\x00\x00\x48\x8B\xE8\x41\xFF\x91\xA0\x00\x00\x00"
46 |
47 | data = b"\x48\x03\x1c\x8a\x48\xf7\xeb\xff\x90\xfe\xfe\x05\x0c"
48 |
49 | data = b"\x50\x53\x51\x48\x89\xd9\x48\x89\xc3\x58\x5a\x5e\x5f\xc2\x10\x00"
50 |
51 | data = b"\x48\xff\xc9\x48\xad\xc3"
52 |
53 | data = b"\x48\x89\xe3\x48\x89\x0b\x58\xc3"
54 |
55 | gdgtCollection = GadgetsCollection("x64", data)
56 |
57 |
58 | gdgtCollection.collect(max_cost=132)
59 |
60 | for gdgt in gdgtCollection.gadgets:
61 | print(hex(gdgt.firstInst.address), ":")
62 |
63 | for inst in gdgt.instList:
64 | print(inst.bytes.hex().rjust(16), "\t", inst.mnemonic, inst.op_str)
65 |
66 | print("")
67 |
68 | print("Cost:", gdgt.cost())
69 |
70 | print(gdgt.gadgetMatrix.printDep())
71 |
72 | print("")
73 |
74 | print("\n----------------------------------------------")
75 |
76 |
77 | print(len(gdgtCollection.gadgets))
78 |
--------------------------------------------------------------------------------
/tests/test_gadget.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import unittest
4 |
5 | import capstone
6 |
7 | import tbrop.arch as arch
8 | import tbrop.gadget as gadget
9 |
10 |
11 | class TestGadget(unittest.TestCase):
12 |
13 | def test_archx64(self):
14 | md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
15 | md.detail = True
16 | archx64 = arch.Arch_x86_64()
17 | for test_case in TestGadget.test_cases:
18 | if "x64" not in test_case:
19 | continue
20 |
21 | with self.subTest(data=test_case["bytes"]):
22 | instList = list(md.disasm(test_case["bytes"],0))
23 |
24 | asm = ""
25 | for inst in instList:
26 | asm += inst.bytes.hex().rjust(16) + " " + inst.mnemonic + " " + inst.op_str + "\n"
27 |
28 | self.assertEqual(test_case["x64"]["asm"], asm)
29 |
30 | gdgt = gadget.Gadget(archx64, instList)
31 |
32 | self.assertEqual(test_case["x64"]["cost"], gdgt.cost())
33 | self.assertEqual(test_case["x64"]["dependencies"], gdgt.gadgetMatrix.printDep())
34 |
35 | @classmethod
36 | def setUpClass(cls):
37 | TestGadget.test_cases = []
38 |
39 | TestGadget.test_cases.append({
40 | "bytes": b"\x58\xc3",
41 | "x64": {
42 | "asm": " 58 pop rax\n"
43 | " c3 ret \n",
44 | "cost": 21,
45 | "dependencies": "\n"
46 | "++++ DepMatrix ++++\n"
47 | "rax <--- stack_0\n"
48 | "deref <--- deref, rsp\n"
49 | "\n"
50 | "++++ chainCond ++++\n"
51 | "stack_1\n",
52 | },
53 | })
54 | TestGadget.test_cases.append({
55 | "bytes": b"\x48\x89\x74\x24\x48\xff\xe0",
56 | "x64": {
57 | "asm": " 4889742448 mov qword ptr [rsp + 0x48], rsi\n"
58 | " ffe0 jmp rax\n",
59 | "cost": 21,
60 | "dependencies": "\n"
61 | "++++ DepMatrix ++++\n"
62 | "deref <--- deref, rsp\n"
63 | "stack_9 <--- rsi\n"
64 | "\n"
65 | "++++ chainCond ++++\n"
66 | "rax\n",
67 | },
68 | })
69 | TestGadget.test_cases.append({
70 | "bytes": b"\x48\x81\xc4\xE0\xFF\xFF\xFF\xc2\x18\x00",
71 | "x64": {
72 | "asm": " 4881c4e0ffffff add rsp, -0x20\n"
73 | " c21800 ret 0x18\n",
74 | "cost": 21,
75 | "dependencies": "\n"
76 | "++++ DepMatrix ++++\n"
77 | "rflags <--- rsp\n"
78 | "deref <--- deref, rsp\n"
79 | "\n"
80 | "++++ chainCond ++++\n"
81 | "stack_{-1}\n",
82 | },
83 | })
84 | TestGadget.test_cases.append({
85 | "bytes": b"\x48\x81\xc4\x40\x01\x00\x00\xff\xe0",
86 | "x64": {
87 | "asm": " 4881c440010000 add rsp, 0x140\n"
88 | " ffe0 jmp rax\n",
89 | "cost": 22,
90 | "dependencies": "\n"
91 | "++++ DepMatrix ++++\n"
92 | "rflags <--- rsp\n"
93 | "deref <--- deref, rsp\n"
94 | "\n"
95 | "++++ chainCond ++++\n"
96 | "rax\n",
97 | },
98 | })
99 | TestGadget.test_cases.append({
100 | "bytes": b"\x92\xC2\xE8\xb8",
101 | "x64": {
102 | "asm": " 92 xchg eax, edx\n"
103 | " c2e8b8 ret 0xb8e8\n",
104 | "cost": 24,
105 | "dependencies": "\n"
106 | "++++ DepMatrix ++++\n"
107 | "rax <--- rax, edx\n"
108 | "rdx <--- rdx, eax\n"
109 | "deref <--- deref, rsp\n"
110 | "\n"
111 | "++++ chainCond ++++\n"
112 | "stack_r\n",
113 | },
114 | })
115 | TestGadget.test_cases.append({
116 | "bytes": b"\x4d\x85\xff\x0F\x84\xC7\x01\x00\x00\xFF\xE0",
117 | "x64": {
118 | "asm": " 4d85ff test r15, r15\n"
119 | " 0f84c7010000 je 0x1d0\n"
120 | " ffe0 jmp rax\n",
121 | "cost": 24,
122 | "dependencies": "\n"
123 | "++++ DepMatrix ++++\n"
124 | "rflags <--- r15\n"
125 | "\n"
126 | "++++ chainCond ++++\n"
127 | "rax\n",
128 | },
129 | })
130 | TestGadget.test_cases.append({
131 | "bytes": b"\x5e\x5b\xC3",
132 | "x64": {
133 | "asm": " 5e pop rsi\n"
134 | " 5b pop rbx\n"
135 | " c3 ret \n",
136 | "cost": 29,
137 | "dependencies": "\n"
138 | "++++ DepMatrix ++++\n"
139 | "rbx <--- stack_1\n"
140 | "rsi <--- stack_0\n"
141 | "deref <--- deref, rsp\n"
142 | "\n"
143 | "++++ chainCond ++++\n"
144 | "stack_2\n",
145 | },
146 | })
147 | TestGadget.test_cases.append({
148 | "bytes": b"\x44\x87\x3d\x4c\xdd\x3c\x00\x4c\x87\xc2\xff\xe0",
149 | "x64": {
150 | "asm": " 44873d4cdd3c00 xchg dword ptr [rip + 0x3cdd4c], r15d\n"
151 | " 4c87c2 xchg rdx, r8\n"
152 | " ffe0 jmp rax\n",
153 | "cost": 35,
154 | "dependencies": "\n"
155 | "++++ DepMatrix ++++\n"
156 | "rdx <--- r8\n"
157 | "r8 <--- rdx\n"
158 | "r15 <--- r15, rip, mem_r\n"
159 | "deref <--- deref, rip\n"
160 | "mem_w <--- mem_w, r15d\n"
161 | "\n"
162 | "++++ chainCond ++++\n"
163 | "rax\n",
164 | },
165 | })
166 | TestGadget.test_cases.append({
167 | "bytes": b"\x8b\x5c\x24\x30\x48\x83\xc4\x20\x5f\xc3",
168 | "x64": {
169 | "asm": " 8b5c2430 mov ebx, dword ptr [rsp + 0x30]\n"
170 | " 4883c420 add rsp, 0x20\n"
171 | " 5f pop rdi\n"
172 | " c3 ret \n",
173 | "cost": 37,
174 | "dependencies": "\n"
175 | "++++ DepMatrix ++++\n"
176 | "rflags <--- rsp\n"
177 | "rbx <--- rbx, stack_6\n"
178 | "rdi <--- stack_4\n"
179 | "deref <--- deref, rsp\n"
180 | "\n"
181 | "++++ chainCond ++++\n"
182 | "stack_5\n",
183 | },
184 | })
185 | TestGadget.test_cases.append({
186 | "bytes": b"\x40\x48\x8B\x74\x24\x48\x48\x83\xC4\x30\x5F\xC3",
187 | "x64": {
188 | "asm": " 40488b742448 mov rsi, qword ptr [rsp + 0x48]\n"
189 | " 4883c430 add rsp, 0x30\n"
190 | " 5f pop rdi\n"
191 | " c3 ret \n",
192 | "cost": 37,
193 | "dependencies": "\n"
194 | "++++ DepMatrix ++++\n"
195 | "rflags <--- rsp\n"
196 | "rdi <--- stack_6\n"
197 | "rsi <--- stack_9\n"
198 | "deref <--- deref, rsp\n"
199 | "\n"
200 | "++++ chainCond ++++\n"
201 | "stack_7\n",
202 | },
203 | })
204 | TestGadget.test_cases.append({
205 | "bytes": b"\x48\x89\x74\x24\x48\x48\x83\xC4\x30\x5F\xC3",
206 | "x64": {
207 | "asm": " 4889742448 mov qword ptr [rsp + 0x48], rsi\n"
208 | " 4883c430 add rsp, 0x30\n"
209 | " 5f pop rdi\n"
210 | " c3 ret \n",
211 | "cost": 38,
212 | "dependencies": "\n"
213 | "++++ DepMatrix ++++\n"
214 | "rflags <--- rsp\n"
215 | "rdi <--- stack_6\n"
216 | "deref <--- deref, rsp\n"
217 | "stack_1 <--- rsi\n"
218 | "\n"
219 | "++++ chainCond ++++\n"
220 | "stack_7\n",
221 | },
222 | })
223 | TestGadget.test_cases.append({
224 | "bytes": b"\x48\x89\x74\x24\x48\x48\x83\xC4\x48\x5f\xff\xe0",
225 | "x64": {
226 | "asm": " 4889742448 mov qword ptr [rsp + 0x48], rsi\n"
227 | " 4883c448 add rsp, 0x48\n"
228 | " 5f pop rdi\n"
229 | " ffe0 jmp rax\n",
230 | "cost": 38,
231 | "dependencies": "\n"
232 | "++++ DepMatrix ++++\n"
233 | "rflags <--- rsp\n"
234 | "rdi <--- rsi\n"
235 | "deref <--- deref, rsp\n"
236 | "stack_{-1} <--- rsi\n"
237 | "\n"
238 | "++++ chainCond ++++\n"
239 | "rax\n",
240 | },
241 | })
242 | TestGadget.test_cases.append({
243 | "bytes": b"\x41\x56\x45\x33\xc0\x48\xff\x25\xa2\x46\x27\x00",
244 | "x64": {
245 | "asm": " 4156 push r14\n"
246 | " 4533c0 xor r8d, r8d\n"
247 | " 48ff25a2462700 jmp qword ptr [rip + 0x2746a2]\n",
248 | "cost": 39,
249 | "dependencies": "\n"
250 | "++++ DepMatrix ++++\n"
251 | "deref <--- deref, rip, rsp\n"
252 | "stack_0 <--- r14\n"
253 | "\n"
254 | "++++ chainCond ++++\n"
255 | "rip, mem_r\n",
256 | },
257 | })
258 | TestGadget.test_cases.append({
259 | "bytes": b"\x48\x8B\xCB\x4C\x8B\x05\x23\x02\x1F\x00\x41\xFF\xD0",
260 | "x64": {
261 | "asm": " 488bcb mov rcx, rbx\n"
262 | " 4c8b0523021f00 mov r8, qword ptr [rip + 0x1f0223]\n"
263 | " 41ffd0 call r8\n",
264 | "cost": 40,
265 | "dependencies": "\n"
266 | "++++ DepMatrix ++++\n"
267 | "rcx <--- rbx\n"
268 | "r8 <--- rip, mem_r\n"
269 | "deref <--- deref, rip, rsp\n"
270 | "\n"
271 | "++++ chainCond ++++\n"
272 | "rip, mem_r\n",
273 | },
274 | })
275 | TestGadget.test_cases.append({
276 | "bytes": b"\x8D\x97\x78\x01\x00\x00\x48\x8B\xE8\x41\xFF\x91\xA0\x00\x00\x00",
277 | "x64": {
278 | "asm": " 8d9778010000 lea edx, [rdi + 0x178]\n"
279 | " 488be8 mov rbp, rax\n"
280 | " 41ff91a0000000 call qword ptr [r9 + 0xa0]\n",
281 | "cost": 40,
282 | "dependencies": "\n"
283 | "++++ DepMatrix ++++\n"
284 | "rbp <--- rax\n"
285 | "rdx <--- rdx, rdi\n"
286 | "deref <--- deref, rsp, r9\n"
287 | "\n"
288 | "++++ chainCond ++++\n"
289 | "r9, mem_r\n",
290 | },
291 | })
292 | TestGadget.test_cases.append({
293 | "bytes": b"\x01\xe8\xa4\xc3",
294 | "x64": {
295 | "asm": " 01e8 add eax, ebp\n"
296 | " a4 movsb byte ptr [rdi], byte ptr [rsi]\n"
297 | " c3 ret \n",
298 | "cost": 55,
299 | "dependencies": "\n"
300 | "++++ DepMatrix ++++\n"
301 | "rflags <--- eax, ebp\n"
302 | "rax <--- rax, ebp\n"
303 | "rdi <--- rdi, eax, ebp, rsi, mem_r\n"
304 | "rsi <--- rsi, eax, ebp, rdi, mem_r\n"
305 | "deref <--- deref, rdi, rsi, rsp\n"
306 | "mem_w <--- eax, ebp, rdi, rsi, mem_r\n"
307 | "\n"
308 | "++++ chainCond ++++\n"
309 | "stack_0\n",
310 | },
311 | })
312 | TestGadget.test_cases.append({
313 | "bytes": b"\x00\x00\x00\x48\x8b\xd3\x48\x8b\xff\x57\x30",
314 | "x64": {
315 | "asm": " 0000 add byte ptr [rax], al\n"
316 | " 00488b add byte ptr [rax - 0x75], cl\n"
317 | " d3488b ror dword ptr [rax - 0x75], cl\n"
318 | " ff5730 call qword ptr [rdi + 0x30]\n",
319 | "cost": 58,
320 | "dependencies": "\n"
321 | "++++ DepMatrix ++++\n"
322 | "rflags <--- cl, rax, mem_r\n"
323 | "deref <--- deref, rax, rdi, rsp\n"
324 | "mem_w <--- cl, rax, mem_r\n"
325 | "\n"
326 | "++++ chainCond ++++\n"
327 | "mem_r, rdi\n",
328 | },
329 | })
330 | TestGadget.test_cases.append({
331 | "bytes": b"\x48\x8b\xe0\x48\x89\x74\x24\x48\x48\x83\xC4\x30\x5F\xC3",
332 | "x64": {
333 | "asm": " 488be0 mov rsp, rax\n"
334 | " 4889742448 mov qword ptr [rsp + 0x48], rsi\n"
335 | " 4883c430 add rsp, 0x30\n"
336 | " 5f pop rdi\n"
337 | " c3 ret \n",
338 | "cost": 62,
339 | "dependencies": "\n"
340 | "++++ DepMatrix ++++\n"
341 | "rflags <--- rax\n"
342 | "rdi <--- rax, mem_r\n"
343 | "rsp <--- rax\n"
344 | "deref <--- deref, rax\n"
345 | "stackOver_r <--- rax, mem_r\n"
346 | "stackOver_w <--- rax, mem_r\n"
347 | "stack_{-12} <--- rax, mem_r\n"
348 | "stack_{-11} <--- rax, mem_r\n"
349 | "stack_{-10} <--- rax, mem_r\n"
350 | "stack_{-9} <--- rax, mem_r\n"
351 | "stack_{-8} <--- rax, mem_r\n"
352 | "stack_{-7} <--- rax, mem_r\n"
353 | "stack_{-6} <--- rax, mem_r\n"
354 | "stack_{-5} <--- rax, mem_r\n"
355 | "stack_{-4} <--- rax, mem_r\n"
356 | "stack_{-3} <--- rax, mem_r\n"
357 | "stack_{-2} <--- rax, mem_r\n"
358 | "stack_{-1} <--- rax, mem_r\n"
359 | "stack_0 <--- rax, mem_r\n"
360 | "stack_1 <--- rsi\n"
361 | "stack_2 <--- rax, mem_r\n"
362 | "stack_3 <--- rax, mem_r\n"
363 | "stack_4 <--- rax, mem_r\n"
364 | "stack_5 <--- rax, mem_r\n"
365 | "stack_6 <--- rax, mem_r\n"
366 | "stack_7 <--- rax, mem_r\n"
367 | "stack_8 <--- rax, mem_r\n"
368 | "stack_9 <--- rax, mem_r\n"
369 | "stack_10 <--- rax, mem_r\n"
370 | "stack_11 <--- rax, mem_r\n"
371 | "stack_12 <--- rax, mem_r\n"
372 | "stack_13 <--- rax, mem_r\n"
373 | "stack_14 <--- rax, mem_r\n"
374 | "stack_15 <--- rax, mem_r\n"
375 | "stack_16 <--- rax, mem_r\n"
376 | "stack_17 <--- rax, mem_r\n"
377 | "stack_18 <--- rax, mem_r\n"
378 | "stack_19 <--- rax, mem_r\n"
379 | "stack_20 <--- rax, mem_r\n"
380 | "stack_21 <--- rax, mem_r\n"
381 | "stack_22 <--- rax, mem_r\n"
382 | "stack_23 <--- rax, mem_r\n"
383 | "stack_24 <--- rax, mem_r\n"
384 | "stack_25 <--- rax, mem_r\n"
385 | "stack_26 <--- rax, mem_r\n"
386 | "stack_27 <--- rax, mem_r\n"
387 | "stack_28 <--- rax, mem_r\n"
388 | "stack_29 <--- rax, mem_r\n"
389 | "stack_30 <--- rax, mem_r\n"
390 | "stack_31 <--- rax, mem_r\n"
391 | "stack_32 <--- rax, mem_r\n"
392 | "stack_33 <--- rax, mem_r\n"
393 | "stack_34 <--- rax, mem_r\n"
394 | "stack_35 <--- rax, mem_r\n"
395 | "stack_36 <--- rax, mem_r\n"
396 | "stack_37 <--- rax, mem_r\n"
397 | "stack_38 <--- rax, mem_r\n"
398 | "stack_r <--- rax, mem_r\n"
399 | "stack_w <--- rax, mem_r\n"
400 | "\n"
401 | "++++ chainCond ++++\n"
402 | "mem_r, rax\n",
403 | },
404 | })
405 | TestGadget.test_cases.append({
406 | "bytes": b"\x20\xB9\x02\x00\x00\x00\x48\x0B\xC2\x48\x8D\x97\x78\x01\x00\x00\x48\x8B\xE8\x41\xFF\x91\xA0\x00\x00\x00",
407 | "x64": {
408 | "asm": " 20b902000000 and byte ptr [rcx + 2], bh\n"
409 | " 480bc2 or rax, rdx\n"
410 | " 488d9778010000 lea rdx, [rdi + 0x178]\n"
411 | " 488be8 mov rbp, rax\n"
412 | " 41ff91a0000000 call qword ptr [r9 + 0xa0]\n",
413 | "cost": 69,
414 | "dependencies": "\n"
415 | "++++ DepMatrix ++++\n"
416 | "rflags <--- rax, rdx\n"
417 | "rax <--- rax, rdx\n"
418 | "rbp <--- rax, rdx\n"
419 | "rdx <--- rdi\n"
420 | "deref <--- deref, rcx, rsp, r9\n"
421 | "mem_w <--- bh, rcx, mem_r\n"
422 | "\n"
423 | "++++ chainCond ++++\n"
424 | "r9, mem_r\n",
425 | },
426 | })
427 | TestGadget.test_cases.append({
428 | "bytes": b"\x00\x00\x00\xE9\x9B\xE4\xFF\xFF\x49\x8B\xC2\xE9\xB6",
429 | "x64": {
430 | "asm": " 0000 add byte ptr [rax], al\n"
431 | " 00e9 add cl, ch\n"
432 | " 9b wait \n"
433 | " e4ff in al, 0xff\n"
434 | " ff498b dec dword ptr [rcx - 0x75]\n"
435 | " c2e9b6 ret 0xb6e9\n",
436 | "cost": 76,
437 | "dependencies": "\n"
438 | "++++ DepMatrix ++++\n"
439 | "rflags <--- rcx, mem_r\n"
440 | "deref <--- deref, rax, rcx, rsp\n"
441 | "mem_w <--- rcx, mem_r\n"
442 | "\n"
443 | "++++ chainCond ++++\n"
444 | "stack_r\n",
445 | },
446 | })
447 | TestGadget.test_cases.append({
448 | "bytes": b"\x03\x48\x89\x58\x08\x0F\xB6\x45\x01\x41\x3B\xC2\x0F\x85",
449 | "x64": {
450 | "asm": " 034889 add ecx, dword ptr [rax - 0x77]\n"
451 | " 58 pop rax\n"
452 | " 080f or byte ptr [rdi], cl\n"
453 | " b645 mov dh, 0x45\n"
454 | " 01413b add dword ptr [rcx + 0x3b], eax\n"
455 | " c20f85 ret 0x850f\n",
456 | "cost": 98,
457 | "dependencies": "\n"
458 | "++++ DepMatrix ++++\n"
459 | "rflags <--- rax, rcx, mem_r, stack_0\n"
460 | "rax <--- stack_0\n"
461 | "rcx <--- rcx, rax, mem_r\n"
462 | "deref <--- deref, rax, rcx, rdi, rsp, mem_r\n"
463 | "mem_w <--- rax, rcx, mem_r\n"
464 | "\n"
465 | "++++ chainCond ++++\n"
466 | "stack_r\n",
467 | },
468 | })
469 | TestGadget.test_cases.append({
470 | "bytes": b"\x91\x9E\xFF\x4C\x8D\x5C\x24\x60\x49\x8B\x5B\x38\x49\x8B\x6B\x40\x49\x8B\x73\x48\x49\x8B\xE3\x41\x5F\x41\x5E\x41\x5D\x41\x5C\x5F\xC3",
471 | "x64": {
472 | "asm": " 91 xchg eax, ecx\n"
473 | " 9e sahf \n"
474 | " ff4c8d5c dec dword ptr [rbp + rcx*4 + 0x5c]\n"
475 | " 2460 and al, 0x60\n"
476 | " 498b5b38 mov rbx, qword ptr [r11 + 0x38]\n"
477 | " 498b6b40 mov rbp, qword ptr [r11 + 0x40]\n"
478 | " 498b7348 mov rsi, qword ptr [r11 + 0x48]\n"
479 | " 498be3 mov rsp, r11\n"
480 | " 415f pop r15\n"
481 | " 415e pop r14\n"
482 | " 415d pop r13\n"
483 | " 415c pop r12\n"
484 | " 5f pop rdi\n"
485 | " c3 ret \n",
486 | "cost": 167,
487 | "dependencies": "\n"
488 | "++++ DepMatrix ++++\n"
489 | "rflags <--- ecx\n"
490 | "rax <--- rax, ecx\n"
491 | "rbp <--- r11, mem_r\n"
492 | "rbx <--- r11, mem_r\n"
493 | "rcx <--- rcx, eax\n"
494 | "rdi <--- r11, mem_r\n"
495 | "rsi <--- r11, mem_r\n"
496 | "rsp <--- r11\n"
497 | "r12 <--- r11, mem_r\n"
498 | "r13 <--- r11, mem_r\n"
499 | "r14 <--- r11, mem_r\n"
500 | "r15 <--- r11, mem_r\n"
501 | "deref <--- deref, eax, rbp, rcx, r11\n"
502 | "mem_w <--- eax, rbp, rcx, mem_r\n"
503 | "stackOver_r <--- r11, mem_r\n"
504 | "stackOver_w <--- r11, mem_r\n"
505 | "stack_{-12} <--- r11, mem_r\n"
506 | "stack_{-11} <--- r11, mem_r\n"
507 | "stack_{-10} <--- r11, mem_r\n"
508 | "stack_{-9} <--- r11, mem_r\n"
509 | "stack_{-8} <--- r11, mem_r\n"
510 | "stack_{-7} <--- r11, mem_r\n"
511 | "stack_{-6} <--- r11, mem_r\n"
512 | "stack_{-5} <--- r11, mem_r\n"
513 | "stack_{-4} <--- r11, mem_r\n"
514 | "stack_{-3} <--- r11, mem_r\n"
515 | "stack_{-2} <--- r11, mem_r\n"
516 | "stack_{-1} <--- r11, mem_r\n"
517 | "stack_0 <--- r11, mem_r\n"
518 | "stack_1 <--- r11, mem_r\n"
519 | "stack_2 <--- r11, mem_r\n"
520 | "stack_3 <--- r11, mem_r\n"
521 | "stack_4 <--- r11, mem_r\n"
522 | "stack_5 <--- r11, mem_r\n"
523 | "stack_6 <--- r11, mem_r\n"
524 | "stack_7 <--- r11, mem_r\n"
525 | "stack_8 <--- r11, mem_r\n"
526 | "stack_9 <--- r11, mem_r\n"
527 | "stack_10 <--- r11, mem_r\n"
528 | "stack_11 <--- r11, mem_r\n"
529 | "stack_12 <--- r11, mem_r\n"
530 | "stack_13 <--- r11, mem_r\n"
531 | "stack_14 <--- r11, mem_r\n"
532 | "stack_15 <--- r11, mem_r\n"
533 | "stack_16 <--- r11, mem_r\n"
534 | "stack_17 <--- r11, mem_r\n"
535 | "stack_18 <--- r11, mem_r\n"
536 | "stack_19 <--- r11, mem_r\n"
537 | "stack_20 <--- r11, mem_r\n"
538 | "stack_21 <--- r11, mem_r\n"
539 | "stack_22 <--- r11, mem_r\n"
540 | "stack_23 <--- r11, mem_r\n"
541 | "stack_24 <--- r11, mem_r\n"
542 | "stack_25 <--- r11, mem_r\n"
543 | "stack_26 <--- r11, mem_r\n"
544 | "stack_27 <--- r11, mem_r\n"
545 | "stack_28 <--- r11, mem_r\n"
546 | "stack_29 <--- r11, mem_r\n"
547 | "stack_30 <--- r11, mem_r\n"
548 | "stack_31 <--- r11, mem_r\n"
549 | "stack_32 <--- r11, mem_r\n"
550 | "stack_33 <--- r11, mem_r\n"
551 | "stack_34 <--- r11, mem_r\n"
552 | "stack_35 <--- r11, mem_r\n"
553 | "stack_36 <--- r11, mem_r\n"
554 | "stack_37 <--- r11, mem_r\n"
555 | "stack_38 <--- r11, mem_r\n"
556 | "stack_r <--- r11, mem_r\n"
557 | "stack_w <--- r11, mem_r\n"
558 | "\n"
559 | "++++ chainCond ++++\n"
560 | "r11, mem_r\n",
561 | },
562 | })
563 | TestGadget.test_cases.append({
564 | "bytes": b"\x41\x56\x45\x33\xc0\x48\x8b\xf9\x48\x8b\xd7\x57\x48\x8B\x91\x88\x00\x00\x00\x48\x8D\x05\x4F\x41\xF8\xFF\x48\x85\xD2\x48\x0F\x44\xD0\x48\x89\x91\x88\x00\x00\x00\x4C\x8B\xD2\x48\x81\xEA\x80\x01\x00\x00\x48\x89\x52\x18\x4C\x89\x52\x20\x41\x0F\x20\xC0\x4C\x89\x82\xC0\x01\x00\x00\x41\x0F\x20\xD0\x4C\x89\x82\xC8\x01\x00\x00\x41\x0F\x20\xD8\x4C\x89\x82\xD0\x01\x00\x00\x41\x0F\x20\xE0\x4C\x89\x82\xD8\x01\x00\x00\xc3",
565 | "x64": {
566 | "asm": " 4156 push r14\n"
567 | " 4533c0 xor r8d, r8d\n"
568 | " 488bf9 mov rdi, rcx\n"
569 | " 488bd7 mov rdx, rdi\n"
570 | " 57 push rdi\n"
571 | " 488b9188000000 mov rdx, qword ptr [rcx + 0x88]\n"
572 | " 488d054f41f8ff lea rax, [rip - 0x7beb1]\n"
573 | " 4885d2 test rdx, rdx\n"
574 | " 480f44d0 cmove rdx, rax\n"
575 | " 48899188000000 mov qword ptr [rcx + 0x88], rdx\n"
576 | " 4c8bd2 mov r10, rdx\n"
577 | " 4881ea80010000 sub rdx, 0x180\n"
578 | " 48895218 mov qword ptr [rdx + 0x18], rdx\n"
579 | " 4c895220 mov qword ptr [rdx + 0x20], r10\n"
580 | " 410f20c0 mov r8, cr0\n"
581 | " 4c8982c0010000 mov qword ptr [rdx + 0x1c0], r8\n"
582 | " 410f20d0 mov r8, cr2\n"
583 | " 4c8982c8010000 mov qword ptr [rdx + 0x1c8], r8\n"
584 | " 410f20d8 mov r8, cr3\n"
585 | " 4c8982d0010000 mov qword ptr [rdx + 0x1d0], r8\n"
586 | " 410f20e0 mov r8, cr4\n"
587 | " 4c8982d8010000 mov qword ptr [rdx + 0x1d8], r8\n"
588 | " c3 ret \n",
589 | "cost": 222,
590 | "dependencies": "\n"
591 | "++++ DepMatrix ++++\n"
592 | "rflags <--- rcx, rip, mem_r\n"
593 | "rax <--- rip\n"
594 | "rdi <--- rcx\n"
595 | "rdx <--- rcx, rip, mem_r\n"
596 | "r8 <--- cr4\n"
597 | "r10 <--- rcx, rip, mem_r\n"
598 | "deref <--- deref, rcx, rip, rsp, mem_r\n"
599 | "mem_w <--- rcx, rip, cr4, mem_r\n"
600 | "stack_{-1} <--- rcx\n"
601 | "stack_0 <--- r14\n"
602 | "\n"
603 | "++++ chainCond ++++\n"
604 | "rcx\n",
605 | },
606 | })
607 |
608 | if __name__ == '__main__':
609 | unittest.main()
610 |
--------------------------------------------------------------------------------