Beispiel #1
0
 def team_player(ip):
     if APP_DEBUG:
         Log.info('CALLED: Add.team_player(' + str(ip) + ')')
     if not validators.is_ip(ip):
         Log.error(str(ip) + ' is not a valid ip address')
         return False
     return Add.__add__(keys.TEAM_PLAYER, ip)
Beispiel #2
0
 def submit_url(url):
     if APP_DEBUG:
         Log.info('CALLED: Set.submit_url(' + str(url) + ')')
     if not validators.is_url(url):
         Log.error(str(url) + ' is not a valid url')
         return False
     return Set.__set__(keys.SUBMIT_URL, url)
Beispiel #3
0
 def team_player(ip='*'):
     if APP_DEBUG:
         Log.info('CALLED: Remove.team_player(' + str(ip) + ')')
     if ip != '*' and not validators.is_ip(ip):
         Log.error(str(ip) + ' is not a valid ip address')
         return False
     return Remove.__remove__(keys.TEAM_PLAYER, ip)
Beispiel #4
0
 def game_server(ip):
     if APP_DEBUG:
         Log.info('CALLED: Set.game_server(' + str(ip) + ')')
     if not validators.is_ip(ip):
         Log.error(str(ip) + ' is not a valid ip address')
         return False
     return Set.__set__(keys.GAME_SERVER, ip)
Beispiel #5
0
 def my_ip(ip):
     if APP_DEBUG:
         Log.info('CALLED: Set.my_ip(' + str(ip) + ')')
     if not validators.is_ip(ip):
         Log.error(str(ip) + ' is not a valid ip address')
         return False
     return Set.__set__(keys.MY_IP, ip)
Beispiel #6
0
        def _deep_inject_form(href, depth=1):
            # Check the domain
            if href in parsed_forms or \
                    urlparse(href).netloc != base_url or \
                    (max_depth is not None and depth > max_depth):
                return ''

            # Visit the current href
            parsed_relevant, request_cookies = HtmlParser.relevant_parse(href)
            parsed_forms[href] = HtmlParser.find_forms(parsed_relevant, href)

            # Find adjacent links
            links = HtmlParser.find_links(parsed_relevant)

            if len(parsed_forms) % 10 == 0:
                Log.info('Writing result in ' + out_file + '...')
                JsonSerializer.set_dictionary(parsed_forms, out_file)

            # Visit adjacent links
            for link in links:
                # print('link: '+link)
                child_request_cookies = _deep_inject_form(link, depth + 1)
                if len(child_request_cookies) > len(request_cookies):
                    request_cookies = child_request_cookies

            return request_cookies
Beispiel #7
0
 def multi_sequential_requests(urls: list,
                               request_type: str = Type.GET,
                               data=None,
                               json: dict or list = None,
                               headers: dict = None) -> dict:
     """
     Make multiple sequential requests
     :param urls: The list of target urls
     :param request_type: get|post|put|patch|delete
     :param data: (optional) Dictionary, list of tuples, bytes, or file-like
         object to send in the body of the :class:`Request`
     :param json: (optional) json data to send in the body of the :class:`Request`
     :param headers: The headers to send
     :return A dictionary of responses like {'url_1': <response>, 'url_2': <response>, ...}
     """
     if APP_DEBUG:
         Log.info('CALLED: multi_request(' + str(urls) + ', ' +
                  str(request_type) + ', ' + str(data) + ')')
     request_type = request_type.lower()
     response_dict = dict()
     for url in urls:
         response = HttpRequest.request(url, request_type, data, json,
                                        headers)
         if response is None:
             continue
         response_dict[url] = response
         if APP_DEBUG:
             try:
                 print(response.json())
             except (JSONDecodeError, SimpleJSONDecodeError):
                 print(response.text)
     return response_dict
Beispiel #8
0
 def server_to_defend(ip):
     if APP_DEBUG:
         Log.info('CALLED: Add.server_to_defend(' + str(ip) + ')')
     if not validators.is_ip(ip):
         Log.error(str(ip) + ' is not a valid ip address')
         return False
     return Add.__add__(keys.SERVER_TO_DEFEND, ip)
Beispiel #9
0
 def server_to_defend(ip='*'):
     if APP_DEBUG:
         Log.info('CALLED: Remove.server_to_defend(' + str(ip) + ')')
     if ip != '*' and not validators.is_ip(ip):
         Log.error(str(ip) + ' is not a valid ip address')
         return False
     return Remove.__remove__(keys.SERVER_TO_DEFEND, ip)
