class RegistryServer(cli.Application):
    mode = cli.SwitchAttr(["-m", "--mode"], cli.Set("UDP", "TCP"), default="UDP",
                          help="Serving mode")

    ipv6 = cli.Flag(["-6", "--ipv6"], help="use ipv6 instead of ipv4")

    port = cli.SwitchAttr(["-p", "--port"], cli.Range(0, 65535), default=REGISTRY_PORT,
                          help="The UDP/TCP listener port")

    logfile = cli.SwitchAttr(["--logfile"], str, default=None,
                             help="The log file to use; the default is stderr")

    quiet = cli.SwitchAttr(["-q", "--quiet"], help="Quiet mode (only errors are logged)")

    pruning_timeout = cli.SwitchAttr(["-t", "--timeout"], int,
                                     default=DEFAULT_PRUNING_TIMEOUT, help="Set a custom pruning timeout (in seconds)")

    def main(self):
        if self.mode == "UDP":
            server = UDPRegistryServer(host='::' if self.ipv6 else '0.0.0.0', port=self.port,
                                       pruning_timeout=self.pruning_timeout)
        elif self.mode == "TCP":
            server = TCPRegistryServer(port=self.port, pruning_timeout=self.pruning_timeout)
        setup_logger(self.quiet, self.logfile)
        server.start()
Exemple #2
0
class ServidorTest(cli.Application):
    verbose = cli.Flag("-v", help="Arrancar el servidor en Verbose mode")
    port = 8080  # Puerto por defecto
    mode = "TCP"  #Protocolo de red por defecto
    type = "HTTP"

    @cli.switch(["-p", "--port"], cli.Range(1024,
                                            65535))  #Puerto entre 1024 y 65535
    def server_port(self, port):
        self.port = port

    @cli.switch(["-m", "--mode"],
                cli.Set("TCP", "UDP",
                        case_sensitive=False))  #Protocolo de red (TCP o UDP)
    def server_mode(self, mode):
        self.mode = mode

    @cli.switch(["-t", "--type"], cli.Set("HTTP",
                                          "HTTPS",
                                          case_sensitive=False))
    def server_type(self, type):
        self.type = type

    def main(self):
        print self.port, self.mode, self.type, self.verbose
Exemple #3
0
class ServidorTest(cli.Application):
    verbose = cli.Flag("-v", help="Arrancar el servidor en Verbose mode")
    port = 8080  # Default port
    mode = "TCP"  #Default network protocol
    type = "HTTP"

    @cli.switch(["-p", "--port"],
                cli.Range(1024, 65535))  #Port between 1024 and 65535
    def server_port(self, port):
        self.port = port

    @cli.switch(["-m", "--mode"],
                cli.Set("TCP", "UDP",
                        case_sensitive=False))  #Network protocol (TCP or UDP)
    def server_mode(self, mode):
        self.mode = mode

    @cli.switch(["-t", "--type"], cli.Set("HTTP",
                                          "HTTPS",
                                          case_sensitive=False))
    def server_type(self, type):
        self.type = type

    def main(self):
        print self.port, self.mode, self.type, self.verbose
Exemple #4
0
class ShowImageApp(cli.Application):
    'Display an image on the terminal'
    double = cli.Flag(
        ['-d', '--double'],
        help="Double resolution (only looks good with some fonts)")

    @cli.switch(['-c', '--colors'],
                cli.Range(1, 4),
                help="Level of color, 1-4")
    def colors_set(self, n):
        colors.use_color = n

    size = cli.SwitchAttr(['-s', '--size'],
                          help="Size, should be in the form 100x150")

    ratio = cli.SwitchAttr(['--ratio'],
                           float,
                           default=2.45,
                           help="Aspect ratio of the font")

    @cli.positional(cli.ExistingFile)
    def main(self, filename):

        size = None
        if self.size:
            size = map(int, self.size.split('x'))

        Image(size, self.ratio).show(filename, self.double)
Exemple #5
0
class Changespeed(cli.Application):
    PROGNAME = "changespeed.py"
    VERSION = "0.1"

    total_seconds = 0

    @cli.switch(["-s", "--seconds"], cli.Range(0, 60), group="Timesetters")
    def seconds(self, seconds):
        """Set seconds"""
        self.total_seconds += seconds

    @cli.switch(["-m", "--minutes"], cli.Range(0, 60), group="Timesetters")
    def minutes(self, minutes):
        """Set minutes"""
        self.total_seconds += (minutes * 60)

    @cli.switch(["-h", "--hours"], int, group="Timesetters")
    def hours(self, hours):
        """Set hours"""
        self.total_seconds += (hours * 60 * 60)

    def speeded_time(self, time, rate):
        """Recount time for selected rate"""
        coeff = 1.0 / rate
        return time * coeff

    def main(self, rate):
        time_pattern = '%H hours %M minutes %S seconds'
        orig_str = time.strftime(time_pattern, time.gmtime(self.total_seconds))
        rated = self.speeded_time(self.total_seconds, float(rate))
        rated_str = time.strftime(time_pattern, time.gmtime(rated))

        print(orig_str)
        print("x " + rate)
        print("-" * 30)
        print(rated_str)
