├── .gitignore
├── LICENSE
├── README.md
├── cigma
├── __init__.py
├── cigma.py
└── magicbytes.json
├── requirements.txt
├── unbox.json.example
└── unbox
├── __init__.py
├── __main__.py
├── cli.py
├── config.py
└── handler
├── __init__.py
├── archive.py
├── base.py
├── commands
├── __init__.py
└── commands.py
├── decompilable.py
├── local.py
├── remote.py
└── utils
├── __init__.py
├── fileformat.py
├── filesystem.py
├── shell.py
└── web.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | env/
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 |
49 | # Translations
50 | *.mo
51 | *.pot
52 |
53 | # Django stuff:
54 | *.log
55 | local_settings.py
56 |
57 | # Flask stuff:
58 | instance/
59 | .webassets-cache
60 |
61 | # Scrapy stuff:
62 | .scrapy
63 |
64 | # Sphinx documentation
65 | docs/_build/
66 |
67 | # PyBuilder
68 | target/
69 |
70 | # Jupyter Notebook
71 | .ipynb_checkpoints
72 |
73 | # pyenv
74 | .python-version
75 |
76 | # celery beat schedule file
77 | celerybeat-schedule
78 |
79 | # SageMath parsed files
80 | *.sage.py
81 |
82 | # dotenv
83 | .env
84 |
85 | # virtualenv
86 | .venv
87 | venv/
88 | ENV/
89 |
90 | # Spyder project settings
91 | .spyderproject
92 | .spyproject
93 |
94 | # Rope project settings
95 | .ropeproject
96 |
97 | # mkdocs documentation
98 | /site
99 |
100 | # mypy
101 | .mypy_cache/
102 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |  *Unpack and Decompile the $h\*! out of things*
2 |
3 | # unbox
4 |
5 |
6 | **Unbox** is a convenient one-click unpack and decompiler tool that wraps existing 3rd party applications like *IDA Pro,
7 | JD-Cli, Dex2Src*, and others to provide a convenient archiver liker command line interfaces to unpack and decompile
8 | various types of files. It currently features support for compiled binaries (*.net, PE, elf, mach, ...*), *java classes,
9 | android application packages* and various types of archives or browser extensions. The goal of this tool is mainly to
10 | take off the extra efford needed to deal with the various decompiler tools and give a standard yet easy to use
11 | interface.
12 |
13 | Requires: :snake: python-2
14 |
15 | **Dependencies:**
16 |
17 | * cigma - https://github.com/7h3rAm/cigma
18 | * patool - https://pypi.python.org/pypi/patool
19 |
20 | # Usage :sheep:
21 |
22 | example: unbox.py [options] [, ...]
23 | options:
24 | -y, --yes ... answer prompts with yes
25 | -n, --no ... answer prompts with no
26 |
27 | command ... list
28 | ... extract
29 |
30 | ... check-dependencies
31 |
32 | target ... file
33 |
34 |
35 | *One interface to rule them all...*
36 |
37 | | usage | command |
38 | |-------|---------|
39 | | unpack and decompile all ***.jar** files | `#> unbox/cli.py extract \lib\Adv*.jar c:\_tmp\decompiled` |
40 | | decompile a **Windows dll** | `#> unbox/cli.py extract samples\7-zip32.dll c:\_tmp\decompiled` |
41 | | decompile an **elf executable** | `#> unbox/cli.py extract samples/crackme1 /tmp/decompiled` |
42 | | unpack and decompile an **apk** | `#> unbox/cli.py extract test.apk c:\_tmp\decompiled` |
43 | | decompile a **.net** application | `#> unbox/cli.py extract test.exe c:\_tmp\decompiled` |
44 | | unpack a **browser extension** | `#> unbox/cli.py extract sample.crx c:\_tmp\decompiled` |
45 | | unpack **all supported** files | `#> unbox/cli.py extract * c:\_tmp\decompiled` |
46 |
47 | *I think you got the idea ...*
48 | *... and yes it will recursively unpack things ...*
49 |
50 |
51 | # Configuration
52 |
53 | * in case your 3rd party tools are not generally available via *PATH* configure them in `unbox.json`
54 |
55 | application search-path order for `unbox.json` is
56 |
57 | * current working dir OR
58 | * `~/unbox.json` OR
59 | * `~/.unbox/unbox.json`
60 |
61 |
62 | # Setup
63 |
64 | * install
65 | * check dependencies `python cli.py check-dependencies`
66 | * install missing 3rd party applications (see table below)
67 | * make them available in PATH or configure them in unbox.json
68 |
69 |
70 | # As a Library
71 |
72 | ```python
73 |
74 | from unbox import UnboxPath
75 |
76 | target = "path/to/target/file"
77 |
78 | dst = UnboxPath(target) # crate an unbox path instance
79 | for p in dst.files.walk(): # auto-decompile/unpack and walk resulting files (source-code, etc..)
80 | print p.path # print the unpacked files' path
81 | ```
82 |
83 | # Live Action
84 |
85 | ### List contents of windows DLL
86 |
87 | ```
88 | #> unbox/cli.py list "samples\7-zip32.dll"
89 | [handler.base/2808][DEBUG ] [base.get_path ] unknown: 7-zip32.dll
90 | [handler.base/2808][DEBUG ] [base.get_path ] {'source': 'databuffer', 'magic': {'mimetype': 'application/x-executable-mz', 'patterns': [{'regex': '\\x4D\\x5A', 'offset': 0, 'size': 2}], 'shortname': 'EXE', 'id': 31, 'longname': 'Windows Executable'}}
91 | [handler.base/2808][DEBUG ] [base.get_path ] 2
92 | [handler.commands.commands/2808][DEBUG ] [commands.decompile ] [u'ida\\idaw.exe', '-B', '-M', '-S"home\\.unbox\\ida_batch_decompile.py -o\\"tmpfolder\\unbox3fcvpg\\7-zip32.c\\""', '"7-zip32.dll"']
93 | [handler.base/2808][DEBUG ] [base.get_path ] scheme: c
94 | [handler.base/2808][DEBUG ] [base.get_path ]
95 | [handler.local/2808][DEBUG ] [local.walk ] walk: tmpfolder
96 |
97 | [handler.base/2808][DEBUG ] [base.get_path ] unknown: tmpfolder\7-zip32.c
98 | [handler.base/2808][DEBUG ] [base.get_path ] {'source': 'databuffer', 'magic': None}
99 | [handler.base/2808][DEBUG ] [base.get_path ] scheme: c
100 | [handler.base/2808][DEBUG ] [base.get_path ]
101 | tmpfolder/unbox3fcvpg/7-zip32.c
102 |
103 | ```
104 |
105 | ### Decompile a windows DLL
106 |
107 | ```
108 | #> unbox/cli.py extract "samples\7-zip32.dll"
109 | [handler.base/9848][DEBUG ] [base.get_path ] unknown: 7-zip32.dll
110 | [handler.base/9848][DEBUG ] [base.get_path ] {'source': 'databuffer', 'magic': {'mimetype': 'application/x-executable-mz', 'patterns': [{'regex': '\\x4D\\x5A', 'offset': 0, 'size': 2}], 'shortname': 'EXE', 'id': 31, 'longname': 'Windows Executable'}}
111 | [handler.base/9848][DEBUG ] [base.get_path ] 2
112 | [handler.commands.commands/9848][DEBUG ] [commands.decompile ] [u'ida\\idaw.exe', '-B', '-M', '-S"home\\.unbox\\ida_batch_decompile.py -o\\"tmpfolder\\unboxdaj2bd\\7-zip32.c\\""', '"7-zip32.dll"']
113 | [handler.base/9848][DEBUG ] [base.get_path ] scheme: c
114 | [handler.base/9848][DEBUG ] [base.get_path ]
115 | [handler.local/9848][DEBUG ] [local.walk ] walk: tmpfolder\unboxdaj2bd
116 |
117 | [handler.base/9848][DEBUG ] [base.get_path ] unknown: tmpfolder\unboxdaj2bd\7-zip32.c
118 | [handler.base/9848][DEBUG ] [base.get_path ] {'source': 'databuffer', 'magic': None}
119 | [handler.base/9848][DEBUG ] [base.get_path ] scheme: c
120 | [handler.base/9848][DEBUG ] [base.get_path ]
121 | tmpfolder\unboxdaj2bd\7-zip32.c
122 | ```
123 |
124 | ### Unpack and decompile apk
125 |
126 | (java) while decompiling binary applications on the fly (see ida output below)
127 |
128 | ```
129 | #> unbox/cli.py extract test.apk
130 | [handler.decompilable/13668][DEBUG ] [decompilable._fetch ] destination: test.apk.jar
131 | [handler.utils.shell/13668][DEBUG ] [shell.execute ] [u'dex-tools-2.0\\dex2jar-2.0\\d2j-dex2jar.bat', '-o', 'tmpfolder\\unboxsmansz\\test.apk.jar', 'test.apk']
132 | dex2jar test.apk -> tmpfolder\unboxsmansz\test.apk.jar
133 | [handler.decompilable/13668][DEBUG ] [decompilable._fetch ] unpack .apk to tmpfolder\unboxsmansz\.apk
134 | [handler.decompilable/13668][DEBUG ] [decompilable._fetch ] decompile .jar to tmpfolder\unboxsmansz\.source
135 | [handler.utils.shell/13668][DEBUG ] [shell.execute ] [u'jd-cli\\jd-cli.bat', '--outputDir', 'tmpfolder\\unboxsmansz\\.source', 'test.apk.jar']
136 | 21:05:30.434 INFO jd.cli.Main - Decompiling tmpfolder\unboxsmansz\test.apk.jar
137 | 21:05:30.467 INFO jd.core.output.DirOutput - Directory output will be initialized for path tmpfolder\unboxsmansz\.source
138 | 21:05:30.787 WARN jd.core.output.DirOutput - Class name or java source is null
139 | ReferenceMap.add: InvalidParameterException(android/util/SparseArray)
140 | ConstantPool.addConstantClass: invalid name index
141 | ConstantPool.addConstantClass: invalid name index
142 | ConstantPool.addConstantClass: invalid name index
143 | ReferenceMap.add: InvalidParameterException(java/util/Map)
144 | ReferenceMap.add: InvalidParameterException(java/util/Map)
145 | Undefined type catch
146 | Undefined type catch
147 | Undefined type catch
148 | Undefined type catch
149 | Undefined type catch
150 | Undefined type catch
151 | Undefined type catch
152 | Undefined type catch
153 | java.lang.Throwable: NameGenerator.generateParameterNameFromSignature: invalid signature 'TT;'
154 | at jd.core.process.analyzer.variable.DefaultVariableNameGenerator.generateLocalVariableNameFromSignature(DefaultVariableNameGenerator.java:106)
155 | at jd.core.process.analyzer.classfile.LocalVariableAnalyzer.GenerateLocalVariableNames(LocalVariableAnalyzer.java:1733)
156 | at jd.core.process.analyzer.classfile.LocalVariableAnalyzer.Analyze(LocalVariableAnalyzer.java:206)
157 | at jd.core.process.analyzer.classfile.ClassFileAnalyzer.PreAnalyzeMethods(ClassFileAnalyzer.java:698)
158 | at jd.core.process.analyzer.classfile.ClassFileAnalyzer.AnalyzeClass(ClassFileAnalyzer.java:126)
159 | at jd.core.process.analyzer.classfile.ClassFileAnalyzer.Analyze(ClassFileAnalyzer.java:84)
160 | at jd.commonide.IdeDecompiler.decompile(IdeDecompiler.java:49)
161 | at jd.core.JavaDecompiler.decompile(JavaDecompiler.java:121)
162 | at jd.core.JavaDecompiler.decompileClass(JavaDecompiler.java:58)
163 | at jd.core.input.ZipFileInput.decompile(ZipFileInput.java:87)
164 | at jd.cli.Main.main(Main.java:118)
165 | 21:05:56.837 WARN jd.core.output.DirOutput - Class name or java source is null
166 | 21:05:56.848 WARN jd.core.output.DirOutput - Class name or java source is null
167 | 21:05:57.270 WARN jd.core.output.DirOutput - Class name or java source is null
168 | 21:05:57.293 WARN jd.core.output.DirOutput - Class name or java source is null
169 | 21:05:57.441 WARN jd.core.output.DirOutput - Class name or java source is null
170 | 21:05:57.445 WARN jd.core.output.DirOutput - Class name or java source is null
171 | 21:05:57.501 WARN jd.core.output.DirOutput - Class name or java source is null
172 | 21:05:57.502 WARN jd.core.output.DirOutput - Class name or java source is null
173 | 21:05:57.506 WARN jd.core.output.DirOutput - Class name or java source is null
174 | 21:05:57.507 WARN jd.core.output.DirOutput - Class name or java source is null
175 | 21:05:57.510 WARN jd.core.output.DirOutput - Class name or java source is null
176 | 21:05:57.522 WARN jd.core.output.DirOutput - Class name or java source is null
177 | 21:05:57.527 WARN jd.core.output.DirOutput - Class name or java source is null
178 | 21:05:57.543 WARN jd.core.output.DirOutput - Class name or java source is null
179 | 21:05:57.547 WARN jd.core.output.DirOutput - Class name or java source is null
180 | 21:05:58.220 WARN jd.core.output.DirOutput - Class name or java source is null
181 | 21:05:58.414 WARN jd.core.output.DirOutput - Class name or java source is null
182 | Undefined type catch
183 | Undefined type catch
184 | Undefined type catch
185 | Undefined type catch
186 | ReferenceMap.add: InvalidParameterException(java/util/Map)
187 | 21:06:04.651 WARN jd.core.output.DirOutput - Class name or java source is null
188 | ReferenceMap.add: InvalidParameterException(java/util/Map)
189 | ReferenceMap.add: InvalidParameterException(java/util/Map)
190 | ReferenceMap.add: InvalidParameterException(java/util/Map)
191 | ReferenceMap.add: InvalidParameterException(java/util/Map)
192 | ReferenceMap.add: InvalidParameterException(java/util/Map)
193 | ReferenceMap.add: InvalidParameterException(java/util/Map)
194 | Undefined type catch
195 | ConstantPool.addConstantClass: invalid name index
196 | ConstantPool.addConstantClass: invalid name index
197 | ConstantPool.addConstantClass: invalid name index
198 | ConstantPool.addConstantClass: invalid name index
199 | ConstantPool.addConstantClass: invalid name index
200 | ConstantPool.addConstantClass: invalid name index
201 | ConstantPool.addConstantClass: invalid name index
202 | ConstantPool.addConstantClass: invalid name index
203 | ConstantPool.addConstantClass: invalid name index
204 | ConstantPool.addConstantClass: invalid name index
205 | ConstantPool.addConstantClass: invalid name index
206 | ConstantPool.addConstantClass: invalid name index
207 | ConstantPool.addConstantClass: invalid name index
208 | ConstantPool.addConstantClass: invalid name index
209 | ConstantPool.addConstantClass: invalid name index
210 | ConstantPool.addConstantClass: invalid name index
211 | ReferenceMap.add: InvalidParameterException(java/util/Map)
212 | ReferenceMap.add: InvalidParameterException(java/util/ArrayList)
213 | 21:06:11.038 WARN jd.core.output.DirOutput - Class name or java source is null
214 | java.lang.Throwable: NameGenerator.generateParameterNameFromSignature: invalid signature 'TT;'
215 | at jd.core.process.analyzer.variable.DefaultVariableNameGenerator.generateLocalVariableNameFromSignature(DefaultVariableNameGenerator.java:106)
216 | at jd.core.process.analyzer.classfile.LocalVariableAnalyzer.GenerateLocalVariableNames(LocalVariableAnalyzer.java:1733)
217 | at jd.core.process.analyzer.classfile.LocalVariableAnalyzer.Analyze(LocalVariableAnalyzer.java:206)
218 | at jd.core.process.analyzer.classfile.ClassFileAnalyzer.PreAnalyzeMethods(ClassFileAnalyzer.java:698)
219 | at jd.core.process.analyzer.classfile.ClassFileAnalyzer.AnalyzeClass(ClassFileAnalyzer.java:126)
220 | at jd.core.process.analyzer.classfile.ClassFileAnalyzer.Analyze(ClassFileAnalyzer.java:84)
221 | at jd.commonide.IdeDecompiler.decompile(IdeDecompiler.java:49)
222 | at jd.core.JavaDecompiler.decompile(JavaDecompiler.java:121)
223 | at jd.core.JavaDecompiler.decompileClass(JavaDecompiler.java:58)
224 | at jd.core.input.ZipFileInput.decompile(ZipFileInput.java:87)
225 | at jd.cli.Main.main(Main.java:118)
226 | ConstantPool.addConstantClass: invalid name index
227 | ConstantPool.addConstantClass: invalid name index
228 | ConstantPool.addConstantClass: invalid name index
229 | ConstantPool.addConstantClass: invalid name index
230 | ConstantPool.addConstantClass: invalid name index
231 | ConstantPool.addConstantClass: invalid name index
232 | ConstantPool.addConstantClass: invalid name index
233 | ConstantPool.addConstantClass: invalid name index
234 | ConstantPool.addConstantClass: invalid name index
235 | Undefined type catch
236 | Undefined type catch
237 | Undefined type catch
238 | Undefined type catch
239 | Undefined type catch
240 | Undefined type catch
241 | Undefined type catch
242 | Undefined type catch
243 | ConstantPool.addConstantClass: invalid name index
244 | ConstantPool.addConstantClass: invalid name index
245 | ConstantPool.addConstantClass: invalid name index
246 | ConstantPool.addConstantClass: invalid name index
247 | 21:06:19.486 INFO jd.core.output.DirOutput - Finished with 2593 class file(s) and 0 resource file(s) written.
248 | [handler.decompilable/13668][DEBUG ] [decompilable._fetch ] remove .jar - we do not need it anymore
249 | [handler.base/13668][DEBUG ] [base.get_path ] scheme: c
250 | [handler.base/13668][DEBUG ] [base.get_path ]
251 | [handler.local/13668][DEBUG ] [local.walk ] walk: tmpfolder\unboxsmansz
252 | 21:06:19.486 INFO jd.core.output.DirOutput - Finished with 2593 class file(s) and 0 resource file(s) written.
253 | [handler.decompilable/13668][DEBUG ] [decompilable._fetch ] remove .jar - we do not need it anymore
254 | [handler.base/13668][DEBUG ] [base.get_path ] scheme: c
255 | [handler.base/13668][DEBUG ] [base.get_path ]
256 | [handler.local/13668][DEBUG ] [local.walk ] walk: tmpfolder\unboxsmansz
257 |
258 | [handler.base/13668][DEBUG ] [base.get_path ] unknown: tmpfolder\unboxsmansz\.apk\AndroidManifest.xml
259 | tmpfolder\unboxsmansz\.apk\AndroidManifest.xml
260 | [handler.base/13668][DEBUG ] [base.get_path ] {'source': 'databuffer', 'magic': None}
261 | [handler.base/13668][DEBUG ] [base.get_path ] scheme: c
262 | [handler.base/13668][DEBUG ] [base.get_path ]
263 | [handler.base/13668][DEBUG ] [base.get_path ] unknown: tmpfolder\unboxsmansz\.apk\classes.dex
264 | [handler.base/13668][DEBUG ] [base.get_path ] {'source': 'databuffer', 'magic': None}
265 | tmpfolder\unboxsmansz\.apk\classes.dex
266 | [handler.base/13668][DEBUG ] [base.get_path ] scheme: c
267 | [handler.base/13668][DEBUG ] [base.get_path ]
268 | [handler.base/13668][DEBUG ] [base.get_path ] unknown: tmpfolder\unboxsmansz\.apk\resources.arsc
269 | [handler.base/13668][DEBUG ] [base.get_path ] {'source': 'databuffer', 'magic': None}
270 | tmpfolder\unboxsmansz\.apk\resources.arsc
271 | [handler.base/13668][DEBUG ] [base.get_path ] scheme: c
272 | [handler.base/13668][DEBUG ] [base.get_path ]
273 | [handler.base/13668][DEBUG ] [base.get_path ] unknown: tmpfolder\unboxsmansz\.apk\assets\fonts\eurostilebold.ttf
274 | [handler.base/13668][DEBUG ] [base.get_path ] {'source': 'databuffer', 'magic': {'mimetype': 'application/x-font-ttf', 'patterns': [{'regex': '\\x00\\x01\\x00\\x00\\x00', 'offset': 0, 'size': 5}], 'shortname': 'TTF', 'id': 32, 'longname': 'TrueType Font'}}
275 | [handler.base/13668][DEBUG ] [base.get_path ] None
276 | [handler.commands.commands/13668][DEBUG ] [commands.decompile ] [u'ida\\idaw.exe', '-B', '-M', '-S"home\\.unbox\\ida_batch_decompile.py -o\\"tmpfolder\\unboxeqk0no\\eurostilebold.c\\""', '"tmpfolder\\unboxsmansz\\.apk\\assets\\fonts\\eurostilebold.ttf"']
277 | [handler.base/13668][DEBUG ] [base.get_path ] scheme: c
278 | [handler.base/13668][DEBUG ] [base.get_path ]
279 | [handler.local/13668][DEBUG ] [local.walk ] walk: tmpfolder\unboxeqk0no
280 | ...
281 |
282 | ...
283 | tmpfolder\unboxsmansz\.source\org\stockchart\e\h$a.java
284 | tmpfolder\unboxsmansz\.source\org\stockchart\e\h.java
285 | [handler.base/13668][DEBUG ] [base.get_path ] {'source': 'databuffer', 'magic': None}
286 | [handler.base/13668][DEBUG ] [base.get_path ] scheme: c
287 | [handler.base/13668][DEBUG ] [base.get_path ]
288 | [handler.base/13668][DEBUG ] [base.get_path ] unknown: tmpfolder\unboxsmansz\.source\org\stockchart\e\i.java
289 | [handler.base/13668][DEBUG ] [base.get_path ] {'source': 'databuffer', 'magic': None}
290 | [handler.base/13668][DEBUG ] [base.get_path ] scheme: c
291 | [handler.base/13668][DEBUG ] [base.get_path ]
292 | tmpfolder\unboxsmansz\.source\org\stockchart\e\i.java
293 | ```
294 |
295 | # Contribute :trophy:
296 |
297 | ## Add new tools and file formats
298 |
299 | TBD
300 |
301 | * add external command wrapper to `handler.commands.commands`
302 | * add the file handler to `handler.`
303 | * route the file to the correct handler in `handler.base.UniversalPath.get_path`
304 |
305 |
306 | ## Supported Formats and implemented 3rd Party Applications:
307 |
308 | | Status | Type | Tool Dependency | ref |
309 | |--------|--------|------------------|-----|
310 | | :heavy_check_mark: | archive | patool or 7z | - |
311 | | :heavy_check_mark: | browser extension | patool or 7z | - |
312 | | :heavy_check_mark: | .net application | JustDecompile (windows) | https://github.com/telerik/JustDecompileEngine |
313 | | :heavy_check_mark: | apk | dex2jar and jd-cli | https://github.com/pxb1988/dex2jar |
314 | | :heavy_check_mark: | compiled java | jd-cli | https://github.com/kwart/jd-cmd |
315 | | :heavy_check_mark: | binary applications |IDA PRO / RetDec :x: | https://www.hex-rays.com/products/ida/ https://github.com/avast-tl/retdec |
316 | | :x: | Ethereum solidity smart contract | porosity | https://github.com/comaeio/porosity/ |
317 | | :x: | compiled python | python-uncompyle6 | https://github.com/rocky/python-uncompyle6/ |
318 |
319 |
320 | Are you missing your favorite decompiler? Let me know or create a PR
321 |
--------------------------------------------------------------------------------
/cigma/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tintinweb/unbox/afcb1c3df5fd24e7c98bc90f88dc5239e8fd95c4/cigma/__init__.py
--------------------------------------------------------------------------------
/cigma/cigma.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import os
4 | import re
5 | import sys
6 | import json
7 | import string
8 | import collections
9 | from pprint import pprint
10 |
11 | class Cigma:
12 | def __init__(self, magicfile="%s/magicbytes.json" % os.path.dirname(__file__), csvfile="%s/sigs.csv" % os.path.dirname(__file__)):
13 | self.filename = None
14 | self.data = None
15 | self.magic = None
16 | self.magicfile = magicfile
17 | self.sigs = self._load_json_file(self.magicfile)
18 | self.csvfile = csvfile
19 | self.result = dict({
20 | "source": None,
21 | "magic": None
22 | })
23 |
24 | # loads a json file and converts unicode key-value pairs to ascii
25 | def _load_json_file(self, filename):
26 | # http://stackoverflow.com/questions/1254454/fastest-way-to-convert-a-dicts-keys-values-from-unicode-to-str
27 | def unicode_to_string(data):
28 | if isinstance(data, basestring):
29 | return data.encode('utf-8')
30 | elif isinstance(data, collections.Mapping):
31 | return dict(map(unicode_to_string, data.iteritems()))
32 | elif isinstance(data, collections.Iterable):
33 | return type(data)(map(unicode_to_string, data))
34 | else:
35 | return data
36 |
37 | with open(filename) as jsonfile:
38 | return dict(unicode_to_string(json.load(jsonfile)))
39 |
40 | def reload_sigs(self):
41 | self.sigs = None
42 | self.sigs = self._load_json_file(self.magicfile)
43 |
44 | def add_sigs(self):
45 | data = open(self.csvfile, "r").readlines()
46 | for line in data:
47 | regex = "\\x%s" % (line.split(";")[0].strip().replace(" ", "\\x"))
48 | shortname = line.split(";")[1].strip()
49 | count = len(self.sigs["rules"]) + 1
50 | self.sigs["rules"].append(dict({
51 | "id": count,
52 | "longname": "",
53 | "mimetype": "",
54 | "patterns": [
55 | {
56 | "offset": 0,
57 | "regex": regex,
58 | "size": len(regex.replace("\\x", "")) / 2
59 | }
60 | ],
61 | "shortname": shortname
62 | }))
63 | self.sigs["meta"]["rulescount"] = len(self.sigs["rules"])
64 |
65 | with open(self.magicfile, "w") as fo:
66 | fo.write(json.dumps(self.sigs, indent=2, sort_keys=True))
67 |
68 | def cigma(self, data=None, filename=None):
69 | if data:
70 | self.data = data
71 | elif filename:
72 | self.filename = filename
73 | with open(self.filename) as fo:
74 | self.data = fo.read()
75 | else:
76 | raise Exception("Pass a filename or data")
77 |
78 | for sig in self.sigs["rules"]:
79 | for idx, pattern in enumerate(sig["patterns"]):
80 | # match upon the size bytes of data extracted from offset
81 | if not re.search(pattern["regex"], self.data[pattern["offset"]:pattern["offset"]+pattern["size"]]):
82 | # by default, all regexes in the patterns list have to match
83 | # we will stop matching at the first failure
84 | self.result["magic"] = None
85 | break
86 | else:
87 | # load the signature details in case this is the final regex to be matched
88 | self.result["magic"] = sig
89 |
90 | # stop testing rest of the sigs if we have already found a match
91 | if self.result["magic"]:
92 | break
93 |
94 | self.result["source"] = self.filename if self.filename else "databuffer"
95 | return self.result
96 |
97 |
98 | if __name__ == "__main__":
99 | if len(sys.argv) != 2:
100 | print "USAGE: %s " % (sys.argv[0])
101 | sys.exit(1)
102 |
103 | # pass filename or file data via appropriate constructor argument
104 | # the cigma() method will read data from file (if given)
105 | # as such, it always works on file data
106 | #pprint(Cigma().cigma(filename=sys.argv[1]))
107 |
108 | pprint(Cigma().cigma(filename=sys.argv[1]))
109 |
--------------------------------------------------------------------------------
/cigma/magicbytes.json:
--------------------------------------------------------------------------------
1 | {
2 | "meta": {
3 | "rulescount": 72,
4 | "version": 0.1
5 | },
6 | "rules": [
7 | {
8 | "id": 1,
9 | "longname": "PKZIP",
10 | "mimetype": "application/octet-stream",
11 | "patterns": [
12 | {
13 | "offset": 0,
14 | "regex": "\\x50\\x4B\\x05\\x06",
15 | "size": 4
16 | }
17 | ],
18 | "shortname": "ZIP"
19 | },
20 | {
21 | "id": 2,
22 | "longname": "PKZIP",
23 | "mimetype": "text/plain",
24 | "patterns": [
25 | {
26 | "offset": 0,
27 | "regex": "\\x50\\x4B\\x07\\x08",
28 | "size": 4
29 | }
30 | ],
31 | "shortname": "ZIP"
32 | },
33 | {
34 | "id": 3,
35 | "longname": "",
36 | "mimetype": "",
37 | "patterns": [
38 | {
39 | "offset": 0,
40 | "regex": "\\x30\\x00\\x00\\x00\\x4C\\x66\\x4C\\x65",
41 | "size": 8
42 | }
43 | ],
44 | "shortname": ""
45 | },
46 | {
47 | "id": 4,
48 | "longname": "Musical Instrument Digital Interface (MIDI)",
49 | "mimetype": "audio/midi",
50 | "patterns": [
51 | {
52 | "offset": 0,
53 | "regex": "\\x4D\\x54\\x68\\x64",
54 | "size": 4
55 | }
56 | ],
57 | "shortname": "MIDI"
58 | },
59 | {
60 | "id": 5,
61 | "longname": "Packet Capture (winpcap)",
62 | "mimetype": "application/vnd.tcpdump.pcap",
63 | "patterns": [
64 | {
65 | "offset": 0,
66 | "regex": "\\xD4\\xC3\\xB2\\xA1",
67 | "size": 4
68 | }
69 | ],
70 | "shortname": "PCAP"
71 | },
72 | {
73 | "id": 6,
74 | "longname": "Photoshop Document (PSD)",
75 | "mimetype": "image/vnd.adobe.photoshop",
76 | "patterns": [
77 | {
78 | "offset": 0,
79 | "regex": "\\x38\\x42\\x50\\x53\\x00\\x01",
80 | "size": 6
81 | }
82 | ],
83 | "shortname": "PSD"
84 | },
85 | {
86 | "id": 7,
87 | "longname": "PKZIP",
88 | "mimetype": "application/zip",
89 | "patterns": [
90 | {
91 | "offset": 0,
92 | "regex": "\\x50\\x4B\\x03\\x04",
93 | "size": 4
94 | }
95 | ],
96 | "shortname": "ZIP"
97 | },
98 | {
99 | "id": 8,
100 | "longname": "Microsoft Cabinet (CAB)",
101 | "mimetype": "text/plain",
102 | "patterns": [
103 | {
104 | "offset": 0,
105 | "regex": "\\x4D\\x53\\x43\\x46",
106 | "size": 4
107 | }
108 | ],
109 | "shortname": "CAB"
110 | },
111 | {
112 | "id": 9,
113 | "longname": "Microsoft Object Linking and Embedding (OLE)",
114 | "mimetype": "application/octet-stream",
115 | "patterns": [
116 | {
117 | "offset": 0,
118 | "regex": "\\xD0\\xCF\\x11\\xE0\\xA1\\xB1\\x1A\\xE1",
119 | "size": 8
120 | }
121 | ],
122 | "shortname": "OLE"
123 | },
124 | {
125 | "id": 10,
126 | "longname": "MP3",
127 | "mimetype": "text/plain",
128 | "patterns": [
129 | {
130 | "offset": 0,
131 | "regex": "\\x49\\x44\\x33",
132 | "size": 3
133 | }
134 | ],
135 | "shortname": "MP3"
136 | },
137 | {
138 | "id": 11,
139 | "longname": "MPEG",
140 | "mimetype": "video/mpeg",
141 | "patterns": [
142 | {
143 | "offset": 0,
144 | "regex": "\\x00\\x00\\x01\\xBA",
145 | "size": 4
146 | }
147 | ],
148 | "shortname": "MPG"
149 | },
150 | {
151 | "id": 12,
152 | "longname": "ZIP",
153 | "mimetype": "application/zip",
154 | "patterns": [
155 | {
156 | "offset": 0,
157 | "regex": "\\x50\\x4B\\x03\\x04\\x14\\x00\\x00\\x00",
158 | "size": 8
159 | }
160 | ],
161 | "shortname": "ZIP"
162 | },
163 | {
164 | "id": 13,
165 | "longname": "Packet Capture (winpcap;Big-endian)",
166 | "mimetype": "application/vnd.tcpdump.pcap",
167 | "patterns": [
168 | {
169 | "offset": 0,
170 | "regex": "\\xA1\\xB2\\xC3\\xD4",
171 | "size": 4
172 | }
173 | ],
174 | "shortname": "PCAP"
175 | },
176 | {
177 | "id": 14,
178 | "longname": "Windows Shortcut",
179 | "mimetype": "application/octet-stream",
180 | "patterns": [
181 | {
182 | "offset": 0,
183 | "regex": "\\x4C\\x00\\x00\\x00\\x01\\x14\\x02\\x00",
184 | "size": 8
185 | }
186 | ],
187 | "shortname": "LNK"
188 | },
189 | {
190 | "id": 15,
191 | "longname": "Word Open XML",
192 | "mimetype": "application/zip",
193 | "patterns": [
194 | {
195 | "offset": 0,
196 | "regex": "\\x50\\x4B\\x03\\x04\\x14\\x00\\x06\\x00",
197 | "size": 8
198 | }
199 | ],
200 | "shortname": "DOCX"
201 | },
202 | {
203 | "id": 16,
204 | "longname": "Windows Graphics Metafile",
205 | "mimetype": "text/plain",
206 | "patterns": [
207 | {
208 | "offset": 0,
209 | "regex": "\\xD7\\xCD\\xC6\\x9A",
210 | "size": 4
211 | }
212 | ],
213 | "shortname": "WMF"
214 | },
215 | {
216 | "id": 17,
217 | "longname": "Windows Icon",
218 | "mimetype": "image/x-icon",
219 | "patterns": [
220 | {
221 | "offset": 0,
222 | "regex": "\\x00\\x00\\x01\\x00",
223 | "size": 4
224 | }
225 | ],
226 | "shortname": "ICO"
227 | },
228 | {
229 | "id": 18,
230 | "longname": "7zip",
231 | "mimetype": "application/x-7z-compressed",
232 | "patterns": [
233 | {
234 | "offset": 0,
235 | "regex": "\\x37\\x7A\\xBC\\xAF\\x27\\x1C",
236 | "size": 6
237 | }
238 | ],
239 | "shortname": "7Z"
240 | },
241 | {
242 | "id": 19,
243 | "longname": "Audio Video Interleaved",
244 | "mimetype": "text/plain",
245 | "patterns": [
246 | {
247 | "offset": 0,
248 | "regex": "\\x52\\x49\\x46\\x46",
249 | "size": 4
250 | }
251 | ],
252 | "shortname": "AVI"
253 | },
254 | {
255 | "id": 20,
256 | "longname": "Advanced Systems Format [Windows Media]",
257 | "mimetype": "video/x-ms-asf",
258 | "patterns": [
259 | {
260 | "offset": 0,
261 | "regex": "\\x30\\x26\\xB2\\x75\\x8E\\x66\\xCF\\x11",
262 | "size": 8
263 | }
264 | ],
265 | "shortname": "ASF"
266 | },
267 | {
268 | "id": 21,
269 | "longname": "Compressed File (LZH)",
270 | "mimetype": "application/octet-stream",
271 | "patterns": [
272 | {
273 | "offset": 0,
274 | "regex": "\\x1F\\xA0",
275 | "size": 2
276 | }
277 | ],
278 | "shortname": "TAR.Z"
279 | },
280 | {
281 | "id": 22,
282 | "longname": "Bitmap Image",
283 | "mimetype": "text/plain",
284 | "patterns": [
285 | {
286 | "offset": 0,
287 | "regex": "\\x42\\x4D",
288 | "size": 2
289 | }
290 | ],
291 | "shortname": "BMP"
292 | },
293 | {
294 | "id": 23,
295 | "longname": "Compressed Flash File (LZMA)",
296 | "mimetype": "text/plain",
297 | "patterns": [
298 | {
299 | "offset": 0,
300 | "regex": "\\x5A\\x57\\x53",
301 | "size": 3
302 | }
303 | ],
304 | "shortname": "SWF"
305 | },
306 | {
307 | "id": 24,
308 | "longname": "Compressed File (LZW)",
309 | "mimetype": "application/x-compress",
310 | "patterns": [
311 | {
312 | "offset": 0,
313 | "regex": "\\x1F\\x9D",
314 | "size": 2
315 | }
316 | ],
317 | "shortname": "TAR.Z"
318 | },
319 | {
320 | "id": 25,
321 | "longname": "E-Mail Message",
322 | "mimetype": "text/plain",
323 | "patterns": [
324 | {
325 | "offset": 0,
326 | "regex": "\\x46\\x72\\x6F\\x6D",
327 | "size": 4
328 | }
329 | ],
330 | "shortname": "EML"
331 | },
332 | {
333 | "id": 26,
334 | "longname": "Compressed Flash File (ZLIB)",
335 | "mimetype": "application/x-shockwave-flash",
336 | "patterns": [
337 | {
338 | "offset": 0,
339 | "regex": "\\x43\\x57\\x53",
340 | "size": 3
341 | }
342 | ],
343 | "shortname": "SWF"
344 | },
345 | {
346 | "id": 27,
347 | "longname": "Flash Video",
348 | "mimetype": "video/x-flv",
349 | "patterns": [
350 | {
351 | "offset": 0,
352 | "regex": "\\x46\\x4C\\x56",
353 | "size": 3
354 | }
355 | ],
356 | "shortname": "FLV"
357 | },
358 | {
359 | "id": 28,
360 | "longname": "eXtensible Markup Language (XML)",
361 | "mimetype": "text/plain",
362 | "patterns": [
363 | {
364 | "offset": 0,
365 | "regex": "\\x3C",
366 | "size": 1
367 | }
368 | ],
369 | "shortname": "XML"
370 | },
371 | {
372 | "id": 29,
373 | "longname": "Executable and Linkable Format (ELF)",
374 | "mimetype": "application/x-executable-32",
375 | "patterns": [
376 | {
377 | "offset": 0,
378 | "regex": "\\x7F\\x45\\x4C\\x46\\x01",
379 | "size": 4
380 | }
381 | ],
382 | "shortname": "ELF"
383 | },
384 | {
385 | "id": 29,
386 | "longname": "Executable and Linkable Format (ELF)",
387 | "mimetype": "application/x-executable-64",
388 | "patterns": [
389 | {
390 | "offset": 0,
391 | "regex": "\\x7F\\x45\\x4C\\x46\\x02",
392 | "size": 4
393 | }
394 | ],
395 | "shortname": "ELF"
396 | },
397 | {
398 | "id": 30,
399 | "longname": "Excel Open XML",
400 | "mimetype": "application/zip",
401 | "patterns": [
402 | {
403 | "offset": 0,
404 | "regex": "\\x50\\x4B\\x03\\x04\\x14\\x00\\x06\\x00",
405 | "size": 8
406 | }
407 | ],
408 | "shortname": "XLSX"
409 | },
410 | {
411 | "id": 31,
412 | "longname": "Windows Executable",
413 | "mimetype": "application/x-executable-mz",
414 | "patterns": [
415 | {
416 | "offset": 0,
417 | "regex": "\\x4D\\x5A",
418 | "size": 2
419 | }
420 | ],
421 | "shortname": "EXE"
422 | },
423 | {
424 | "id": 32,
425 | "longname": "TrueType Font",
426 | "mimetype": "application/x-font-ttf",
427 | "patterns": [
428 | {
429 | "offset": 0,
430 | "regex": "\\x00\\x01\\x00\\x00\\x00",
431 | "size": 5
432 | }
433 | ],
434 | "shortname": "TTF"
435 | },
436 | {
437 | "id": 33,
438 | "longname": "GZIP",
439 | "mimetype": "application/gzip",
440 | "patterns": [
441 | {
442 | "offset": 0,
443 | "regex": "\\x1F\\x8B\\x08",
444 | "size": 3
445 | }
446 | ],
447 | "shortname": "GZ"
448 | },
449 | {
450 | "id": 34,
451 | "longname": "GIF Image",
452 | "mimetype": "image/gif",
453 | "patterns": [
454 | {
455 | "offset": 0,
456 | "regex": "\\x47\\x49\\x46\\x38",
457 | "size": 4
458 | }
459 | ],
460 | "shortname": "GIF"
461 | },
462 | {
463 | "id": 35,
464 | "longname": "Java Archive (JAR)",
465 | "mimetype": "application/zip",
466 | "patterns": [
467 | {
468 | "offset": 0,
469 | "regex": "\\x50\\x4B\\x03\\x04\\x14\\x00\\x08\\x00",
470 | "size": 8
471 | }
472 | ],
473 | "shortname": "JAR"
474 | },
475 | {
476 | "id": 36,
477 | "longname": "HyperText Markup Language (HTML)",
478 | "mimetype": "text/plain",
479 | "patterns": [
480 | {
481 | "offset": 0,
482 | "regex": "\\x3C",
483 | "size": 1
484 | }
485 | ],
486 | "shortname": "HTML"
487 | },
488 | {
489 | "id": 37,
490 | "longname": "Matroska Stream",
491 | "mimetype": "application/octet-stream",
492 | "patterns": [
493 | {
494 | "offset": 0,
495 | "regex": "\\x1A\\x45\\xDF\\xA3\\x93\\x42\\x82\\x88",
496 | "size": 8
497 | }
498 | ],
499 | "shortname": "MKV"
500 | },
501 | {
502 | "id": 38,
503 | "longname": "JPEG Image",
504 | "mimetype": "image/jpeg",
505 | "patterns": [
506 | {
507 | "offset": 0,
508 | "regex": "\\xFF\\xD8\\xFF",
509 | "size": 3
510 | }
511 | ],
512 | "shortname": "JPG"
513 | },
514 | {
515 | "id": 39,
516 | "longname": "Portable Network Graphics (PNG)",
517 | "mimetype": "text/plain",
518 | "patterns": [
519 | {
520 | "offset": 0,
521 | "regex": "\\x89\\x50\\x4E\\x47",
522 | "size": 4
523 | }
524 | ],
525 | "shortname": "PNG"
526 | },
527 | {
528 | "id": 40,
529 | "longname": "Portable Document Format (PDF)",
530 | "mimetype": "application/pdf",
531 | "patterns": [
532 | {
533 | "offset": 0,
534 | "regex": "\\x25\\x50\\x44\\x46",
535 | "size": 4
536 | }
537 | ],
538 | "shortname": "PDF"
539 | },
540 | {
541 | "id": 41,
542 | "longname": "Tcpdump Capture",
543 | "mimetype": "text/plain",
544 | "patterns": [
545 | {
546 | "offset": 0,
547 | "regex": "\\x34\\xCD\\xB2\\xA1",
548 | "size": 4
549 | }
550 | ],
551 | "shortname": "PCAP"
552 | },
553 | {
554 | "id": 42,
555 | "longname": "Tagged Image File Format",
556 | "mimetype": "image/tiff",
557 | "patterns": [
558 | {
559 | "offset": 0,
560 | "regex": "\\x4D\\x4D\\x00\\x2A",
561 | "size": 4
562 | }
563 | ],
564 | "shortname": "TIF"
565 | },
566 | {
567 | "id": 43,
568 | "longname": "Tagged Image File Format",
569 | "mimetype": "image/tiff",
570 | "patterns": [
571 | {
572 | "offset": 0,
573 | "regex": "\\x49\\x49\\x2A\\x00",
574 | "size": 4
575 | }
576 | ],
577 | "shortname": "TIF"
578 | },
579 | {
580 | "id": 44,
581 | "longname": "Silverlight Application Package",
582 | "mimetype": "application/zip",
583 | "patterns": [
584 | {
585 | "offset": 0,
586 | "regex": "\\x50\\x4B\\x03\\x04",
587 | "size": 4
588 | }
589 | ],
590 | "shortname": "XAP"
591 | },
592 | {
593 | "id": 45,
594 | "longname": "Rich Text Format",
595 | "mimetype": "text/rtf",
596 | "patterns": [
597 | {
598 | "offset": 0,
599 | "regex": "\\x7B\\x5C\\x72\\x74\\x66\\x31",
600 | "size": 6
601 | }
602 | ],
603 | "shortname": "RTF"
604 | },
605 | {
606 | "id": 46,
607 | "longname": "PowerPoint Open XML format",
608 | "mimetype": "application/zip",
609 | "patterns": [
610 | {
611 | "offset": 0,
612 | "regex": "\\x50\\x4B\\x03\\x04\\x14\\x00\\x06\\x00",
613 | "size": 8
614 | }
615 | ],
616 | "shortname": "PPTX"
617 | },
618 | {
619 | "id": 47,
620 | "longname": "",
621 | "mimetype": "",
622 | "patterns": [
623 | {
624 | "offset": 0,
625 | "regex": "\\x50\\x4B\\x53\\x70\\x58",
626 | "size": 5
627 | }
628 | ],
629 | "shortname": "PKSFX"
630 | },
631 | {
632 | "id": 48,
633 | "longname": "",
634 | "mimetype": "",
635 | "patterns": [
636 | {
637 | "offset": 0,
638 | "regex": "\\x46\\x75\\x6E\\x63\\x74\\x69\\x6F\\x6E",
639 | "size": 8
640 | }
641 | ],
642 | "shortname": "VBS"
643 | },
644 | {
645 | "id": 49,
646 | "longname": "",
647 | "mimetype": "",
648 | "patterns": [
649 | {
650 | "offset": 0,
651 | "regex": "\\x42\\x5A\\x68",
652 | "size": 3
653 | }
654 | ],
655 | "shortname": "BZip2"
656 | },
657 | {
658 | "id": 50,
659 | "longname": "",
660 | "mimetype": "",
661 | "patterns": [
662 | {
663 | "offset": 0,
664 | "regex": "\\x52\\x61\\x72\\x21\\x1A\\x07",
665 | "size": 6
666 | }
667 | ],
668 | "shortname": "RAR"
669 | },
670 | {
671 | "id": 51,
672 | "longname": "",
673 | "mimetype": "",
674 | "patterns": [
675 | {
676 | "offset": 0,
677 | "regex": "\\x57\\x69\\x6E\\x5A\\x69\\x70",
678 | "size": 6
679 | }
680 | ],
681 | "shortname": "WinZIP"
682 | },
683 | {
684 | "id": 52,
685 | "longname": "",
686 | "mimetype": "",
687 | "patterns": [
688 | {
689 | "offset": 0,
690 | "regex": "\\x75\\x73\\x74\\x61\\x72",
691 | "size": 5
692 | }
693 | ],
694 | "shortname": "TAR"
695 | },
696 | {
697 | "id": 53,
698 | "longname": "",
699 | "mimetype": "",
700 | "patterns": [
701 | {
702 | "offset": 0,
703 | "regex": "\\xCA\\xFE\\xBA\\xBE",
704 | "size": 4
705 | }
706 | ],
707 | "shortname": "Class"
708 | },
709 | {
710 | "id": 54,
711 | "longname": "",
712 | "mimetype": "",
713 | "patterns": [
714 | {
715 | "offset": 0,
716 | "regex": "\\xFF\\x4B\\x45\\x59\\x42\\x20\\x20\\x20",
717 | "size": 8
718 | }
719 | ],
720 | "shortname": "SYS Keyboard Driver"
721 | },
722 | {
723 | "id": 55,
724 | "longname": "",
725 | "mimetype": "",
726 | "patterns": [
727 | {
728 | "offset": 0,
729 | "regex": "\\xFF\\xFE\\x3C\\x00\\x3F\\x00\\x78\\x00\\x6D\\x00\\x6C",
730 | "size": 11
731 | }
732 | ],
733 | "shortname": "Windows At Job"
734 | },
735 | {
736 | "id": 56,
737 | "longname": "",
738 | "mimetype": "",
739 | "patterns": [
740 | {
741 | "offset": 0,
742 | "regex": "\\x72\\x65\\x67\\x66",
743 | "size": 4
744 | }
745 | ],
746 | "shortname": "Registry Hive"
747 | },
748 | {
749 | "id": 57,
750 | "longname": "",
751 | "mimetype": "",
752 | "patterns": [
753 | {
754 | "offset": 0,
755 | "regex": "\\x3C\\x3F\\x70\\x68\\x70",
756 | "size": 5
757 | }
758 | ],
759 | "shortname": "PHP"
760 | },
761 | {
762 | "id": 58,
763 | "longname": "",
764 | "mimetype": "",
765 | "patterns": [
766 | {
767 | "offset": 0,
768 | "regex": "\\x23\\x20\\x44\\x69\\x73\\x6B\\x20\\x44",
769 | "size": 8
770 | }
771 | ],
772 | "shortname": "VMDK"
773 | },
774 | {
775 | "id": 59,
776 | "longname": "",
777 | "mimetype": "",
778 | "patterns": [
779 | {
780 | "offset": 0,
781 | "regex": "\\x43\\x4F\\x57\\x44",
782 | "size": 4
783 | }
784 | ],
785 | "shortname": "VMDK"
786 | },
787 | {
788 | "id": 60,
789 | "longname": "",
790 | "mimetype": "",
791 | "patterns": [
792 | {
793 | "offset": 0,
794 | "regex": "\\x4B\\x44\\x4D",
795 | "size": 3
796 | }
797 | ],
798 | "shortname": "VMDK"
799 | },
800 | {
801 | "id": 61,
802 | "longname": "",
803 | "mimetype": "",
804 | "patterns": [
805 | {
806 | "offset": 0,
807 | "regex": "\\x63\\x6F\\x6E\\x65\\x63\\x74\\x69\\x78",
808 | "size": 8
809 | }
810 | ],
811 | "shortname": "VHD"
812 | },
813 | {
814 | "id": 62,
815 | "longname": "",
816 | "mimetype": "",
817 | "patterns": [
818 | {
819 | "offset": 0,
820 | "regex": "\\x41\\x45\\x53",
821 | "size": 3
822 | }
823 | ],
824 | "shortname": "AESCrypt"
825 | },
826 | {
827 | "id": 63,
828 | "longname": "",
829 | "mimetype": "",
830 | "patterns": [
831 | {
832 | "offset": 0,
833 | "regex": "\\x43\\x57\\x53",
834 | "size": 3
835 | }
836 | ],
837 | "shortname": "SWF"
838 | },
839 | {
840 | "id": 64,
841 | "longname": "",
842 | "mimetype": "",
843 | "patterns": [
844 | {
845 | "offset": 0,
846 | "regex": "\\x5A\\x57\\x53",
847 | "size": 3
848 | }
849 | ],
850 | "shortname": "SWF"
851 | },
852 | {
853 | "id": 65,
854 | "longname": "",
855 | "mimetype": "",
856 | "patterns": [
857 | {
858 | "offset": 0,
859 | "regex": "\\x47\\x49\\x46",
860 | "size": 3
861 | }
862 | ],
863 | "shortname": "GIF"
864 | },
865 | {
866 | "id": 66,
867 | "longname": "",
868 | "mimetype": "",
869 | "patterns": [
870 | {
871 | "offset": 0,
872 | "regex": "\\x3C\\x3F\\x78\\x6D\\x6C",
873 | "size": 5
874 | }
875 | ],
876 | "shortname": "XML"
877 | },
878 | {
879 | "id": 67,
880 | "longname": "",
881 | "mimetype": "",
882 | "patterns": [
883 | {
884 | "offset": 0,
885 | "regex": "\\x46\\x49\\x4C\\x45",
886 | "size": 4
887 | }
888 | ],
889 | "shortname": "NTFS MFT"
890 | },
891 | {
892 | "id": 68,
893 | "longname": "",
894 | "mimetype": "",
895 | "patterns": [
896 | {
897 | "offset": 0,
898 | "regex": "\\x4A\\x41\\x52\\x43\\x53\\x00",
899 | "size": 6
900 | }
901 | ],
902 | "shortname": "JARCS"
903 | },
904 | {
905 | "id": 69,
906 | "longname": "",
907 | "mimetype": "",
908 | "patterns": [
909 | {
910 | "offset": 0,
911 | "regex": "\\x5F\\x43\\x41\\x53\\x45\\x5F",
912 | "size": 6
913 | }
914 | ],
915 | "shortname": "Encase File"
916 | },
917 | {
918 | "id": 70,
919 | "longname": "",
920 | "mimetype": "",
921 | "patterns": [
922 | {
923 | "offset": 0,
924 | "regex": "\\x43\\x57\\x53",
925 | "size": 3
926 | }
927 | ],
928 | "shortname": "CWS"
929 | },
930 | {
931 | "id": 71,
932 | "longname": "",
933 | "mimetype": "",
934 | "patterns": [
935 | {
936 | "offset": 0,
937 | "regex": "\\x5A\\x57\\x53",
938 | "size": 3
939 | }
940 | ],
941 | "shortname": "ZWS"
942 | },
943 | {
944 | "id": 72,
945 | "longname": "",
946 | "mimetype": "",
947 | "patterns": [
948 | {
949 | "offset": 0,
950 | "regex": "\\x46\\x57\\x53",
951 | "size": 3
952 | }
953 | ],
954 | "shortname": "FWS"
955 | }
956 | ]
957 | }
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pathlib2
2 | patool
--------------------------------------------------------------------------------
/unbox.json.example:
--------------------------------------------------------------------------------
1 | {
2 | "tools":{
3 | "svn":{
4 | "executable":"svn"
5 | },
6 | "ida32":{
7 | "executable":"path_to\\idaw.exe"
8 | },
9 | "git":{
10 | "executable":"path_to\\git.exe"
11 | },
12 | "dex2jar":{
13 | "executable":"path_to\\d2j-dex2jar.bat"
14 | },
15 | "just_decompile_engine":{
16 | "executable":"path_to\\JustDecompileEngine-ReleaseQ22016SP2-default-\\ConsoleRunner\\bin\\Debug\\ConsoleRunner.exe"
17 | },
18 | "7zip":{
19 | "executable":"path_to\\7z.exe"
20 | },
21 | "jd-cli":{
22 | "executable":"path_to\\jd-cli.bat"
23 | },
24 | "ida64":{
25 | "executable":"path_to\\idaw64.exe"
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/unbox/__init__.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author :
4 |
5 | from config import load_config
6 | from handler.base import UnboxPath
7 |
8 | CONFIG = load_config("..")
9 |
10 | __all__ = []
--------------------------------------------------------------------------------
/unbox/__main__.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author :
4 |
5 | import cli
6 | import sys
7 | import logging
8 |
9 | logger = logging.getLogger("unbox")
10 |
11 | if __name__ == "__main__":
12 | logging.basicConfig(level=logging.INFO,
13 | format="[%(name)s/%(process)s][%(levelname)-10s] [%(module)s.%(funcName)-14s] %(message)s")
14 | sys.exit(cli.main()())
15 |
--------------------------------------------------------------------------------
/unbox/cli.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author :
4 |
5 | '''
6 |
7 | Decompile the Shit out of things.
8 |
9 | '''
10 |
11 | import sys
12 | import argparse
13 | import os, glob
14 | from distutils.dir_util import copy_tree
15 | import logging
16 | import handler.commands
17 | from handler.base import UnboxPath
18 |
19 | logger = logging.getLogger(__name__)
20 |
21 | def auto_prompt(s, options):
22 | q = "\n\n[i] %s" %s
23 | if options.yes:
24 | print "%s\n<--yes"%q
25 | return True
26 | elif options.no:
27 | print "%s\n<--no" % q
28 | return False
29 | yn = raw_input(q).strip()
30 | if yn=="y":
31 | return True
32 | return False
33 |
34 | def cmd_extract(options):
35 | ret = 0
36 | for fglob in glob.glob(options.args[0]):
37 | dst = UnboxPath(fglob)
38 | try:
39 | for p in dst.files.walk():
40 | print p.path
41 | if len(options.args) >= 2:
42 | if os.path.exists(options.args[1]) and \
43 | auto_prompt("Destination %s already exists. Overwrite? [y|n]" % options.args[1], options):
44 | copy_tree(str(dst.files.path), options.args[1])
45 | logger.info("moved files to %s" % options.args[1])
46 | finally:
47 | logger.debug("--cleanup--")
48 | if os.path.exists(str(dst.files.path)):
49 | logger.debug("deleting tempfolder")
50 | dst.files.unlink()
51 | ret = 1
52 | logger.info("--done--")
53 | return ret
54 |
55 |
56 | def cmd_list(options):
57 | for fglob in glob.glob(options.args[0]):
58 | dst = UnboxPath(fglob)
59 | try:
60 | for p in dst.files.walk():
61 | print p.path
62 | finally:
63 | dst.files.unlink()
64 | return 0
65 |
66 |
67 | def cmd_check(options):
68 |
69 | for name, cls in handler.commands.__dict__.iteritems():
70 | f_isAvailable = getattr(cls, "_is_available", None)
71 | f_isAvailable and f_isAvailable()
72 |
73 |
74 | COMMANDS = {
75 | 'list': cmd_list,
76 | 'extract': cmd_extract,
77 | 'check-dependencies': cmd_check,
78 | }
79 |
80 | def main():
81 | usage = """unbox.py [options]
82 | example: unbox.py [options] [, ...]
83 | options:
84 | -y, --yes ... answer prompts with yes
85 | -n, --no ... answer prompts with no
86 |
87 | command ... list
88 | ... extract
89 |
90 | ... check-dependencies
91 |
92 | target ... file
93 | """
94 | if len(sys.argv) <= 1:
95 | print "invalid command.\n"
96 | print usage
97 | return 1
98 |
99 | command = sys.argv.pop(1) # pop command arg
100 | if len(sys.argv) <= 1 and command == "check-dependencies":
101 | options = {}
102 | else:
103 | # parse the rest
104 | parser = argparse.ArgumentParser(usage=usage)
105 | parser.add_argument("-v", "--verbose",
106 | action="store_true",
107 | dest="verbose", default=False,
108 | help="verbose output")
109 | parser.add_argument("-u", "--unpack",
110 | action="store_true",
111 | dest="unpack", default=False,
112 | help="unpack/decompile file")
113 | parser.add_argument("-c", "--decompile",
114 | action="store_true",
115 | dest="decompile", default=False,
116 | help="decompile")
117 | parser.add_argument("-y", "--yes",
118 | action="store_true",
119 | dest="yes", default=False,
120 | help="answer prompts with yes")
121 | parser.add_argument("-n", "--n",
122 | action="store_true",
123 | dest="no", default=False,
124 | help="answer prompts with no")
125 | parser.add_argument("args", nargs="+")
126 |
127 | options = parser.parse_args()
128 |
129 | if options.verbose:
130 | logger.setLevel(logging.DEBUG)
131 | else:
132 | logger.setLevel(logging.INFO)
133 |
134 | logger.debug("start")
135 |
136 | f_cmd = COMMANDS.get(command.lower())
137 | if not f_cmd:
138 | print "invalid command.\n"
139 | print usage
140 | return 1
141 |
142 | return f_cmd(options)
143 |
144 | return 0
145 |
146 | if __name__=="__main__":
147 | logging.basicConfig(level=logging.DEBUG, format="[%(name)s/%(process)s][%(levelname)-10s] [%(module)s.%(funcName)-14s] %(message)s")
148 | sys.exit(main())
--------------------------------------------------------------------------------
/unbox/config.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author :
4 |
5 |
6 | from handler.utils.filesystem import get_download_dir
7 | import os
8 | import json
9 | import logging
10 |
11 | logger = logging.getLogger(__name__)
12 |
13 | def load_config(prefix=None):
14 | CONFIG_NAME = "unbox.json"
15 | home = os.path.expanduser("~")
16 | candidate_paths = [os.path.join(os.getcwd(), CONFIG_NAME),
17 | os.path.join(home, CONFIG_NAME),
18 | os.path.join(get_download_dir(), CONFIG_NAME)]
19 |
20 | if prefix:
21 | candidate_paths.insert(0, os.path.join(prefix, CONFIG_NAME))
22 |
23 | # find first matching path
24 | for p in candidate_paths:
25 | logger.debug("config: checking in %s" % p)
26 | if os.path.exists(p):
27 | break
28 | else:
29 | p = None
30 |
31 | if not p:
32 | return {}
33 | with open(p, 'r') as f:
34 | cfg = json.load(fp=f)
35 | return cfg
36 |
--------------------------------------------------------------------------------
/unbox/handler/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tintinweb/unbox/afcb1c3df5fd24e7c98bc90f88dc5239e8fd95c4/unbox/handler/__init__.py
--------------------------------------------------------------------------------
/unbox/handler/archive.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author :
4 |
5 | from local import LocalPath
6 | from utils.filesystem import TempFile
7 | import patoolib
8 | import commands
9 | import logging
10 |
11 | logger = logging.getLogger(__name__)
12 |
13 | patoolib.ArchivePrograms.update({
14 | 'crx': {
15 | 'extract': ('7z',),
16 | 'test': ('7z',),
17 | 'list': ('7z',),
18 | },
19 | })
20 |
21 |
22 | class Archive(LocalPath):
23 | def __init__(self, source, destination=None):
24 | self.uri = source
25 | if not destination:
26 | self.tmp_local_file = TempFile()
27 | self.tmp_local_file.mkdirectory()
28 | destination = self._fetch(source, str(self.tmp_local_file))
29 |
30 | source = self._fetch(source, destination)
31 | LocalPath.__init__(self, source)
32 |
33 | def _fetch(self, source, destination):
34 | commands.P7Zip.extract(source, destination)
35 | # cmd = [Config.PATH_7ZIP, 'x', '-o%s' % destination, source]
36 | # logger.debug(cmd)
37 | # ret = subprocess.call(cmd)
38 | # if ret != 0:
39 | # raise Exception("command failed")
40 | return destination
41 |
42 |
43 | class ArchivePatool(LocalPath):
44 | def __init__(self, source, destination=None):
45 | self.uri = source
46 | destination = destination or self.mkdtemp()
47 | source = self._fetch(source, destination)
48 | LocalPath.__init__(self, source)
49 |
50 | def _fetch(self, source, destination, verbosity=-1, interactive=True):
51 | patoolib.extract_archive(source, verbosity=verbosity,
52 | interactive=interactive,
53 | outdir=destination)
54 | return destination
55 |
56 |
57 | class ChromeExtensionCrx(ArchivePatool):
58 | pass # just an ordinary zip archive
59 |
60 | class FirefoxExtensionXpi(ArchivePatool):
61 | pass # just an ordinary zip archive
--------------------------------------------------------------------------------
/unbox/handler/base.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author :
4 |
5 |
6 |
7 | import local, remote, archive, decompilable
8 | from utils.fileformat import PeFileFormat
9 | import urlparse
10 | import os
11 | from cigma.cigma import Cigma
12 |
13 |
14 | import logging
15 |
16 | logger = logging.getLogger(__name__)
17 |
18 |
19 | class UnboxPath(object):
20 |
21 | def __init__(self, source):
22 | self.source = source
23 | self._files = None
24 |
25 | @property
26 | def files(self):
27 | self._files = self._files or UnboxPath.get_path(self.source)
28 | return self._files
29 |
30 | @staticmethod
31 | def get_path(source):
32 | uri = urlparse.urlparse(source)
33 |
34 | if uri.scheme and uri.path.endswith(".git"):
35 | po = remote.GitRepo(source)
36 | elif uri.scheme.startswith("svn"):
37 | po = remote.SvnRepo(source)
38 | elif uri.scheme in ("http", "https", "ftp"):
39 | po = remote.Web(source)
40 | elif os.path.isfile(source):
41 | if any(source.endswith(ext) for ext in ('.zip', '.gz', '.tar')):
42 | po = archive.Archive(source)
43 | elif source.endswith('.crx'):
44 | po = archive.ChromeExtensionCrx(source)
45 | elif source.endswith('.xpi'):
46 | po = archive.FirefoxExtensionXpi(source)
47 | elif source.endswith('.apk'):
48 | po = decompilable.Apk(source)
49 | elif source.endswith('.jar'):
50 | po = decompilable.Jar(source)
51 | else:
52 | # we do not know what is is
53 | logger.debug("unknown: %s" % source)
54 | c = Cigma()
55 | try:
56 | with open(source, 'rb') as f:
57 | data = f.read(384)
58 | magic = c.cigma(data=data)
59 | logger.debug(magic)
60 | d_magic = magic["magic"]
61 | if not d_magic:
62 | po = local.LocalPath(source)
63 | else:
64 | mimetype = d_magic.get('mimetype', "")
65 | if mimetype.startswith("application/x-executable-32"):
66 | po = decompilable.Application32Bits(source)
67 | elif mimetype.startswith("application/x-executable-64"):
68 | po = decompilable.Application64Bits(source)
69 | elif mimetype.startswith("application/"):
70 | petype = PeFileFormat.petype(data)
71 | logger.debug(petype)
72 | if petype == PeFileFormat.TYPE_PE64:
73 | po = decompilable.Application64Bits(source)
74 | elif petype == PeFileFormat.TYPE_DOTNET:
75 | po = decompilable.ApplicationDotNet(source)
76 | else:
77 | po = decompilable.Application32Bits(source)
78 | else:
79 | po = local.LocalPath(source)
80 | except Exception as e:
81 | logger.exception("exception!")
82 | po = local.LocalPath(source)
83 | elif os.path.isdir(source):
84 | po = local.LocalPath(source)
85 |
86 | logger.debug("scheme: %s" % uri.scheme)
87 | logger.debug(po)
88 | return po
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
--------------------------------------------------------------------------------
/unbox/handler/commands/__init__.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author :
4 |
5 | from commands import *
6 |
--------------------------------------------------------------------------------
/unbox/handler/commands/commands.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author :
4 |
5 | from unbox import config
6 | import subprocess
7 | import os
8 | import hashlib
9 | import logging
10 |
11 |
12 | logger = logging.getLogger(__name__)
13 |
14 | CONFIG = config.load_config()
15 |
16 | from ..utils.shell import Shell
17 | from ..utils.web import download_file
18 | from ..utils.filesystem import get_download_dir
19 |
20 |
21 | class Git:
22 | @staticmethod
23 | def _is_available():
24 | '''
25 | Download missing parts or provide instructions on how to do so
26 | :return:
27 | '''
28 | if not Shell.test(Git._get_command()):
29 | print "=" * 30
30 | print "= Please install the >git< command line tools and add them to the PATH variable or configure the specific path in unbox.cfg.json "
31 | print "=" * 30
32 | return False
33 | return True
34 |
35 | @staticmethod
36 | def _get_command():
37 | cmd = CONFIG.get("tools",{}).get("git",{}).get("executable","git")
38 | return cmd
39 |
40 | @staticmethod
41 | def clone(source, destination, args=[]):
42 | cmd = [Git._get_command(), 'clone'] + args + [source, destination]
43 | return Shell.execute(cmd)
44 |
45 |
46 | class Svn:
47 | @staticmethod
48 | def _is_available():
49 | '''
50 | Download missing parts or provide instructions on how to do so
51 | :return:
52 | '''
53 | if not Shell.test(Svn._get_command()):
54 | print "=" * 30
55 | print "= Please install the >svn< command line tools and add them to the PATH variable or configure the specific path in unbox.cfg.json "
56 | print "=" * 30
57 | return False
58 | return True
59 |
60 | @staticmethod
61 | def _get_command():
62 | cmd = CONFIG.get("tools", {}).get("svn", {}).get("executable", "svn")
63 | return cmd
64 |
65 | @staticmethod
66 | def export(source, destination):
67 | cmd = [Svn._get_command(), 'export', source, destination]
68 | return Shell.execute(cmd)
69 |
70 |
71 | class P7Zip:
72 | """
73 | @title: 7zip archiver
74 | @ref: http://www.7-zip.org/
75 | """
76 |
77 | @staticmethod
78 | def _is_available():
79 | '''
80 | Download missing parts or provide instructions on how to do so
81 | :return:
82 | '''
83 | if not Shell.test(P7Zip._get_command()):
84 | print "=" * 30
85 | print "= Please install the >7zip< command line tools and add them to the PATH variable or configure the specific path in unbox.cfg.json "
86 | print "=" * 30
87 | return False
88 | return True
89 |
90 | @staticmethod
91 | def _get_command():
92 | cmd = CONFIG.get("tools", {}).get("7zip", {}).get("executable", "7z")
93 | return cmd
94 |
95 | @staticmethod
96 | def extract(source, destination):
97 | cmd = [P7Zip._get_command(), 'x', '-o%s' % destination, source]
98 | return Shell.execute(cmd)
99 |
100 |
101 | class JdCli:
102 | """
103 | @title: Command line Java Decompiler
104 | @ref: https://github.com/kwart/jd-cmd
105 | """
106 |
107 | @staticmethod
108 | def _is_available():
109 | '''
110 | Download missing parts or provide instructions on how to do so
111 | :return:
112 | '''
113 | if not Shell.test(JdCli._get_command()):
114 | print "=" * 30
115 | print "= Please install the >jd-cli< command line tools and add them to the PATH variable or configure the specific path in unbox.cfg.json "
116 | print "=" * 30
117 | return False
118 | return True
119 |
120 | @staticmethod
121 | def _get_command():
122 | cmd = CONFIG.get("tools", {}).get("jd-cli", {}).get("executable", "jd-cli")
123 | return cmd
124 |
125 | @staticmethod
126 | def decompile(source, destination):
127 | cmd = [JdCli._get_command(), '--outputDir', destination, source]
128 | return Shell.execute(cmd)
129 |
130 |
131 | class Dex2Jar:
132 | """
133 | @title: dextools dex2jar
134 | @ref: https://github.com/pxb1988/dex2jar
135 | """
136 |
137 | @staticmethod
138 | def _is_available():
139 | '''
140 | Download missing parts or provide instructions on how to do so
141 | :return:
142 | '''
143 | if not Shell.test(Dex2Jar._get_command()):
144 | print "=" * 30
145 | print "= Please install the >dex2jar< command line tools and add them to the PATH variable or configure the specific path in unbox.cfg.json "
146 | print "=" * 30
147 | return False
148 | return True
149 |
150 | @staticmethod
151 | def _get_command():
152 | cmd = CONFIG.get("tools", {}).get("dex2jar", {}).get("executable", "d2j-dex2jar")
153 | return cmd
154 |
155 | @staticmethod
156 | def decompile(source, destination):
157 | cmd = [Dex2Jar._get_command(), '-o', destination, source]
158 | return Shell.execute(cmd)
159 |
160 |
161 | class JustDecompileDotNet:
162 | """
163 | @title: The decompilation engine of JustDecompile http://www.telerik.com/products/decompiler.aspx
164 | @ref: https://github.com/telerik/JustDecompileEngine
165 | """
166 |
167 | @staticmethod
168 | def _is_available():
169 | '''
170 | Download missing parts or provide instructions on how to do so
171 | :return:
172 | '''
173 | if not Shell.test(JustDecompileDotNet._get_command()):
174 | print "=" * 30
175 | print "= Please install the >JustDecompileDotNet< command line tools and add them to the PATH variable or configure the specific path in unbox.cfg.json "
176 | print "=" * 30
177 | return False
178 | return True
179 |
180 | @staticmethod
181 | def _get_command():
182 | cmd = CONFIG.get("tools", {}).get("just_decompile_engine", {}).get("executable")
183 | return cmd
184 |
185 | @staticmethod
186 | def decompile(source, destination):
187 | cmd = [JustDecompileDotNet._get_command(), '/out:%s' % destination, '/target:%s' % source]
188 | return Shell.execute(cmd)
189 |
190 |
191 | class Ida32:
192 | """
193 | @title: Hex-Ray's IDA x64 batch decompiler
194 | @ref: https://github.com/tintinweb/ida-batch_decompile
195 | """
196 | SUPPORT_SCRIPT = ("https://raw.githubusercontent.com/tintinweb/ida-batch_decompile/v0.1/ida_batch_decompile.py",
197 | "SHA-1",
198 | "694ae11e3502bc0d017c194b0f54fd377c0276d3")
199 |
200 |
201 | @staticmethod
202 | def _is_available():
203 | '''
204 | Download missing parts or provide instructions on how to do so
205 | :return:
206 | '''
207 | if not Shell.test(Ida32._get_command()):
208 | print "=" * 30
209 | print "= Please install the >IDA Pro including Hexrays Decompiler< command line tools and add them to the PATH variable or configure the specific path in unbox.cfg.json "
210 | print "=" * 30
211 | return False
212 |
213 | if not os.path.exists(os.path.join(get_download_dir(), "ida_batch_decompile.py")):
214 | yn = raw_input("Download '%s'? [y|n]" % Ida32.SUPPORT_SCRIPT[0])
215 | if yn.strip() == "n":
216 | return False
217 | dl = Ida32.SUPPORT_SCRIPT[0]
218 | file = download_file(dl, get_download_dir())
219 | else:
220 | file = os.path.join(get_download_dir(), "ida_batch_decompile.py")
221 | with open(file, 'rb') as f:
222 | this_hash = hashlib.sha1()
223 | this_hash.update(f.read())
224 | if not Ida32.SUPPORT_SCRIPT[2] == this_hash.hexdigest():
225 | raise Exception("Checksum Failed for ida_batch_decompile.py!")
226 | #raise Exception("requests download file")
227 |
228 | return True
229 |
230 | @staticmethod
231 | def _get_command():
232 | cmd = CONFIG.get("tools", {}).get("ida32", {}).get("executable","idaw")
233 | return cmd
234 |
235 | @staticmethod
236 | def decompile(source, destination):
237 | idascript = os.path.abspath(os.path.join(get_download_dir(), "ida_batch_decompile.py"))
238 | destination_file = os.path.join(destination, os.path.split(source)[1].rsplit(".", 1)[0] + '.c')
239 |
240 | decompile_script_cmd = '%s -o\\"%s\\"' % (idascript, destination_file)
241 | cmd = [Ida32._get_command(), '-B', '-M', '-S"%s"' % decompile_script_cmd, '"' + source + '"']
242 | logger.debug(cmd)
243 | ret = subprocess.call(' '.join(cmd), shell=True)
244 | # ret = subprocess.call(cmd, shell=True)
245 | # subprocess.call()
246 | if ret != 0:
247 | raise Exception("command failed: %s" % ret)
248 | return destination
249 |
250 |
251 | class Ida64:
252 | """
253 | @title: Hex-Ray's IDA x64 batch decompiler
254 | @ref: https://github.com/tintinweb/ida-batch_decompile
255 | """
256 |
257 | @staticmethod
258 | def _is_available():
259 | '''
260 | Download missing parts or provide instructions on how to do so
261 | :return:
262 | '''
263 | if not Shell.test(Ida64._get_command()):
264 | print "=" * 30
265 | print "= Please install the >IDA Pro including Hexrays Decompiler< command line tools and add them to the PATH variable or configure the specific path in unbox.cfg.json "
266 | print "=" * 30
267 | return False
268 |
269 | if not os.path.exists(os.path.join(get_download_dir(), "ida_batch_decompile.py")):
270 | yn = raw_input("Download '%s'? [y|n]" % Ida32.SUPPORT_SCRIPT[0])
271 | if yn.strip() == "n":
272 | return False
273 | dl = Ida32.SUPPORT_SCRIPT[0]
274 | file = download_file(dl, get_download_dir())
275 | else:
276 | file = os.path.join(get_download_dir(), "ida_batch_decompile.py")
277 | with open(file, 'rb') as f:
278 | this_hash = hashlib.sha1()
279 | this_hash.update(f.read())
280 | if not Ida32.SUPPORT_SCRIPT[2] == this_hash.hexdigest():
281 | raise Exception("Checksum Failed for ida_batch_decompile.py!")
282 | #raise Exception("requests download file")
283 |
284 | return True
285 |
286 | @staticmethod
287 | def _get_command():
288 | cmd = CONFIG.get("tools", {}).get("ida64", {}).get("executable", "idaw64")
289 | return cmd
290 |
291 | @staticmethod
292 | def decompile(source, destination):
293 | idascript = os.path.abspath(os.path.join(get_download_dir(), "ida_batch_decompile.py"))
294 | destination_file = os.path.join(destination, os.path.split(source)[1].rsplit(".", 1)[0] + '.c')
295 |
296 | decompile_script_cmd = '%s -o\\"%s\\"' % (idascript, destination_file)
297 | cmd = [Ida64._get_command(), '-B', '-M', '-S"%s"' % decompile_script_cmd, '"' + source + '"']
298 | logger.debug(cmd)
299 | ret = subprocess.call(' '.join(cmd), shell=True)
300 | # ret = subprocess.call(cmd, shell=True)
301 | # subprocess.call()
302 | if ret != 0:
303 | raise Exception("command failed: %s" % ret)
304 | return destination
305 |
306 |
307 | class RetDec:
308 | """
309 | @title: RetDec is a retargetable machine-code decompiler based on LLVM. https://retdec.com/
310 | @ref: # https://github.com/avast-tl/retdec
311 | """
312 |
313 | @staticmethod
314 | def _is_available():
315 | '''
316 | Download missing parts or provide instructions on how to do so
317 | :return:
318 | '''
319 | if not Shell.test(RetDec._get_command()):
320 | print "=" * 30
321 | print "= Please install the >RETDEC< command line tools and add them to the PATH variable or configure the specific path in unbox.cfg.json "
322 | print "=" * 30
323 | return False
324 |
325 | return True
326 |
327 | @staticmethod
328 | def _get_command():
329 | cmd = CONFIG.get("tools", {}).get("retdec", {}).get("executable", "retdec")
330 | return cmd
331 |
332 | @staticmethod
333 | def decompile(source, destination):
334 | pass
335 |
336 |
337 | class Porosity:
338 | """
339 | @title: Decompiler and Security Analysis tool for Blockchain-based Ethereum Smart-Contracts https://www.comae.io
340 | @ref: # https://github.com/comaeio/porosity
341 | """
342 |
343 | @staticmethod
344 | def _is_available():
345 | '''
346 | Download missing parts or provide instructions on how to do so
347 | :return:
348 | '''
349 | if not Shell.test(Porosity._get_command()):
350 | print "=" * 30
351 | print "= Please install the >Porosity< command line tools and add them to the PATH variable or configure the specific path in unbox.cfg.json "
352 | print "=" * 30
353 | return False
354 |
355 | return True
356 |
357 | @staticmethod
358 | def _get_command():
359 | cmd = CONFIG.get("tools", {}).get("porosity", {}).get("executable", "porosity")
360 | return cmd
361 |
362 | @staticmethod
363 | def decompile(source, destination):
364 | # porosity --abi $abi --code $code --decompile --verbose 0 > output.sol
365 | pass
366 |
367 |
--------------------------------------------------------------------------------
/unbox/handler/decompilable.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author :
4 |
5 | from local import LocalPath
6 | from archive import ArchivePatool
7 | Archive = ArchivePatool # lets use PaTool
8 | import os
9 | import commands
10 | from utils.filesystem import TempFile
11 | import logging
12 |
13 | logger = logging.getLogger(__name__)
14 |
15 |
16 | class Jar(LocalPath):
17 | def __init__(self, source, destination=None):
18 | self.uri = source
19 | if not destination:
20 | self.tmp_local_file = TempFile()
21 | self.tmp_local_file.mkdirectory()
22 | destination = str(self.tmp_local_file)
23 |
24 | source = self._fetch(source, destination)
25 | LocalPath.__init__(self, source)
26 |
27 | def _fetch(self, source, destination):
28 | commands.JdCli.decompile(source, destination)
29 | # cmd = [Config.PATH_JAR2SRC, '--outputDir', destination, source]
30 | # logger.debug(cmd)
31 | # ret = subprocess.call(cmd)
32 | # if ret != 0:
33 | # raise Exception("command failed")
34 | return destination
35 |
36 |
37 | class ApplicationDotNet(LocalPath):
38 | def __init__(self, source, destination=None):
39 | self.uri = source
40 | if not destination:
41 | self.tmp_local_file = TempFile()
42 | self.tmp_local_file.mkdirectory()
43 | destination = str(self.tmp_local_file)
44 |
45 | source = self._fetch(source, destination)
46 | LocalPath.__init__(self, source)
47 |
48 | def _fetch(self, source, destination):
49 | commands.JustDecompileDotNet.decompile(source, destination)
50 | return destination
51 |
52 |
53 | class Apk(LocalPath):
54 | def __init__(self, source):
55 | self.uri = source
56 | self.tmp_local_file = TempFile()
57 | self.tmp_local_file.mkdirectory()
58 |
59 | source = self._fetch(source, str(self.tmp_local_file))
60 | LocalPath.__init__(self, source)
61 |
62 | def _fetch(self, source, destination):
63 | '''
64 | 1) create tempfolder
65 | 2) unpack .apk to tempfolder .apk
66 | 3) convert .apk to tempfolder .jar
67 | 4) decompile .jar to tempfolder .java
68 |
69 | dex2jar -o
70 |
71 | '''
72 | path, fname = os.path.split(source)
73 |
74 | destination_jar = os.path.join(destination, fname + ".jar")
75 | logger.debug("destination: %s" % destination_jar)
76 | # 1) convert .apk to .jar
77 | commands.Dex2Jar.decompile(source, destination_jar)
78 | # cmd = [Config.PATH_DEX2JAR, '-o', destination_jar, source]
79 | # logger.debug(cmd)
80 | # ret = subprocess.call(cmd)
81 | # if ret != 0:
82 | # raise Exception("command failed")
83 |
84 | # 2) unpack .apk
85 | destination_dir_apk = os.path.join(destination, '.apk')
86 | os.makedirs(destination_dir_apk)
87 | logger.debug("unpack .apk to %s" % destination_dir_apk)
88 | apk_unpacked = Archive(source, destination_dir_apk)
89 | # 3) decompile .jar
90 | destination_dir_source = os.path.join(destination, '.source')
91 | os.makedirs(destination_dir_source)
92 | logger.debug("decompile .jar to %s" % destination_dir_source)
93 | jar_decompiled = Jar(destination_jar, destination_dir_source)
94 |
95 | logger.debug("remove .jar - we do not need it anymore")
96 | os.unlink(destination_jar)
97 | return destination
98 |
99 |
100 | class Application32Bits(LocalPath): # ida32
101 | # https://www.hex-rays.com/products/ida/support/idadoc/417.shtml
102 | """
103 | https://www.hex-rays.com/products/ida/support/idadoc/417.shtml
104 |
105 | idc.wait()
106 | idaapi.decompile_many(outfile, None, flags=0xffffffff)
107 |
108 | see idaallthethings
109 | + https://www.hex-rays.com/products/ida/support/idadoc/417.shtml
110 | 1) get os type (windows,linux) (idaw vs idal)
111 | 2) idaw -B -S"myscript.idc argument1 \"argument 2\" argument3"
112 |
113 | idaw|idal -B -S"ida-allthethings.py" "C:\_tmp\telnet.exe"
114 |
115 | https://www.hex-rays.com/products/decompiler/manual/batch.shtml
116 | """
117 |
118 | def __init__(self, source):
119 | self.uri = source
120 | self.tmp_local_file = TempFile()
121 | self.tmp_local_file.mkdirectory()
122 |
123 | source = self._fetch(source, str(self.tmp_local_file))
124 | LocalPath.__init__(self, source)
125 |
126 | def _fetch(self, source, destination, branch=None):
127 | commands.Ida32.decompile(source, destination)
128 | '''
129 | idascript = os.path.abspath(r'ida-allthethings.py')
130 | print (destination)
131 | destination_file = os.path.join(destination, os.path.split(source)[1].rsplit(".", 1)[0] + '.c')
132 |
133 | decompile_script_cmd = '%s \\"%s\\"' % (idascript, destination_file)
134 | cmd = [Config.PATH_IDA32, '-B', '-M', '-S"%s"' % decompile_script_cmd, '"' + source + '"']
135 | logger.debug(cmd)
136 | print (' '.join(cmd))
137 | ret = subprocess.call(' '.join(cmd), shell=True)
138 | # ret = subprocess.call(cmd, shell=True)
139 | # subprocess.call()
140 | if ret != 0:
141 | raise Exception("command failed: %s" % ret)
142 | '''
143 | return destination
144 |
145 |
146 | class Application64Bits(LocalPath):
147 | def __init__(self, source):
148 | self.uri = source
149 | self.tmp_local_file = TempFile()
150 | self.tmp_local_file.mkdirectory()
151 |
152 | source = self._fetch(source, str(self.tmp_local_file))
153 | LocalPath.__init__(self, source)
154 |
155 | def _fetch(self, source, destination, branch=None):
156 | commands.Ida64.decompile(source, destination)
157 | return destination
158 |
159 | class SoliditySmartContract(LocalPath):
160 | def __init__(self, source):
161 | self.uri = source
162 | self.tmp_local_file = TempFile()
163 | self.tmp_local_file.mkdirectory()
164 |
165 | source = self._fetch(source, str(self.tmp_local_file))
166 | LocalPath.__init__(self, source)
167 |
168 | def _fetch(self, source, destination, branch=None):
169 | commands.Porosity.decompile(source, destination)
170 | return destination
171 |
--------------------------------------------------------------------------------
/unbox/handler/local.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author :
4 |
5 | from utils.filesystem import TempFile
6 | import base
7 | import pathlib2
8 | import codecs, chardet
9 | import os
10 | import shutil
11 | import re
12 | import logging
13 |
14 | logger = logging.getLogger(__name__)
15 |
16 |
17 | class LocalPath(object):
18 | def __init__(self, source):
19 | self.encoding = None
20 | self.fd = None
21 | self.source = source
22 | self.path = pathlib2.Path(source)
23 | self.tmp = TempFile()
24 |
25 | def __repr__(self):
26 | return "<%s encoding=%r path=%r>"% (self.__class__.__name__, self.encoding, self.path)
27 |
28 | def open(self):
29 | ''' open file from fs
30 | '''
31 | self.fd = codecs.open(str(self.path.absolute()), mode='r')
32 | # probe for encoding
33 | self.encoding = chardet.detect(self.fd.read(512))
34 | self.fd.seek(0) # rewind
35 | return self.fd
36 |
37 | def close(self):
38 | if self.fd:
39 | self.fd.close()
40 |
41 | def read(self):
42 | return self.fd.read()
43 |
44 | def walk(self, exclude_rex=[re.compile(r'.*/.git.*'), ], include_rex=[]):
45 | logger.debug("walk: %s"%self.path.absolute())
46 | for root, _, files in os.walk(str(self.path.absolute())):
47 | for filename in files:
48 | abspath = os.path.join(root, filename)
49 | normalized_abspath = abspath.replace("\\", '//')
50 | if not any(regex.match(normalized_abspath) for regex in include_rex):
51 | # if we do not want to force inclusion, check exclusion list
52 | if any(regex.match(normalized_abspath) for regex in exclude_rex):
53 | continue
54 | gp = base.UnboxPath.get_path(abspath)
55 | if gp.path.is_file():
56 | yield gp
57 | elif gp.path.is_dir():
58 | # recurse into subpath
59 | for sub_f in gp.walk():
60 | yield sub_f
61 |
62 | def remove(self):
63 | def shutil_errorhandler(function, path, excinfo):
64 | logger.error("could not remove path: %s (%r) (%r)" % (path, function, excinfo))
65 |
66 | self.close()
67 | if self.path.is_dir():
68 | shutil.rmtree(str(self.path.absolute()), ignore_errors=False, onerror=shutil_errorhandler)
69 | else:
70 | self.path.unlink()
71 |
72 | def unlink(self):
73 | self.remove()
--------------------------------------------------------------------------------
/unbox/handler/remote.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author :
4 |
5 |
6 | import os
7 | import tempfile
8 | import commands
9 | import urllib
10 |
11 | import logging
12 |
13 | logger = logging.getLogger(__name__)
14 |
15 | from local import LocalPath
16 | import base
17 | from utils.filesystem import TempFile
18 |
19 | class GitRepo(LocalPath):
20 |
21 | def __init__(self, source):
22 | self.uri = source
23 |
24 | self.tmp_local_file = TempFile()
25 | self.tmp_local_file.mkdirectory()
26 | source = self._fetch(source, str(self.tmp_local_file))
27 |
28 | LocalPath.__init__(self, source)
29 |
30 | def _fetch(self, source, destination, branch=None):
31 | ret = commands.Git.clone(source, destination, args=["--recursive"])
32 | # cmd = [Config.PATH_GIT, 'clone', '--recursive', source, destination]
33 | # ret = subprocess.call(cmd)
34 | # if ret != 0:
35 | # raise Exception("command failed")
36 | return destination
37 |
38 |
39 | class SvnRepo(LocalPath):
40 | def __init__(self, source):
41 | self.uri = source
42 |
43 | self.tmp_local_file = TempFile()
44 | self.tmp_local_file.mkdirectory()
45 | source = self._fetch(source, str(self.tmp_local_file))
46 |
47 | LocalPath.__init__(self, source)
48 |
49 | def _fetch(self, source, destination, branch=None):
50 | commands.Svn.export(source, destination)
51 | # cmd = [Config.PATH_SVN, 'export', source, destination]
52 | # ret = subprocess.call(cmd)
53 | # if ret != 0:
54 | # raise Exception("command failed")
55 | return destination
56 |
57 |
58 | class Web(LocalPath):
59 |
60 | def __init__(self, source):
61 | self.uri = source
62 | self.tmp_local_file = TempFile()
63 | self.tmp_local_file.mkfile(suffix='.' + source.rsplit('.', 1)[1])
64 | source = self._fetch(source, str(self.tmp_local_file))
65 | source = base.UnboxPath.get_path(source)
66 | LocalPath.__init__(self, source.path.absolute())
67 |
68 | def _fetch(self, source, destination):
69 | destination, _ = urllib.urlretrieve(source, destination)
70 | return destination
--------------------------------------------------------------------------------
/unbox/handler/utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tintinweb/unbox/afcb1c3df5fd24e7c98bc90f88dc5239e8fd95c4/unbox/handler/utils/__init__.py
--------------------------------------------------------------------------------
/unbox/handler/utils/fileformat.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author :
4 |
5 |
6 | import struct
7 |
8 | class PeFileFormat:
9 | TYPE_MZ = 1
10 | TYPE_PE32 = 2
11 | TYPE_PE64 = 3
12 | TYPE_DOTNET = 4
13 |
14 | @staticmethod
15 | def petype(data):
16 | #
17 | # MZ header size == 0x40
18 | # PE Header location at MZ[0x3c] is at least 0x33 long
19 | if not (len(data) > 0x40 and data[0:2] == "MZ"):
20 | # not MZ
21 | return None
22 |
23 | t = PeFileFormat.TYPE_MZ
24 |
25 | offset = struct.unpack('I', data[0x3c:0x3c + 4])[0]
26 | if not (len(data) > offset + 0x33 and data[offset:offset + 4] == 'PE\0\0'):
27 | # MZ
28 | return t
29 |
30 | arch = data[offset + 0x18 + 1]
31 | if arch == '\x01':
32 | t = PeFileFormat.TYPE_PE32
33 | elif arch == '\x02':
34 | t = PeFileFormat.TYPE_PE64
35 | else:
36 | return t
37 | '''
38 | /*
39 | Now we are at the end of the PE Header and from here, the
40 | PE Optional Headers starts...
41 | To go directly to the datadictionary, we'll increase the
42 | stream’s current position to with 96 (0x60). 96 because,
43 | 28 for Standard fields
44 | 68 for NT-specific fields
45 | From here DataDictionary starts...and its of total 128 bytes. DataDictionay has 16 directories in total,
46 | doing simple maths 128/16 = 8.
47 | So each directory is of 8 bytes.
48 | In this 8 bytes, 4 bytes is of RVA and 4 bytes of Size.
49 |
50 | btw, the 15th directory consist of CLR header! if its 0, its not a CLR file :)
51 | */'''
52 |
53 | if not len(data) >= offset + 0x78 + 4:
54 | return t
55 | # datadir start
56 | datadir_offset = offset + 0x78
57 | # last datadir
58 | if not len(data) >= 8 * 14 + datadir_offset + 8:
59 | return t
60 | # check last datadir: http://geekswithblogs.net/rupreet/archive/2005/11/02/58873.aspx
61 | datadir_rva, datdir_size = struct.unpack('II', data[8 * 14 + datadir_offset:8 * 14 + datadir_offset + 8])
62 | if datadir_rva != 0x00:
63 | t = PeFileFormat.TYPE_DOTNET
64 | # PE
65 | return t
66 |
--------------------------------------------------------------------------------
/unbox/handler/utils/filesystem.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author :
4 |
5 | import pathlib2
6 | import tempfile
7 | import os, shutil
8 | import logging
9 |
10 | logger = logging.getLogger(__name__)
11 |
12 |
13 | class TempFile(object):
14 |
15 | def __init__(self):
16 | self.tmp = None
17 |
18 | def __str__(self):
19 | return str(self.tmp)
20 |
21 | def __repr__(self):
22 | return repr(self.tmp)
23 |
24 | def mkdirectory(self, prefix="unbox", force=False):
25 | if self.tmp and not force:
26 | return self.tmp
27 | self.tmp = pathlib2.Path(tempfile.mkdtemp(prefix=prefix))
28 | return self.tmp
29 |
30 | def mkfile(self, prefix="", suffix="None", force=False):
31 | if self.tmp and not force:
32 | return self.tmp
33 |
34 | _, tempname = tempfile.mkstemp(suffix=suffix, prefix=prefix)
35 | os.close(_) # close the fd, we only want that name
36 |
37 | self.tmp = pathlib2.Path(tempname)
38 | return self.tmp
39 |
40 | def remove(self):
41 | def shutil_errorhandler(function, path, excinfo):
42 | logger.error("could not remove path: %s (%r) (%r)" % (path, function, excinfo))
43 |
44 | if self.tmp:
45 | shutil.rmtree(str(self.tmp.absolute()), ignore_errors=False, onerror=shutil_errorhandler)
46 |
47 |
48 | def get_download_dir():
49 | return os.path.join(os.path.expanduser("~"), ".unbox")
--------------------------------------------------------------------------------
/unbox/handler/utils/shell.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author :
4 |
5 | import subprocess
6 | import platform
7 | import os
8 | import logging
9 |
10 | logger = logging.getLogger(__name__)
11 |
12 |
13 | class Shell:
14 |
15 | @staticmethod
16 | def test(cmd):
17 | if os.path.isfile(cmd):
18 | # just return true if it is a file ;)
19 | return True
20 | ret = subprocess.call(["where" if platform.system() == "Windows" else "which", cmd])
21 | logger.debug("testing for command %s returned %s" % (cmd, ret))
22 | return True if ret in (0, ) else False
23 |
24 | @staticmethod
25 | def execute(cmd):
26 | logger.debug(cmd)
27 | ret = subprocess.call(cmd)
28 | if ret != 0:
29 | raise Exception("command failed")
30 | return ret
--------------------------------------------------------------------------------
/unbox/handler/utils/web.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import os
3 |
4 | def download_file(url, destination):
5 | local_filename = os.path.join(destination, url.split('/')[-1])
6 | # NOTE the stream=True parameter
7 | r = requests.get(url, stream=True)
8 | if not os.path.exists(destination):
9 | os.mkdir(destination)
10 | with open(local_filename, 'wb') as f:
11 | for chunk in r.iter_content(chunk_size=1024):
12 | if chunk: # filter out keep-alive new chunks
13 | f.write(chunk)
14 | #f.flush() commented by recommendation from J.F.Sebastian
15 | return local_filename
--------------------------------------------------------------------------------