Beispiel #10
0
    def try_inject_forms(forms: dict,
                         cookies: str = '',
                         delay: int = 1,
                         random_agent: bool = False) -> dict:
        """
        Try injection with all provided forms
        :param forms: dict A dictionary of { "<url>": [ <parsed_form_1>, <parsed_form_2>, ... ], ... }
        :param cookies: str the request cookies
        :param delay: int The delay on each request
        :param random_agent: True if set a random agent for each sqlmap request
        :rtype: dict
        """
        sqlmap_tasks = dict()
        Log.info('Trying injection with cookies: ' + str(cookies))
        for url, page_forms in forms.items():
            page_forms: list  # The forms in page returned by url
            for page_form in page_forms:
                page_form: dict  # The attributes and inputs of form
                action: str = page_form.get('action')
                inputs: dict = page_form.get('inputs')
                method: str = page_form.get('method')

                if random_agent:
                    agent = None
                else:
                    agent = HttpRequest.default_agent()

                task_options = {
                    'dbms': 'MySQL',
                    'cookie': cookies,
                    'agent': agent,
                    'referer': url,
                    'delay': delay,
                    'randomAgent': random_agent,
                    'method': method,
                    'url': action,
                    'data': SqlmapClient.__get_data(inputs)
                }

                csrf_token = SqlmapClient.__get_csrf_token(inputs)
                if csrf_token is not None:
                    csrf_token_name = csrf_token.get('name')
                    task_options.update({
                        'csrfUrl': url,
                        'csrfMethod': HttpRequest.Type.GET,
                        'csrfToken': csrf_token_name,
                    })

                # for key, value in task_options.items():
                #     print('---------- ' + key + ': ----------')
                #     print(value)

                sqlmap_task = SqlmapClient._task_new()
                sqlmap_task.option_set(task_options)
                sqlmap_tasks[sqlmap_task.id] = sqlmap_task

                sqlmap_task.scan_start()

        return sqlmap_tasks
Beispiel #11
0
 def browser_target():
     """
     The function that launch the browser
     """
     set_owner_process(user)
     Log.info('Launching browser with User: '******'Web browser opened')
Beispiel #12
0
def django_gui():
    sys.path.insert(0, os.path.dirname(__file__))
    bind_host = _get_bind_socket()
    Log.info("Starting " + str(APP_NAME) + ' GUI')
    sys.argv = [sys.argv[0], 'web.wsgi', '-b', bind_host]
    django_cmd(['migrate'])
    _launch_browser(bind_host)
    gunicorn_run()
Beispiel #13
0
 def get(self, request, *args, **kwargs):
     """
     :type request: django.core.handlers.wsgi.WSGIRequest
     :return: django.http.HttpResponse
     """
     request_params: dict = request.GET.dict()
     job_id = request_params.get('job_id')
     Log.info("Showing job #" + str(job_id))
     return render(request, self.template_name)
 def kill(self, sig: int):
     """
     Send a signal to process which is running this job
     :param sig: The signal as integer (eg. 9 for SIGKILL)
     """
     Log.info("Sending signal " + str(sig) + " to job #" + str(self.id) + ' (' + str(self.pid) + ')')
     self.status = sig
     os.kill(self.pid, sig)
     self.save()
     Log.success("Signal " + str(sig) + " sent to job #" + str(self.id) + ' (' + str(self.pid) + ')')
Beispiel #15
0
    def deep_inject_form(url, max_depth, listen: bool = False) -> dict:
        """
        Search a form in the page returned by url.
        If it doesn't find a form, or the injection can't be done, it visit the website in search for other forms
        :param listen: True if this method should listen and print the SQL tasks, otherwise False
        :param url: str The url to visit
        :param max_depth: int The max depth during the visit
        :return A dictionary of SQL injection tasks
        """

        base_url = urlparse(url).netloc
        parsed_forms = dict()
        out_file = APP_STORAGE_OUT + '/' + now(
        ) + '_DEEP_FORMS_' + base_url + '.json'

        def _deep_inject_form(href, depth=1):
            # Check the domain
            if href in parsed_forms or \
                    urlparse(href).netloc != base_url or \
                    (max_depth is not None and depth > max_depth):
                return ''

            # Visit the current href
            parsed_relevant, request_cookies = HtmlParser.relevant_parse(href)

            # Find forms in page
            parsed_forms[href] = HtmlParser.find_forms(parsed_relevant, href)

            # Find adjacent links
            links = HtmlParser.find_links(parsed_relevant)

            if len(parsed_forms) % 10 == 0:
                Log.info('Writing result in ' + out_file + '...')
                JsonSerializer.set_dictionary(parsed_forms, out_file)

            # Visit adjacent links
            for link in links:
                # print('link: '+link)
                child_request_cookies = _deep_inject_form(link, depth + 1)
                if len(child_request_cookies) > len(request_cookies):
                    request_cookies = child_request_cookies

            return request_cookies

        cookies = _deep_inject_form(url)
        Log.info('Writing result in ' + out_file + '...')
        JsonSerializer.set_dictionary(parsed_forms, out_file)
        Log.success('Result wrote in ' + out_file)
        Log.success('Website crawled! Found ' + str(len(parsed_forms)) +
                    ' pages')
        tasks = SqlmapClient.try_inject_forms(parsed_forms, cookies)
        if listen:
            SqlInjection.__listen_tasks(tasks)
        return tasks
