Example #1
0
    def makeService(self, options):
        """
        Construct a TCPServer from a factory defined in Cowrie.
        """

        if options["help"] is True:
            print("""Usage: twistd [options] cowrie [-h]
Options:
  -h, --help             print this help message.

Makes a Cowrie SSH/Telnet honeypot.
""")
            sys.exit(1)

        if os.name == 'posix' and os.getuid() == 0:
            print('ERROR: You must not run cowrie as root!')
            sys.exit(1)

        tz = CowrieConfig().get('honeypot', 'timezone', fallback='UTC')
        # `system` means use the system time zone
        if tz != 'system':
            os.environ['TZ'] = tz

        log.msg("Python Version {}".format(str(sys.version).replace('\n', '')))
        log.msg("Twisted Version {}.{}.{}".format(__twisted_version__.major,
                                                  __twisted_version__.minor,
                                                  __twisted_version__.micro))
        log.msg("Cowrie Version {}.{}.{}".format(__cowrie_version__.major,
                                                 __cowrie_version__.minor,
                                                 __cowrie_version__.micro))

        # check configurations
        if not self.enableTelnet and not self.enableSSH and not self.pool_only:
            print(
                'ERROR: You must at least enable SSH or Telnet, or run the backend pool'
            )
            sys.exit(1)

        # Load output modules
        self.output_plugins = []
        for x in CowrieConfig().sections():
            if not x.startswith('output_'):
                continue
            if CowrieConfig().getboolean(x, 'enabled') is False:
                continue
            engine = x.split('_')[1]
            try:
                output = __import__('cowrie.output.{}'.format(engine),
                                    globals(), locals(), ['output']).Output()
                log.addObserver(output.emit)
                self.output_plugins.append(output)
                log.msg("Loaded output engine: {}".format(engine))
            except ImportError as e:
                log.err(
                    "Failed to load output engine: {} due to ImportError: {}".
                    format(engine, e))
                log.msg(
                    "Please install the dependencies for {} listed in requirements-output.txt"
                    .format(engine))
            except Exception:
                log.err()
                log.msg("Failed to load output engine: {}".format(engine))

        self.topService = service.MultiService()
        application = service.Application('cowrie')
        self.topService.setServiceParent(application)

        # initialise VM pool handling - only if proxy AND pool set to enabled, and pool is to be deployed here
        # or also enabled if pool_only is true
        backend_type = CowrieConfig().get('honeypot',
                                          'backend',
                                          fallback='shell')
        proxy_backend = CowrieConfig().get('proxy',
                                           'backend',
                                           fallback='simple')

        if (backend_type == 'proxy'
                and proxy_backend == 'pool') or self.pool_only:
            # in this case we need to set some kind of pool connection

            local_pool = CowrieConfig().get('proxy', 'pool',
                                            fallback='local') == 'local'
            pool_host = CowrieConfig().get('proxy',
                                           'pool_host',
                                           fallback='127.0.0.1')
            pool_port = CowrieConfig().getint('proxy',
                                              'pool_port',
                                              fallback=6415)

            if local_pool or self.pool_only:
                # start a pool locally
                f = PoolServerFactory()
                f.tac = self

                listen_endpoints = get_endpoints_from_section(
                    CowrieConfig(), 'backend_pool', 6415)
                create_endpoint_services(reactor, self.topService,
                                         listen_endpoints, f)

                pool_host = '127.0.0.1'  # force use of local interface

            # either way (local or remote) we set up a client to the pool
            # unless this instance has no SSH and Telnet (pool only)
            if (self.enableTelnet or self.enableSSH) and not self.pool_only:
                self.pool_handler = PoolHandler(pool_host, pool_port, self)

        else:
            # we initialise the services directly
            self.pool_ready()

        return self.topService
Example #2
0
    def makeService(self, options: Dict) -> service.Service:
        """
        Construct a TCPServer from a factory defined in Cowrie.
        """

        if options["help"] is True:
            print("""Usage: twistd [options] cowrie [-h]
Options:
  -h, --help             print this help message.

Makes a Cowrie SSH/Telnet honeypot.
""")
            sys.exit(1)

        if os.name == "posix" and os.getuid() == 0:
            print("ERROR: You must not run cowrie as root!")
            sys.exit(1)

        tz: str = CowrieConfig.get("honeypot", "timezone", fallback="UTC")
        # `system` means use the system time zone
        if tz != "system":
            os.environ["TZ"] = tz

        log.msg("Python Version {}".format(str(sys.version).replace("\n", "")))
        log.msg("Twisted Version {}.{}.{}".format(
            __twisted_version__.major,
            __twisted_version__.minor,
            __twisted_version__.micro,
        ))
        log.msg("Cowrie Version {}.{}.{}".format(
            __cowrie_version__.major,
            __cowrie_version__.minor,
            __cowrie_version__.micro,
        ))

        # check configurations
        if not self.enableTelnet and not self.enableSSH and not self.pool_only:
            print(
                "ERROR: You must at least enable SSH or Telnet, or run the backend pool"
            )
            sys.exit(1)

        # Load output modules
        self.output_plugins = []
        for x in CowrieConfig.sections():
            if not x.startswith("output_"):
                continue
            if CowrieConfig.getboolean(x, "enabled") is False:
                continue
            engine: str = x.split("_")[1]
            try:
                output = __import__(f"cowrie.output.{engine}", globals(),
                                    locals(), ["output"]).Output()
                log.addObserver(output.emit)
                self.output_plugins.append(output)
                log.msg(f"Loaded output engine: {engine}")
            except ImportError as e:
                log.err(
                    f"Failed to load output engine: {engine} due to ImportError: {e}"
                )
                log.msg(
                    f"Please install the dependencies for {engine} listed in requirements-output.txt"
                )
            except Exception:
                log.err()
                log.msg(f"Failed to load output engine: {engine}")

        self.topService = service.MultiService()
        application = service.Application("cowrie")
        self.topService.setServiceParent(application)

        # initialise VM pool handling - only if proxy AND pool set to enabled, and pool is to be deployed here
        # or also enabled if pool_only is true
        backend_type: str = CowrieConfig.get("honeypot",
                                             "backend",
                                             fallback="shell")
        proxy_backend: str = CowrieConfig.get("proxy",
                                              "backend",
                                              fallback="simple")

        if (backend_type == "proxy"
                and proxy_backend == "pool") or self.pool_only:
            # in this case we need to set some kind of pool connection

            local_pool: bool = (CowrieConfig.get("proxy",
                                                 "pool",
                                                 fallback="local") == "local")
            pool_host: str = CowrieConfig.get("proxy",
                                              "pool_host",
                                              fallback="127.0.0.1")
            pool_port: int = CowrieConfig.getint("proxy",
                                                 "pool_port",
                                                 fallback=6415)

            if local_pool or self.pool_only:
                # start a pool locally
                f = PoolServerFactory()
                f.tac = self

                listen_endpoints = get_endpoints_from_section(
                    CowrieConfig, "backend_pool", 6415)
                create_endpoint_services(reactor, self.topService,
                                         listen_endpoints, f)

                pool_host = "127.0.0.1"  # force use of local interface

            # either way (local or remote) we set up a client to the pool
            # unless this instance has no SSH and Telnet (pool only)
            if (self.enableTelnet or self.enableSSH) and not self.pool_only:
                self.pool_handler = PoolHandler(pool_host, pool_port,
                                                self)  # type: ignore

        else:
            # we initialise the services directly
            self.pool_ready()

        return self.topService