Exemple #6
0
class ClassicServer(cli.Application):
    mode = cli.SwitchAttr(["-m", "--mode"], cli.Set("threaded", "forking", "stdio", "oneshot"),
                          default="threaded", help="The serving mode (threaded, forking, or 'stdio' for "
                          "inetd, etc.)")

    port = cli.SwitchAttr(["-p", "--port"], cli.Range(0, 65535), default=None,
                          help="The TCP listener port ("
                               "default = {DEFAULT_SERVER_PORT!r}, "
                               "default for SSL = {DEFAULT_SERVER_SSL_PORT!r})",
                          group="Socket Options")
    host = cli.SwitchAttr(["--host"], str, default="", help="The host to bind to. "
                          "The default is localhost", group="Socket Options")
    ipv6 = cli.Flag(["--ipv6"], help="Enable IPv6", group="Socket Options")

    logfile = cli.SwitchAttr("--logfile", str, default=None, help="Specify the log file to use; "
                             "the default is stderr", group="Logging")
    quiet = cli.Flag(["-q", "--quiet"], help="Quiet mode (only errors will be logged)",
                     group="Logging")

    ssl_keyfile = cli.SwitchAttr("--ssl-keyfile", cli.ExistingFile,
                                 help="The keyfile to use for SSL. Required for SSL", group="SSL",
                                 requires=["--ssl-certfile"])
    ssl_certfile = cli.SwitchAttr("--ssl-certfile", cli.ExistingFile,
                                  help="The certificate file to use for SSL. Required for SSL", group="SSL",
                                  requires=["--ssl-keyfile"])
    ssl_cafile = cli.SwitchAttr("--ssl-cafile", cli.ExistingFile,
                                help="The certificate authority chain file to use for SSL. "
                                "Optional; enables client-side authentication",
                                group="SSL", requires=["--ssl-keyfile"])

    auto_register = cli.Flag("--register", help="Asks the server to attempt registering with "
                             "a registry server. By default, the server will not attempt to register",
                             group="Registry")
    registry_type = cli.SwitchAttr("--registry-type", cli.Set("UDP", "TCP"),
                                   default="UDP", help="Specify a UDP or TCP registry", group="Registry")
    registry_port = cli.SwitchAttr("--registry-port", cli.Range(0, 65535), default=REGISTRY_PORT,
                                   help="The registry's UDP/TCP port", group="Registry")
    registry_host = cli.SwitchAttr("--registry-host", str, default=None,
                                   help="The registry host machine. For UDP, the default is 255.255.255.255; "
                                   "for TCP, a value is required", group="Registry")

    def main(self):
        if not self.host:
            self.host = "::1" if self.ipv6 else "127.0.0.1"

        if self.registry_type == "UDP":
            if self.registry_host is None:
                self.registry_host = "255.255.255.255"
            self.registrar = UDPRegistryClient(ip=self.registry_host, port=self.registry_port)
        else:
            if self.registry_host is None:
                raise ValueError("With TCP registry, you must specify --registry-host")
            self.registrar = TCPRegistryClient(ip=self.registry_host, port=self.registry_port)

        if self.ssl_keyfile:
            self.authenticator = SSLAuthenticator(self.ssl_keyfile, self.ssl_certfile,
                                                  self.ssl_cafile)
            default_port = DEFAULT_SERVER_SSL_PORT
        else:
            self.authenticator = None
            default_port = DEFAULT_SERVER_PORT
        if self.port is None:
            self.port = default_port

        setup_logger(self.quiet, self.logfile)

        if self.mode == "threaded":
            self._serve_mode(ThreadedServer)
        elif self.mode == "forking":
            self._serve_mode(ForkingServer)
        elif self.mode == "oneshot":
            self._serve_oneshot()
        elif self.mode == "stdio":
            self._serve_stdio()

    def _serve_mode(self, factory):
        t = factory(SlaveService, hostname=self.host, port=self.port,
                    reuse_addr=True, ipv6=self.ipv6, authenticator=self.authenticator,
                    registrar=self.registrar, auto_register=self.auto_register)
        t.start()

    def _serve_oneshot(self):
        t = OneShotServer(SlaveService, hostname=self.host, port=self.port,
                          reuse_addr=True, ipv6=self.ipv6, authenticator=self.authenticator,
                          registrar=self.registrar, auto_register=self.auto_register)
        t._listen()
        sys.stdout.write("rpyc-oneshot\n")
        sys.stdout.write(f"{t.host}\t{t.port}\n")
        sys.stdout.flush()
        t.start()

    def _serve_stdio(self):
        origstdin = sys.stdin
        origstdout = sys.stdout
        sys.stdin = open(os.devnull, "r")
        sys.stdout = open(os.devnull, "w")
        sys.stderr = open(os.devnull, "w")
        conn = rpyc.classic.connect_pipes(origstdin, origstdout)
        try:
            try:
                conn.serve_all()
            except KeyboardInterrupt:
                print("User interrupt!")
        finally:
            conn.close()