Beispiel #16
0
 def __init__(self, host: str = DEFAULT_HOST, port: int = DEFAULT_PORT):
     """
     :param host: The host
     :param port: The port
     """
     self.host = host
     self.port = port
     self.base_url = 'http://' + self.host + ':' + str(port)
     # Start the sqlmap-api server in a parallel thread
     Log.info("Starting sqlmap-api server in a parallel thread")
     MultiTask.multithread(sqlmap_server, (self.host, self.port), True, 1)
     while not check_socket(self.host, self.port):
         # Wait sqlmap-api server
         sleep(0.1)
     Log.success("Sqlmap-api server started!")
Beispiel #17
0
 def request(url: str,
             request_type: str = HttpRequest.Type.GET,
             json: dict or list = None) -> dict:
     """
     Send a request to sqlmap-api server and then load the data json as dict
     :param url: The sqlmap-api url (eg. "http://127.0.0.1:8775/task/new")
     :param request_type: get|post|put|patch|delete
     :param json: The json to send
     :rtype: dict
     """
     response = HttpRequest.request(url, request_type, json=json)
     r_data = JsonSerializer.load_json(response.text)
     Log.info('Response data of ' + url + ': ' + str(r_data))
     if not r_data['success']:
         Log.error('Response data of ' + url + ' has { success: False }')
         raise requests.RequestException('Request to ' + url + ' failed')
     return r_data
Beispiel #18
0
 def kill(self, sig: int):
     """
     Send a signal to process which is running this job
     :param sig: The signal as integer (eg. 9 for SIGKILL)
     """
     if self.status == sig:
         return
     Log.info("Sending signal " + str(sig) + " to job #" + str(self.id) +
              ' (' + str(self.pid) + ')')
     self.status = sig
     try:
         os.kill(self.pid, sig)
     except ProcessLookupError:
         # Process does not exists
         pass
     self.save()
     Log.success("Signal " + str(sig) + " sent to job #" + str(self.id) +
                 ' (' + str(self.pid) + ')')
Beispiel #19
0
 def get(self, request, *args, **kwargs):
     """
     :type request: django.core.handlers.wsgi.WSGIRequest
     :return: django.http.HttpResponse
     """
     if not util.is_root():
         return render(request,
                       self.error_templates.get('root_required'))
     request_params: dict = request.GET.dict()
     try:
         sniffing_job_id = int(request_params.get('id'))
     except (ValueError, TypeError):
         return redirect('/sniffing')
     Log.info("Showing job #" + str(sniffing_job_id))
     try:
         sniffing_job = SniffingJobModel.objects.get(id=sniffing_job_id)
     except ObjectDoesNotExist:
         return redirect('/sniffing')
     return render(request, self.template_name, {'job': sniffing_job})
Beispiel #20
0
    def try_inject(forms: dict,
                   cookies: str = '',
                   delay: int = 0,
                   random_agent: bool = False) -> dict:
        """
        Try injection with all provided forms
        :param forms: dict A dictionary of { "<url>": [ <parsed_form_1>, <parsed_form_2>, ... ], ... }
        :param cookies: str the request cookies
        :param delay: int The delay on each request
        :param random_agent: True if set a random agent for each sqlmap request
        :rtype: dict
        """
        sqlmap_tasks = dict()
        Log.info('Trying injection with cookies: ' + str(cookies))
        for url, page_forms in forms.items():
            page_forms: list  # The forms in page returned by url
            for page_form in page_forms:
                page_form: dict  # The attributes and inputs of form
                action = page_form.get('action')
                inputs = page_form.get('inputs')
                method = page_form.get('method')
                # Foreach form, will created a new SqlmapTask
                pprint(inputs)
                sqlmap_task = SqlmapClient._task_new()
                sqlmap_task.option_set({
                    'cookie': cookies,
                    'agent': HttpRequest.default_agent(),
                    'referer': url,
                    'delay': delay,
                    'randomAgent': random_agent,
                    'method': method,
                    'url': action
                })
                sqlmap_task.option_get([
                    'referer', 'agent', 'referer', 'delay', 'randomAgent',
                    'method', 'url'
                ])
                sqlmap_tasks[sqlmap_task.id] = sqlmap_task

        return sqlmap_tasks
