def read_config(self):
     response = ipc.sync_http_raw("GET", SOCK_CONFIG,
                                  "/get/section/NmapProbes")
     ipc.assert_response_valid(response, dict)
     self.nmap_probes = response["text"].copy()
     for key, value in self.nmap_probes.items():
         self.nmap.add_file(value)
Beispiel #2
0
def reload(args):
    resp = ipc.sync_http_raw("POST", http_socks["modules"], "/reload")
    if ipc.response_valid(resp, dict):
        print("Status: {}".format(resp["text"].get("status", "Unknown")))
    else:
        print("Error")
        print(resp)
Beispiel #3
0
def dump(args):
    client = args.client
    resp = ipc.sync_http_raw("GET", http_socks["database"], "/get/client/{}".format(client))
    if ipc.response_valid(resp, dict):
        dump_client(resp["text"])
    else:
        print("Unable to find information about client {}".format(client))
Beispiel #4
0
def stop(args):
    service = args.service
    if service == "all":
        stop_all()
    elif service in http_socks:
        _res = ipc.sync_http_raw("POST", http_socks[service], "/exit")
    else:
        print("Invalid service {}".format(service))
Beispiel #5
0
    async def reload_all(self, _request):
        options = ipc.sync_http_raw("GET", SOCK_CONFIG, "/get/section/Options")
        ipc.assert_response_valid(options, dict)
        options = self.parse_option(options["text"])

        self.modules.reload_all("modules/", options)

        return sanic.response.json(RETURN_OK)
Beispiel #6
0
    def refresh_config(self):
        response = ipc.sync_http_raw("GET", SOCK_CONFIG,
                                     "/get/variable/DNSAPI/root")
        ipc.assert_response_valid(response, dict)
        assert "root" in response["text"]
        root = response["text"]["root"]
        roots = root.split(",")

        response = ipc.sync_http_raw("GET", SOCK_CONFIG,
                                     "/get/section/ManageWebserver")
        ipc.assert_response_valid(response, dict)
        self.config = response["text"].copy()
        self.config["roots"] = roots
        assert isinstance(self.config, dict) and \
            "port" in self.config and \
            "bind" in self.config and \
            "redirect_initial" in self.config and \
            "redirect_attack" in self.config
Beispiel #7
0
def clients(args):
    resp = ipc.sync_http_raw("GET", http_socks["database"], "/get/clients")
    ids = resp["text"]
    if ipc.response_valid(resp, dict):
        for key, val in ids.items():
            print("{} ({} - {})".format(key, val.get("publicip", None), val["browser"]))
            for child in val["childs"]:
                print("\t{} ({}:{})".format(child["id"], child["ip"],
                                                   child["port"]))
Beispiel #8
0
    async def status(self, _request):
        port = self.main_server.get("port", 80)

        resp = ipc.sync_http_raw(
            "GET", "http://{}:{}".format(self.config["roots"][0], port),
            "/status")
        if isinstance(resp, dict) is True and resp.get(
                "text", {}).get("status") == "up":
            return sanic.response.json(RETURN_UP)
        return sanic.response.json({"status": "down"})
Beispiel #9
0
def modules(args):
    resp = ipc.sync_http_raw("GET", http_socks["modules"], "/modules/loaded")
    if ipc.response_valid(resp, dict):
        for key, val in resp["text"].items():
            print("{}:".format(key))
            for v in val:
                print("\t{}".format(v))
    else:
        print("error")
        print(resp)
Beispiel #10
0
def status(args):
    for key, val in http_socks.items():
        try:
            resp = ipc.sync_http_raw("GET", val, "/status")
        except:
            print("{} is unavailable".format(key))
            continue
        if ipc.response_valid(resp, dict):
            print("Status for {} - {}".format(key, resp["text"].get("status")))
        else:
            print("Received an invalid response {}".format(resp))
Beispiel #11
0
    def run(self):
        logger.info("Initializing module loader")
        self.socket = ipc.unix_socket(SOCKET_MODULES)

        # Get global options from config file
        options = ipc.sync_http_raw("GET", SOCK_CONFIG, "/get/section/Options")
        ipc.assert_response_valid(options, dict)
        options = self.parse_option(options["text"])

        # Get options for this class
        mod_options = ipc.sync_http_raw("GET", SOCK_CONFIG,
                                        "/get/section/Modules")
        ipc.assert_response_valid(mod_options, dict)
        self.options = mod_options["text"].copy()

        # Some values must be present in options
        assert "safety" in self.options
        assert "intrusiveness" in self.options

        if "default_passes" in self.options:
            self.options["default_passes"] = misc.file2json(
                self.options["default_passes"])
            logger.info("Loaded default passes")

        # Try and convert string to enums
        try:
            self.options["safety"] = Safety[self.options["safety"]]
            self.options["intrusiveness"] = Intrusiveness[
                self.options["intrusiveness"]]
        except:
            logger.critical(
                "Safety or intrusiveness values could not be converted to enum"
            )
            return

        self.modules.parse_mod_dir("modules/", options)

        self.app = Sanic("ModuleLoader")
        self.add_routes()
        logger.info("Done initializing module loader")
        self.app.run(sock=self.socket, access_log=False)
Beispiel #12
0
 def wait_webserver(self, ip, port, count=10, delay=0.5):
     for i in range(0, count):
         logger.debug("Checking if server at {}:{} is up".format(ip, port))
         try:
             resp = ipc.sync_http_raw("GET",
                                      "http://127.0.0.1:{}".format(port),
                                      "/status")
         except:
             resp = None
             pass
         if ipc.response_valid(resp, dict):
             return True
         time.sleep(delay)
     return False