class OracleConnCLI(cli.Application):
    """
    An cli application to test oracle database connection through cx_Oracle.
    """

    AUTHOR = 'luoxu34'
    PROGNAME = colors.blue | 'OracleConnCLI'
    VERSION = colors.green | '0.01'

    _username = '******'
    _password = ''
    _host = '127.0.0.1'
    _port = 1521
    _sid = 'orcl'

    @cli.switch('-u', str, help='login username of database')
    def set_login_username(self, username):
        self._username = username

    @cli.switch('-p', str, help='password of login user')
    def set_login_password(self, password):
        self._password = password

    @cli.switch(['-h', '--host'],
                str,
                help='host ip or hostname where instance is running')
    def set_host_ip(self, ip):
        self._host = ip

    @cli.switch(['-P', '--port'],
                cli.Range(1, 65535),
                help='listen port of instance, default 1521')
    def set_listener_port(self, port):
        self._port = port

    @cli.switch(['-s', '--sid'], str, help='instance name, default orcl')
    def set_sid(self, sid):
        self._sid = sid

    def main(self):
        if not self._password:
            self._password = getpass.getpass(
                'login username: {}\nlogin password: '******'{}/{}@{}:{}/{}'.format(self._username, self._password,
                                           self._host, self._port, self._sid)
        print('connect string: {}'.format(conn_str))

        db = None
        try:
            db = cx_Oracle.connect(conn_str)
            msg = 'connect result: OK [sid: {}, version: {}]'.format(
                self._sid, db.version)
            print(colors.green | msg)
            return 0
        except Exception as exc:
            msg = 'connect result: failed [{}]'.format(exc)
            print(colors.red | msg)
            return 1
        finally:
            if db:
                db.close()

    @cli.switch(['-v', '--version'],
                overridable=True,
                group='Meta-switches',
                help=T_('''Prints the program's version and quits'''))
    def version(self):
        print('{} {} by {}'.format(self.PROGNAME, self.VERSION, self.AUTHOR))
Exemple #8
0
class AngrDbgServer(cli.Application):
    port = cli.SwitchAttr(
        ["-p", "--port"],
        cli.Range(0, 65535),
        default=None,
        help="The TCP listener port (default = %s, default for SSL = %s)" %
        (DEFAULT_SERVER_PORT, DEFAULT_SERVER_SSL_PORT),
        group="Socket Options")
    host = cli.SwitchAttr(["--host"],
                          str,
                          default="127.0.0.1",
                          help="The host to bind to. "
                          "The default is INADDR_ANY",
                          group="Socket Options")
    ipv6 = cli.Flag(["--ipv6"], help="Enable IPv6", group="Socket Options")

    logfile = cli.SwitchAttr("--logfile",
                             str,
                             default=None,
                             help="Specify the log file to use; "
                             "the default is stderr",
                             group="Logging")
    quiet = cli.Flag(["-q", "--quiet"],
                     help="Quiet mode (only errors will be logged)",
                     group="Logging")

    ssl_keyfile = cli.SwitchAttr(
        "--ssl-keyfile",
        cli.ExistingFile,
        help="The keyfile to use for SSL. Required for SSL",
        group="SSL",
        requires=["--ssl-certfile"])
    ssl_certfile = cli.SwitchAttr(
        "--ssl-certfile",
        cli.ExistingFile,
        help="The certificate file to use for SSL. Required for SSL",
        group="SSL",
        requires=["--ssl-keyfile"])
    ssl_cafile = cli.SwitchAttr(
        "--ssl-cafile",
        cli.ExistingFile,
        help=
        "The certificate authority chain file to use for SSL. Optional; enables client-side "
        "authentication",
        group="SSL",
        requires=["--ssl-keyfile"])

    auto_register = cli.Flag(
        "--register",
        help="Asks the server to attempt registering with "
        "a registry server. By default, the server will not attempt to register",
        group="Registry")
    registry_type = cli.SwitchAttr("--registry-type",
                                   cli.Set("UDP", "TCP"),
                                   default="UDP",
                                   help="Specify a UDP or TCP registry",
                                   group="Registry")
    registry_port = cli.SwitchAttr("--registry-port",
                                   cli.Range(0, 65535),
                                   default=REGISTRY_PORT,
                                   help="The registry's UDP/TCP port",
                                   group="Registry")
    registry_host = cli.SwitchAttr(
        "--registry-host",
        str,
        default=None,
        help=
        "The registry host machine. For UDP, the default is 255.255.255.255; "
        "for TCP, a value is required",
        group="Registry")

    def main(self):
        if self.registry_type == "UDP":
            if self.registry_host is None:
                self.registry_host = "255.255.255.255"
            self.registrar = UDPRegistryClient(ip=self.registry_host,
                                               port=self.registry_port)
        else:
            if self.registry_host is None:
                raise ValueError(
                    "With TCP registry, you must specify --registry-host")
            self.registrar = TCPRegistryClient(ip=self.registry_host,
                                               port=self.registry_port)

        if self.ssl_keyfile:
            self.authenticator = SSLAuthenticator(self.ssl_keyfile,
                                                  self.ssl_certfile,
                                                  self.ssl_cafile)
            default_port = DEFAULT_SERVER_SSL_PORT
        else:
            self.authenticator = None
            default_port = DEFAULT_SERVER_PORT
        if self.port is None:
            self.port = default_port

        setup_logger(self.quiet, self.logfile)

        sys.stdout.write(BANNER + " starting at %s %s\n" %
                         (self.host, self.port))
        sys.stdout.flush()

        done_event = threading.Event()
        srv = WeirdServer(SlaveService,
                          done_event,
                          hostname=self.host,
                          port=self.port,
                          reuse_addr=True,
                          ipv6=self.ipv6,
                          authenticator=self.authenticator,
                          registrar=self.registrar,
                          auto_register=self.auto_register)

        t = threading.Thread(target=self._serve, args=[srv])
        t.start()

        # wait for 2 connections
        done_event.wait()

        IPython.embed(
            banner1=BANNER + " client connected\n",
            banner2=
            "",  # "tip: call serve_all() on the client to have a full working shell here.",
            exit_msg=BANNER + " shell closed.\nexiting...\n")

        os.kill(srv.proc, signal.SIGKILL)
        os._exit(0)

    def _serve(self, srv):
        srv.start()

        sys.stdout.write("\n" + BANNER + " client disconnected.\nexiting...\n")
        os._exit(0)
Exemple #9
0
class ClipSilences(cli.Application):
    verbose = cli.Flag(["-v", "--verbose"], help="Enable verbose logging")
    in_file = cli.SwitchAttr("-i", help="The input file to read / analyse / convert", mandatory=True)
    min_duration = cli.SwitchAttr("--s-min", help="The minimum duration of silences", default=0.5, argtype=float)
    max_duration = cli.SwitchAttr("--s-max", help="The maximum duration of silences", default=6, argtype=float)
    threshold = cli.SwitchAttr("-t", help="silence threshold in dB", default=-30, argtype=cli.Range(-100, 0))
    codec = cli.SwitchAttr("--codec-video", help="video encoding library",
                           argtype=cli.Set("h264_vaapi", "h264_nvenc", "libx264", "h264_v4l2m2m", str))
    audio_codec = cli.SwitchAttr("--codec-audio", help="video encoding library", default="libvorbis",
                                 argtype=cli.Set("libvorbis", "libmp3lame", "libfdk_aac", str))

    def info(self, output=None) -> Tuple[int, str, str]:
        print(f'duration: {self.min_duration}')
        assert self.min_duration >= 0.5
        assert len(self.in_file) > 0
        ffmpeg_cmd = self.mk_ffmpeg_bound_command()
        print(f'Running ffmpeg command: {ffmpeg_cmd}')
        _cmd = (ffmpeg_cmd > output) if output else ffmpeg_cmd
        return _cmd & TEE

    def mk_ffmpeg_bound_command(self):
        return ffmpeg[
            '-hide_banner',
            '-vn',  # disable video 'recording'
            '-i', self.in_file,
            '-af', f'silencedetect=n={self.threshold}dB:d={self.min_duration}',  # audio filter, silencedetect
            '-f', 'null',  # output format: null
            '-',  # output to stdout
        ]

    @staticmethod
    def ease_in_and_out(x: float) -> float:
        return 2 * x * x if x < 0.5 else 1 - (-2 * x + 2) ** 2 / 2

    @staticmethod
    def rescale_silence(start, duration, end, min_duration=0.5, max_duration=10) -> Tuple[float, float, float]:
        offset = min_duration
        scaling = (max_duration - min_duration) / 2
        if duration < 0.5:
            return start, duration, end
        _duration = min(
            [10, ClipSilences.ease_in_and_out(max([0, duration - offset]) / scaling) * scaling / 2 + offset])
        delta = (duration - _duration) / 2
        return start + delta, _duration, end - delta

    @staticmethod
    def rescale_all_silences(silences: List[Tuple[float, float, float]],
                             min_duration, max_duration) -> List[Tuple[float, float, float]]:
        return list(
            ClipSilences.rescale_silence(s, d, e, min_duration=min_duration, max_duration=max_duration) for (s, d, e) in
            silences)

    @cli.switch("-o", help="The output file")
    def trim_silences(self, silences: List[Tuple[float, float, float]]):
        video = VideoFileClip(self.in_file)
        full_duration = video.duration
        # print(f"pre_silences: {silences}")
        _silences = self.rescale_all_silences(silences, min_duration=self.min_duration, max_duration=self.max_duration)
        # print(f"post_silences: {_silences}")
        non_silent_periods = list(
            [(end1, start2 - end1, start2) for (_, _, end1), (start2, _, _) in zip(_silences[:-1], _silences[1:])])
        print(non_silent_periods)
        input_dir, input_file = os.path.split(self.in_file)
        fname, fext = os.path.splitext(input_file)
        output_fname = os.path.join(input_dir, f"{fname}_NOSILENCE_{self.min_duration}s{fext}")
        tmp_audio_fname = f"{fname}.TEMP_MPY_wvf_snd_custom.ogg"
        tmp_video_fname = f"{fname}.TEMP_MPY_vid_custom{fext}"
        print(f"writing output to {output_fname}")
        clips = list([video.subclip(s, e) for s, d, e in non_silent_periods if d >= 1])
        print(f"got list of clips")
        # comp = mpy.CompositeVideoClip(clips)
        comp = concatenate_videoclips(clips)
        print(f"make composite video clip (no sound yet)")
        comp.write_videofile(tmp_video_fname, codec=self.codec, preset='ultrafast',
                             threads=os.cpu_count() + 1, audio_codec=self.audio_codec)
        print(f"done writing out ${tmp_video_fname}")

        video.close()
        print(f"closed video")
        # print(f"preparing to write audio")
        # comp.audio.write_audiofile(tmp_audio_fname, buffersize=2000000, codec=self.audio_codec)
        # print(f"wrote audio")
        # comp.audio = None
        # print(f"wrote out video, now combining")
        # output_video = VideoFileClip(tmp_video_fname, audio=False)
        # output_video.set_audio(AudioFileClip(tmp_audio_fname))
        # output_video.write_videofile(output_fname)
        # output_video.write_videofile(output_fname, preset='ultrafast', codec=self.codec, threads=os.cpu_count() + 1,
        #                              fps=video.fps)
        print(f"wrote video out")

    def main(self, cmd=cli.Set("info", "trim")):
        (_code, _stdout, _stderr) = self.info()
        silences = []
        for l in _stderr.split('\n'):
            if 'silence_end' not in l:
                continue
            # sample line: [silencedetect @ 0x7fffe351b460] silence_end: 51.2464 | silence_duration: 2.06966
            l2 = l.strip().split('silence_end: ')[1]
            silence_end, rem = l2.split(' ', maxsplit=1)
            silence_duration = rem.split('silence_duration: ')[1]
            end = float(silence_end)
            duration = float(silence_duration)
            start = end - duration
            silences.append((start, duration, end))
        self.trim_silences(silences)
Exemple #10
0
class Cli(cli.Application):
    '''
		Command-Line options received.
	'''
    verbose = cli.Flag(["-v", '--verbose'], help="Verbose Mode.")
    brute = cli.Flag(
        ["-b", '--brute'],
        help=
        "Brute Force Mode. (Specify -u/--users-file and -f/--passwords-file options to select the users and passwords files.)"
    )
    useMirror = cli.Flag(
        ["-d", '--use-mirrors'],
        help=
        "Use the mirror directories of TOR. This will help to not overwhelm the official directories"
    )
    useShodan = cli.Flag(
        ["-s", '--use-shodan'],
        help=
        "Use ShodanHQ Service. (Specify -k/--shodan-key to set up the file where's stored your shodan key.)"
    )
    threads = 1
    mode = None
    usersFile = None
    passFile = None
    exitNodesToAttack = 10  #Number of default exit-nodes to filter from the Server Descriptor file.
    shodanKey = None
    scanPorts = "21,22,23,53,69,80,88,110,139,143,161,389,443,445,1079,1080,1433,3306,5432,8080,9050,9051,5800"  #Default ports used to scan with nmap.
    scanProtocol = 'tcp'  #Using TCP protocol to perform the nmap scan.
    scanArguments = None  #Scan Arguments passed to nmap.
    exitNodeFingerprint = None  #Fingerprint of the exit-node to attack.
    queue = Queue.Queue(
    )  #Queue with the host/open-port found in the scanning.

    @cli.switch(["-n", "--servers-to-attack"],
                int,
                help="Number of TOR exit-nodes to attack. Default = 10")
    def servers_to_attack(self, exitNodesToAttack):
        '''	
			Number of "exit-nodes" to attack received from command-line
		'''
        self.exitNodesToAttack = exitNodesToAttack

    @cli.switch(["-t", "--threads"],
                cli.Range(1, 20),
                help='Number of threads to use.')
    def number_threads(self, threads):
        '''	
			Number of threads to create when the scanning process has been done.
		'''
        self.threads = threads

    @cli.switch(["-m", "--mode"],
                cli.Set("windows", "linux", case_sensitive=False),
                mandatory=True,
                help="Filter the platform of exit-nodes to attack.")
    def server_mode(self, mode):
        '''
			Server Mode: Search for Windows or Linux machines.
		'''
        self.mode = mode

    @cli.switch(["-u", "--users-file"],
                help="Users File in the Bruteforce mode.",
                requires=["--brute"])
    def users_file(self, usersFile):
        '''
			User's file. Used to perform bruteforce attacks.
		'''
        self.usersFile = usersFile

    @cli.switch(["-f", "--passwords-file"],
                help="Passwords File in the Bruteforce mode.",
                requires=["--brute"])
    def users_file(self, usersFile):
        '''
						User's file. Used to perform bruteforce attacks.		
		'''
        self.usersFile = usersFile

    @cli.switch(["-k", "--shodan-key"],
                str,
                help="Development Key to use Shodan API.",
                requires=["--use-shodan"])
    def shodan_key(self, shodanKey):
        '''
			This option is used to specify the file where the shodan development key is stored
		'''
        self.shodanKey = shodanKey

    @cli.switch(
        ["-l", "--list-ports"],
        str,
        help="Comma-separated List of ports to scan with Nmap. Don't use spaces"
    )
    def list_ports(self, scanPorts):
        '''
			List of ports used to perform the nmap scan.
		'''
        self.scanPorts = scanPorts

    @cli.switch(["-p", "--scan-protocol"],
                cli.Set("tcp", "udp", case_sensitive=True),
                help="Protocol used to scan the target.")
    def scan_protocol(self, scanProtocol):
        '''
			Protocol used to perform the nmap scan.
		'''
        self.scanProtocol = scanProtocol

    @cli.switch(
        ["-a", "--scan-arguments"],
        str,
        help=
        'Arguments to Nmap. Use "" to specify the arguments. For example: "-sSV -A -Pn"'
    )
    def scan_arguments(self, scanArguments):
        '''
			Arguments used to perform the nmap scan.
		'''
        self.scanArguments = scanArguments

    @cli.switch(["-e", "--exit-node-fingerprint"],
                str,
                help="ExitNode's Fingerprint to attack.")
    def exitNode_Fingerprint(self, exitNodeFingerprint):
        '''
			If we want to perform a single attack against an known "exit-node", We can specify the fingerprint of the exit-node to perform the attack.
		'''
        self.exitNodeFingerprint = exitNodeFingerprint

    def main(self):
        '''
			List and Scan the exit nodes. The function will return an dictionary with the exitnodes found and the open ports.
			THIS PROCESS IS VERY SLOW AND SOMETIMES THE CONNECTION WITH THE DIRECTORY AUTHORITIES IS NOT AVAILABLE.
		'''
        discovery = Discovery(self)
        exitNodes = discovery.listExitNodes(
        )  #Returns a tuple with IP Addresses and open-ports.
        if exitNodes != None and len(exitNodes) > 0:
            for thread in range(
                    self.threads
            ):  #Creating the number of threads specified by command-line.
                worker = WorkerThread(self.queue, thread, self)
                worker.setDaemon(True)
                worker.start()

            for exitNode in exitNodes.items():
                self.queue.put(exitNode)
            self.queue.join(
            )  #Blocks the main process until the queue is empty.

        log.info("[+] Process finished at " +
                 strftime("%Y-%m-%d %H:%M:%S", gmtime()))
Exemple #11
0
class Cli(cli.Application):
    '''
    Command-Line options received.
    '''
    PROGNAME = "TORTAZO"
    AUTHOR = "Adastra"
    VERSION = "1.1"
    SEPARATOR = ':'  #Separator for the dictionary (bruteforce attacks) for each line in the file, the user and password must be separated by colon. For Instance -> user:password
    verbose = cli.Flag(["-v", '--verbose'], help="Verbose Mode.")
    brute = cli.Flag(
        ["-b", '--brute'],
        help=
        "Brute Force Mode. (Specify -f/--passwords-file option to select the passwords file. Every line should contain the the username and password to test separated with a colon <USER>:<PASSWORD>)"
    )
    useMirror = cli.Flag(
        ["-d", '--use-mirrors'],
        help=
        "Use the mirror directories of TOR. This will help to not overwhelm the official directories"
    )
    useShodan = cli.Flag(
        ["-s", '--use-shodan'],
        help=
        "Use ShodanHQ Service. (Specify -k/--shodan-key to set up the file where's stored your shodan key.)"
    )
    useCircuitExitNodes = cli.Flag(
        ["-c", "--use-circuit-nodes"],
        help="Use the exit nodes selected for a local instance of TOR.")
    openShell = cli.Flag(["-o", "--open-shell"],
                         excludes=["--mode"],
                         requires=["--zombie-mode"],
                         help="Open a shell on the specified host.")
    useDatabase = cli.Flag(
        ["-D", '--use-database'],
        help=
        "Tortazo will store the last results from the scanning process in a database. If you use this flag, Tortazo will omit the scan and just will try use the data stored from the last execution."
    )
    cleanDatabase = cli.Flag(
        ["-C", '--clean-database'],
        help=
        "Tortazo will delete all records stored in database when finished executing. This option will delete every record stored, included the data from previous scans."
    )

    threads = 1  #Execution Threads.
    # mode = None #Mode: Windows/Linux
    dictFile = None  #Dict. file for brute-force attacks.
    exitNodesToAttack = 10  #Number of default exit-nodes to filter from the Server Descriptor file.
    shodanKey = None  #ShodanKey file.
    scanPorts = "21,22,23,53,69,80,88,110,139,143,161,162,389,443,445,1079,1080,1433,3306,5432,8080,9050,9051,5800"  #Default ports used to scan with nmap.
    scanArguments = None  #Scan Arguments passed to nmap.
    exitNodeFingerprint = None  #Fingerprint of the exit-node to attack.
    queue = Queue.Queue(
    )  #Queue with the host/open-port found in the scanning.
    controllerPort = '9151'
    zombieMode = None
    mode = "linux"
    runCommand = None
    pluginManagement = None
    scanIdentifier = None

    @cli.switch(
        ["-n", "--servers-to-attack"],
        int,
        help=
        "Number of TOR exit-nodes to attack. If this switch is used with --use-database, will recover information stored from the last 'n' scans. Default = 10"
    )
    def servers_to_attack(self, exitNodesToAttack):
        '''
        Number of "exit-nodes" to attack received from command-line
        '''
        self.exitNodesToAttack = exitNodesToAttack

    @cli.switch(["-t", "--threads"],
                cli.Range(1, 20),
                help='Number of threads to use.')
    def number_threads(self, threads):
        '''
        Number of threads to create when the brute-force switches has been specified.
        '''
        self.threads = threads

    @cli.switch(["-m", "--mode"],
                cli.Set("windows", "linux", case_sensitive=False),
                excludes=["--zombie-mode"],
                help="Filter the platform of exit-nodes to attack.")
    def server_mode(self, mode):
        '''
        Server Mode: Search for Windows or Linux machines.
        '''
        self.mode = mode

    @cli.switch(["-f", "--passwords-file"],
                str,
                help="Passwords File in the Bruteforce mode.",
                requires=["--brute"])
    def passwords_file(self, dictFile):
        '''
        User's file. Used to perform bruteforce attacks.
        '''
        self.dictFile = dictFile

    @cli.switch(["-k", "--shodan-key"],
                str,
                help="Development Key to use Shodan API.",
                requires=["--use-shodan"])
    def shodan_key(self, shodanKey):
        '''
        This option is used to specify the file where the shodan development key is stored
        '''
        self.shodanKey = shodanKey

    @cli.switch(
        ["-l", "--list-ports"],
        str,
        help="Comma-separated List of ports to scan with Nmap. Don't use spaces"
    )
    def list_ports(self, scanPorts):
        '''
        List of ports used to perform the nmap scan.
        '''
        self.scanPorts = scanPorts

    @cli.switch(
        ["-a", "--scan-arguments"],
        str,
        help=
        'Arguments to Nmap. Use "" to specify the arguments. For example: "-sSV -A -Pn"'
    )
    def scan_arguments(self, scanArguments):
        '''
        Arguments used to perform the nmap scan.
        '''
        self.scanArguments = scanArguments

    @cli.switch(["-e", "--exit-node-fingerprint"],
                str,
                help="ExitNode's Fingerprint to attack.")
    def exitNode_Fingerprint(self, exitNodeFingerprint):
        '''
        If we want to perform a single attack against an known "exit-node", We can specify the fingerprint of the exit-node to perform the attack.
        '''
        self.exitNodeFingerprint = exitNodeFingerprint

    @cli.switch(
        ["-i", "--controller-port"],
        str,
        help="Controller's port of the local instance of TOR. (Default=9151)",
        requires=["--use-circuit-nodes"])
    def controller_port(self, controllerPort):
        '''
        Controller's Port. Default=9151
        '''
        self.controllerPort = controllerPort

    @cli.switch(
        ["-z", "--zombie-mode"],
        str,
        help=
        "This option reads the tortazo_botnet.bot file generated from previous successful attacks. With this option you can select the Nicknames that will be excluded. (Nicknames included in the tortazo_botnet.bot). For instance, '-z Nickname1,Nickname2' or '-z all' to include all nicknames."
    )
    def zombie_mode(self, zombieMode):
        '''
        Zombie mode to execute commands across the compromised hosts.
        '''
        if zombieMode == None:
            self.zombieMode = ""
        self.zombieMode = zombieMode

    @cli.switch(
        ["-r", "--run-command"],
        str,
        excludes=["--mode"],
        requires=["--zombie-mode"],
        help=
        'Execute a command across the hosts of the botnet. Requieres the -z/--zombie-mode. example: --run-command "uname -a; uptime" '
    )
    def run_command(self, runCommand):
        '''
        Command to execute across the compromised hosts.
        '''
        self.runCommand = runCommand

    @cli.switch(
        ["-P", "--use-plugin"],
        str,
        help=
        'Execute a plugin (or list) included in the plugins directory. for instance: "-P simplePlugin:simplePrinter,argName1=arg1,argName2=arg2,argNameN=argN;anotherSimplePlugin:anotherSimpleExecutor,argName1=arg1,argName2=arg2,argNameN=argN" where simplePlugin is the module, simplePrinter is a class which inherites from BasePlugin class and argName1=argValue1,argName2=argValue2,argNameN=argValueN are arguments used for this plugin. Multiple plugins should be separated by ";" and you can get the help banner for a plugin executing "pluginName:help". Check the documentation for more detailed information'
    )
    def plugin_management(self, pluginManagement):
        '''
        Plugin Management.
        '''
        self.pluginManagement = pluginManagement

    @cli.switch(
        ["-S", "--scan-identifier"],
        int,
        requires=["--use-database"],
        help=
        "scan identifier in the Scan table. Tortazo will use the relays related with the scan identifier specified with this option."
    )
    def scan_identifier(self, scanIdentifier):
        '''
        Scan Identifier. Tortazo will use the relays associated with this scan. (Relation between the Scan and TorNodeData tables.)
        '''
        self.scanIdentifier = scanIdentifier

    def main(self):
        '''
        Initialization of logger system.
        '''

        self.logger = log
        self.exitNodes = []
        self.database = TortazoDatabase()

        if self.verbose:
            self.logger.basicConfig(format="%(levelname)s: %(message)s",
                                    level=log.DEBUG)
            self.logger.debug(
                term.format("[+] Verbose mode activated.", term.Color.GREEN))
        else:
            self.logger.basicConfig(format="%(levelname)s: %(message)s")
        self.logger.info(
            term.format(
                "[+] Process started at " +
                strftime("%Y-%m-%d %H:%M:%S", gmtime()), term.Color.YELLOW))

        #self.loadAndExecute(self,"simplePlugin:simplePrinter")
        '''
            List and Scan the exit nodes. The function will return an dictionary with the exitnodes found and the open ports.
            THIS PROCESS IS VERY SLOW AND SOMETIMES THE CONNECTION WITH THE DIRECTORY AUTHORITIES IS NOT AVAILABLE.
        '''

        if self.zombieMode:
            '''
            In zombie mode, The program should read the file named "tortazo_botnet.bot".
            In that file, every line have this format: host:user:password:nickname
            Extract every host and then, create a list of bots.
            '''
            botnet = BotNet(self)
            botnet.start()

        else:
            discovery = Discovery(self)

            if self.useDatabase:
                #There's a previous scan stored in database. We'll use that information!
                if self.scanIdentifier is None:
                    self.logger.info(
                        term.format(
                            "[+] Getting the last %s scans executed from database..."
                            % (self.exitNodesToAttack), term.Color.YELLOW))
                    self.logger.debug(
                        term.format(
                            "[+] Use -n/--servers-to-attack option to include more or less records from the scans recorded in database.",
                            term.Color.GREEN))
                    self.exitNodes = self.database.searchExitNodes(
                        self.exitNodesToAttack, None)
                else:
                    self.logger.info(
                        term.format(
                            "[+] Getting the relays for the scan %d ..." %
                            (self.scanIdentifier), term.Color.YELLOW))
                    self.exitNodes = self.database.searchExitNodes(
                        self.exitNodesToAttack, self.scanIdentifier)

                if len(self.exitNodes) > 0:
                    self.logger.info(
                        term.format("[+] Done!", term.Color.YELLOW))
                else:
                    if self.scanIdentifier is None:
                        self.logger.info(
                            term.format(
                                "[+] No records found... You should execute an initial scan.",
                                term.Color.YELLOW))
                        self.logger.warn(
                            term.format(
                                "[-] You've chosen to use the database records, however the database tables are empty because you have not run an initial scan.",
                                term.Color.RED))
                        self.logger.warn(
                            term.format(
                                "[-] Tortazo just saves the relays found in the last scan. Previous scans always will be deleted.",
                                term.Color.RED))
                    else:
                        self.logger.warn(
                            term.format(
                                "[+] No records found with the scan identifier specified, check the database...",
                                term.Color.RED))
                    return
            else:
                if self.useCircuitExitNodes:
                    #Try to use a local instance of TOR to get information about the relays in the server descriptors.
                    self.exitNodes = discovery.listCircuitExitNodes()
                else:
                    #Try to connect with the TOR directories to get information about the relays in the server descriptors.
                    self.exitNodes = discovery.listAuthorityExitNodes(
                    )  #Returns a list of TorNodeData objects

            if self.exitNodes is not None and len(self.exitNodes) > 0:
                reporter = Reporting(self)
                reporter.generateNmapReport(self.exitNodes,
                                            config.NmapOutputFile)
                self.shodanHosts = []
                for torNode in self.exitNodes:
                    if self.brute:
                        self.queue.put(torNode)
                    #If shodan is activated, let's try to gather some information for every node found.
                    if self.useShodan == True:
                        #Using Shodan to search information about this machine in shodan database.
                        self.logger.info(
                            term.format(
                                "[+] Shodan Activated. About to read the Development Key. ",
                                term.Color.YELLOW))
                        if self.shodanKey == None:
                            #If the key is None, we can't use shodan.
                            self.logger.warn(
                                term.format(
                                    "[-] Shodan Key's File has not been specified. We can't use shodan without a valid key",
                                    term.Color.RED))
                        else:
                            #Read the shodan key and create the Shodan object.
                            try:
                                shodanKeyString = open(
                                    self.shodanKey).readline().rstrip('\n')
                                shodanHost = discovery.shodanSearchByHost(
                                    shodanKeyString, torNode.host)
                                self.shodanHosts.append(shodanHost)
                            except IOError, ioerr:
                                self.logger.warn(
                                    term.format(
                                        "[-] Shodan's key File: %s not Found."
                                        % (self.shodanKey), term.Color.RED))

                if len(self.shodanHosts) > 0:
                    reporter.generateShodanReport(self.shodanHosts,
                                                  config.ShodanOutputFile)

                #Check if there's any plugin to execute!
                if self.pluginManagement != None:
                    self.loadAndExecute(self.pluginManagement, self.exitNodes)

                #Block until the queue is empty.
                if self.brute:
                    for thread in range(
                            self.threads
                    ):  #Creating the number of threads specified by command-line.
                        worker = WorkerThread(self.queue, thread, self)
                        worker.setDaemon(True)
                        worker.start()
                    self.queue.join()

                if self.cleanDatabase:
                    self.logger.info(
                        term.format(
                            "[+] Cleaning database... Deleting all records.",
                            term.Color.YELLOW))
                    self.database.initDatabase()
                    self.database.cleanDatabaseState()
        self.logger.info((term.format(
            "[+] Process finished at " +
            strftime("%Y-%m-%d %H:%M:%S", gmtime()), term.Color.YELLOW)))
Exemple #12
0
class RegistryServer(cli.Application):

    config = cli.SwitchAttr(["-c", "--conf"],
                            str,
                            default=None,
                            help="Config file")

    mode = cli.SwitchAttr(["-m", "--mode"],
                          cli.Set("UDP", "TCP"),
                          default="UDP",
                          help="Serving mode")

    ipv6 = cli.Flag(["-6", "--ipv6"], help="use ipv6 instead of ipv4")

    host = cli.SwitchAttr(["--host"],
                          str,
                          default="::",
                          help="Interface to bind to")

    port = cli.SwitchAttr(["-p", "--port"],
                          cli.Range(0, 65535),
                          default=REGISTRY_PORT,
                          help="The UDP/TCP listener port")

    logfile = cli.SwitchAttr(["--logfile"],
                             str,
                             default=None,
                             help="The log file to use; the default is stderr")

    quiet = cli.Flag(["-q", "--quiet"],
                     help="Quiet mode (only errors are logged)")

    timeout = cli.SwitchAttr(["-t", "--timeout"],
                             int,
                             default=DEFAULT_PRUNING_TIMEOUT,
                             help="Set a custom pruning timeout (in seconds)")

    @cli.switch("--config",
                str,
                excludes=['-m', '-6', '-p', '--logfile', '-q', '-t'])
    def config(self, config):
        ''' Use config instead of command line arguments'''
        if config:
            conf = ConfigParser({
                "mode": "UDP",
                "ipv6": False,
                "host": "::",
                "port": REGISTRY_PORT,
                "logfile": None,
                "quiet": True,
                "timeout": DEFAULT_PRUNING_TIMEOUT
            })
            conf.read(config)

        self.mode = conf.get("registry", "mode").upper()
        if self.mode not in ["UDP", "TCP"]:
            raise ValueError("Invalid mode %s" % (self.mode, ))

        self.ipv6 = conf.getboolean("registry", "ipv6")
        self.port = conf.getint("registry", "port")
        self.logfile = conf.get("registry", "logfile")
        self.host = conf.get("registry", "host")
        self.quiet = conf.getboolean("registry", "quiet")

    def main(self):
        if self.mode == "UDP":
            server = UDPRegistryServer(host=self.host,
                                       port=self.port,
                                       pruning_timeout=self.timeout)
        elif self.mode == "TCP":
            server = TCPRegistryServer(port=self.port,
                                       pruning_timeout=self.timeout)
        setup_logger(self.quiet, self.logfile)
        print >> sys.stderr, "Starting registry on port %s..." % self.port
        server.start()
Exemple #13
0
class BBHost(cli.Application):

    host = cli.SwitchAttr(["--host"],
                          str,
                          default="127.0.0.1",
                          group="Socket Options",
                          help="The host to bind to. Default is localhost")
    port_help = (
        f"The TCP listener port (default = {DEFAULT_RPYC_SERVER_PORT},"
        "default for SSL = {DEFAULT_RPYC_SERVER_SSL_PORT}")
    port = cli.SwitchAttr(["-p", "--port"],
                          cli.Range(0, 65535),
                          default=DEFAULT_RPYC_SERVER_PORT,
                          group="Socket Options",
                          help=port_help)

    logfile = cli.SwitchAttr(
        "--logfile",
        str,
        default=None,
        group="Logging",
        help="Specify the log file to use; the default is stderr")
    quiet = cli.Flag(["-q", "--quiet"],
                     group="Logging",
                     help="Quiet mode (only errors will be logged)")

    ssl_keyfile = cli.SwitchAttr(
        "--ssl-keyfile",
        cli.ExistingFile,
        group="SSL",
        requires=["--ssl-certfile"],
        help="The keyfile to use for SSL. Required for SSL")
    ssl_certfile = cli.SwitchAttr(
        "--ssl-certfile",
        cli.ExistingFile,
        group="SSL",
        requires=["--ssl-keyfile"],
        help="The certificate file to use for SSL. Required for SSL")
    ssl_help = "The certificate authority chain file to use for SSL. Optional; enables client-side authentication"
    ssl_cafile = cli.SwitchAttr("--ssl-cafile",
                                cli.ExistingFile,
                                group="SSL",
                                requires=["--ssl-keyfile"],
                                help=ssl_help)

    def main(self):
        if self.ssl_keyfile:
            self.authenticator = SSLAuthenticator(self.ssl_keyfile,
                                                  self.ssl_certfile,
                                                  self.ssl_cafile)
            default_port = DEFAULT_SERVER_SSL_PORT
        else:
            self.authenticator = None
            default_port = DEFAULT_SERVER_PORT
        if self.port is None:
            self.port = default_port

        setup_logger(self.quiet, self.logfile)

        server = ThreadedServer(BBTestService,
                                hostname=self.host,
                                port=self.port,
                                authenticator=self.authenticator)
        server.start()