Beispiel #21
0
    def _get_job(self, request, redirect_url: str):
        """
        Show the requested job
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param redirect_url: The url to redirect the request in case of errors
        :return: django.http.HttpResponse
        """
        request_params: dict = request.GET.dict()

        try:
            job_id = int(request_params.get('id'))
        except (ValueError, TypeError) as e:
            Log.error(str(e))
            return redirect(redirect_url)

        Log.info("Showing job #" + str(job_id))

        try:
            job = self.model_class.objects.get(id=job_id)
        except ObjectDoesNotExist:
            return redirect(redirect_url)

        return render(request, self.template_name, {'job': job})
Beispiel #22
0
 def __init__(
         self,
         filters: str = None,
         src_file: str = None,
         dest_file: str = None,
         interfaces: list = None,
         limit_length: int = None,
         pkt_count: int = None,
         callback=None
 ):
     """
     Packet capture method
     :param filters: https://wiki.wireshark.org/DisplayFilters
     :param src_file: Il file .pcap da cui leggere i pacchetti ascoltati (o None, per Live sniffing)
     :param dest_file: Il file in cui scrivere il .pcap dei pacchetti ascoltati (o None)
     :param interfaces: The list of interfaces to sniff (or None, to sniff all interfaces)
     :param limit_length: The limit length of each packet field (they will be truncated), or None
     :param pkt_count: Max packets to sniff, or None
     :param callback: The callback method to call (or None) (@see PcapSniffer._user_callback_example)
     """
     root_required()
     self.count = 0  # Sniffed packets
     self.max_count = pkt_count
     # Prevents the mac manufacturer lookup sniffing
     self.filters = PcapSniffer._get_filters(filters)
     self.src_file = src_file
     self.dest_file = dest_file
     self.limit_length = limit_length
     self.user_callback = callback
     self.interfaces = interfaces
     Log.info('Analyzing filters: ' + str(self.filters))
     if self.src_file is not None:
         Log.info('Analyzing file: ' + self.src_file)
         self._capture = pyshark.FileCapture(
             input_file=self.src_file,
             display_filter=self.filters,
             output_file=self.dest_file,
             # include_raw=True,
             # use_json=True
             # debug=APP_DEBUG
         )
     else:
         Log.info('Analyzing live traffic')
         self._capture = pyshark.LiveCapture(
             interface=self.interfaces,
             display_filter=self.filters,
             output_file=self.dest_file,
             # include_raw=True,
             # use_json=True
             # debug=APP_DEBUG
         )
Beispiel #23
0
 def server_to_attack():
     if APP_DEBUG:
         Log.info('CALLED: Get.server_to_attack()')
     return Get.__get__(keys.SERVER_TO_ATTACK)
Beispiel #24
0
 def submit_url():
     if APP_DEBUG:
         Log.info('CALLED: Get.submit_url()')
     return Get.__get__(keys.SUBMIT_URL)
Beispiel #25
0
 def game_server():
     if APP_DEBUG:
         Log.info('CALLED: Get.game_server()')
     return Get.__get__(keys.GAME_SERVER)
Beispiel #26
0
 def flag_regex():
     if APP_DEBUG:
         Log.info('CALLED: Get.flag_regex()')
     return Get.__get__(keys.FLAG_REGEX)
Beispiel #27
0
 def print_response(response, limit=1000):
     """
     :param response: The response to print
     :param limit: The limit data length before truncate that
     """
     Log.info(str(response.url))
     Log.info('      |--- status_code: ' + str(response.status_code))
     Log.info('      |--- encoding: ' + str(response.encoding))
     Log.info('      |--- headers:')
     for key, value in response.headers.items():
         Log.info('      |       |--- ' + str(key) + ': ' + str(value))
     Log.info('      |')
     try:
         json_body = response.json()
         Log.info('      |-- data: ' + str(json_body))
     except ValueError:
         data = str(response.text)
         if len(data) > limit:
             data = '[truncated]' + data[0:limit]
         Log.info('      |-- data: ' + data)
Beispiel #28
0
 def my_interface(interface):
     if APP_DEBUG:
         Log.info('CALLED: Set.my_interface(' + str(interface) + ')')
     return Set.__set__(keys.MY_INTERFACE, interface)
Beispiel #29
0
 def team_token(token):
     if APP_DEBUG:
         Log.info('CALLED: Set.team_token(' + str(token) + ')')
     return Set.__set__(keys.TEAM_TOKEN, token)
Beispiel #30
0
 def flag_regex(regex):
     if APP_DEBUG:
         Log.info('CALLED: Set.flag_regex(' + str(regex) + ')')
     return Set.__set__(keys.FLAG_REGEX, regex)