Beispiel #13
0
def stop_all():
    port = get_value("Options", "LPORT")
    if port == None:
        print("Unable to get port of shell")
    try:
        port = int(port)
    except:
        print("Unable to convert port {} to int".format(port))
        sys.exit(1)
    print("Stopping shell at port {}".format(port))
    procs.stop_shell(port)

    for key, val in http_socks.items():
        print("Stopping {}".format(key))
        _res = ipc.sync_http_raw("POST", val, "/exit")
Beispiel #14
0
def wait_service_up(url, attempts=10, delay=0.5):
    """
    Keep running until service is up or service has failed to start.
    """
    for _i in range(0, attempts):
        try:
            logger.debug("Checking if service: {} is up".format(url))
            resp = ipc.sync_http_raw("GET", url, "/status")
            if resp["text"]["status"] == "up":
                return True
        except:
            logger.debug("Service URL: {} was not detected as up".format(url))
            pass
        time.sleep(delay)
    return False
Beispiel #15
0
    def run(self):
        response = ipc.sync_http_raw(
            "GET",
            SOCK_CONFIG,
            "/get/variable/Database/storage"
        )
        assert isinstance(response, dict) and "text" in response
        dbfile = response["text"].get("storage", None)
        assert dbfile is not None
        self.db = TinyDB(dbfile)

        self.socket = ipc.unix_socket(SOCKET_DATABASE)
        self.app = Sanic("Database")
        self.add_routes()
        logger.info("Initialized database module")
        self.app.run(sock=self.socket, access_log=False)
Beispiel #16
0
def purge(args):
    print("Purging database")
    resp = ipc.sync_http_raw("POST", http_socks["database"], "/purge")
    if ipc.response_valid(resp, dict):
        print("Result {}".format(resp["text"]))
Beispiel #17
0
def get_value(section, key):
    resp = ipc.sync_http_raw("GET", SOCK_CONFIG, "/get/variable/{}/{}".format(section, key))
    if ipc.response_valid(resp, dict):
        return resp["text"].get(key, None)
    return None
Beispiel #18
0
def stop_services(stoplist):
    for url in stoplist:
        logger.info("Stopping service with URL: {}".format(url))
        ipc.sync_http_raw("POST", url, "/exit")
Beispiel #19
0
def start_webserver(args):
    port = int(args.port)
    res = ipc.sync_http_raw("POST", http_socks["webserver"], "/start/{}".format(port))
    print(res["text"])
Beispiel #20
0
    def run(self, sock, port):
        logger.info("Starting web server on port {}".format(port))
        self.port = port

        response = ipc.sync_http_raw("GET", SOCK_CONFIG, "/get/section/Scan")
        ipc.assert_response_valid(response, dict)
        self.config = response["text"]
        self.set_default_options()

        # Get all static files to serve
        response = ipc.sync_http_raw("GET", SOCK_CONFIG,
                                     "/get/section/Webserver")
        ipc.assert_response_valid(response, dict)
        assert "static" in response["text"]
        self.config["files2serve"] = []
        for entry in response["text"]["static"].split(";"):
            try:
                webname, path = entry.split(":")
                self.config["files2serve"].append((webname, path))
            except:
                logger.critical(
                    "Entry: '{}' in config file is invalid".format(entry))
                sys.exit(1)

        self.client_managed = misc.string2bool(response["text"].get(
            "client_managed", "False"))
        assert isinstance(self.client_managed, bool)

        assert "interface" in response["text"]
        self.config["interface"] = response["text"]["interface"]

        self.config["debug_mode"] = misc.string2bool(response["text"].get(
            "debug_mode", "False"))
        assert isinstance(self.config["debug_mode"], bool)

        if "redirect_index" in response["text"]:
            self.config["redirect_index"] = response["text"].get(
                "redirect_index")

        response = ipc.sync_http_raw("GET", SOCK_CONFIG,
                                     "/get/variable/DNSAPI/root")
        ipc.assert_response_valid(response, dict)
        assert "root" in response["text"]
        self.root = response["text"]["root"]

        self.app = Sanic("Webserver")
        self.cors = CORS(self.app,
                         automatic_options=True,
                         resources={r"/*": {
                             "origins": "*"
                         }})

        if self.add_routes() is not True:
            logger.fatal("Unable to add routes")
            return False

        # Add some middleware to the webserver

        @self.app.middleware('request')
        async def all_requests(request):
            logger.debug("Web request {} -> {}".format(request.ip,
                                                       request.path))

        @self.app.middleware('request')
        async def check_host(request):
            host = request.host.split(":")[0]
            if host != self.root and host.endswith(".{}".format(
                    self.root)) is False:
                logger.warning(
                    "Tried to access with invalid hostname {} from {}".format(
                        request.host, request.ip))
                return sanic.response.text("Invalid request", status=500)

        # Catch some exceptions to avoid cluttering the log file
        @self.app.exception(sanic.exceptions.NotFound)
        def custom_404(request, exception):
            logger.error("Resource not found {} from client {}".format(
                request.path, request.ip))
            return sanic.response.text("Requested URL {} not found".format(
                request.path),
                                       status=404)

        logger.info("Started web server on port {}".format(port))
        self.app.run(sock=sock, access_log=False)
Beispiel #21
0
 def _stop_webserver(self, webserver):
     ipc.sync_http_raw("POST",
                       "http://localhost:{}".format(webserver["port"]),
                       "/exit")
     webserver["proc"].join()
     webserver["socket"].close()