Example #1
0
def new(req):
    response = HttpResponse()
    response['Content-type'] = "text/plain"

    #Replace dangerous commands
    command = re.sub(r"[\\;|`&]", "", req.POST['command'])
    if req.session.user.is_permitted(command):
        try:
            nmap_version = os.system("nmap --version")
            nmapCommand = NmapCommand(command)
            instance = server.currentInstance
            resourceID = instance.addResource(nmapCommand)
            assert isinstance(instance, UmitWebServer)
            th = server.currentInstance.fireResourceEvent(
                resourceID, "run_scan")
            #instance.updateResource(resourceID, [nmapCommand, th])

            req.session['command_' + resourceID] = command
            req.session['profile_' + resourceID] = req.POST['profile_name']
            req.session['target_' + resourceID] = req.POST['target']
            response.write(
                "{'result': 'OK', 'status': 'RUNNING', 'id': '%s'}" %
                resourceID)
        except Exception, e:
            response.write("{'result': 'FAIL', 'status': '%s'}" %
                           str(e).replace("'", "\\'"))
        return response
Example #2
0
    def runTest(self):
        r = HttpResponse("", "text/plain")
        cookies = {}
        files = {}
        for key in self._req.COOKIES.keys():
            cookies[key] = self._req.COOKIES[key].value

        for key in self._req.FILES.keys():
            files[key] = {
                'name': self._req.FILES[key]['name'],
                'size': self._req.FILES[key]['size']
            }

        r_dict = {}
        r_dict['GET'] = self._req.GET
        r_dict['POST'] = self._req.POST
        r_dict['COOKIES'] = cookies
        r_dict['FILES'] = files
        #self.logger.debug("REQUEST received: %s" % str(vars(self._req)))
        session_items = self._req.session.items()
        session_attributes = {}
        map(lambda d: session_attributes.update(d), [{
            items[0]: items[1]
        } for items in session_items])
        r_dict['SESSION'] = session_attributes
        r.write(str(r_dict))
        return r
Example #3
0
def check(req, resource_id):
    response = HttpResponse()
    response['Content-type'] = "text/javascript"

    nmapCommand = server.currentInstance.getResource(resource_id)
    server_thread = None
    if isinstance(nmapCommand, list):
        nmapCommand, server_thread = nmapCommand
        assert isinstance(server_thread, ServerThread)

    assert isinstance(nmapCommand, NmapCommand)
    if nmapCommand is None:
        raise Http404

    if server_thread and len(server_thread.exceptions) > 0:
        server.currentInstance.removeResource(resource_id)
        raise Http500("Nmap command raised an exception!\n%s" % \
                      "\n".join(str(e) for e in server_thread.exceptions))

    output = nmapCommand.get_output()
    error = nmapCommand.get_error()
    if nmapCommand.scan_state():
        response.write("{'result': 'OK', 'status': 'RUNNING', " + \
                       "'output': {'text': '%s', 'error': '%s'}}" % \
                       (output.replace("'", "\\'").replace("\n", "\\n' + \n'"),
                        error.replace("'", "\\'").replace("\n", "\\n' + \n'")))
    else:
        profile = CommandProfile()
        parser = NmapParser()
        parser.set_xml_file(nmapCommand.get_xml_output_file())
        parser.parse()

        parser.profile_name = req.session['profile_' + resource_id]
        parser.target = req.session['target_' + resource_id]
        parser.nmap_command = req.session['command_' + resource_id]
        parser.profile = profile.get_command(parser.profile_name)
        parser.profile_hint = profile.get_hint(parser.profile_name)
        parser.profile_description = profile.get_description(
            parser.profile_name)
        parser.profile_annotation = profile.get_annotation(parser.profile_name)
        parser.profile_options = profile.get_options(parser.profile_name)
        try:
            parser.nmap_output = nmapCommand.get_raw_output()
        except:
            parser.nmap_output = "\\n".join(
                self.scan_result.get_nmap_output().split("\n"))
        #del parser['nmap']
        #parsed_scan = #str(__scan_to_json(parser))
        parsed_scan = ScanJsonParser(parser).parse()
        text_out = nmapCommand.get_output().replace("'", "\\'").replace(
            "\n", "\\n' + \n'")
        response.write("{'result': 'OK', 'status': 'FINISHED', 'output':" + \
                       " {'full': %s, 'plain': '%s'}}" % (parsed_scan, text_out))
        server.currentInstance.removeResource(resource_id)
        fname = mktemp()
        fresult = open(fname, "w", 0)
        parser.write_xml(fresult)
        req.session['scan_result_' + resource_id] = open(fname, 'r').read()

    return response
Example #4
0
    def runTest(self):
        r = HttpResponse("", "text/plain")

        try:
            self._req.session.destroy()
            r.write("{'result': 'OK'}")
        except Exception, ex:
            r.write("{'result': 'FAIL', 'message': '%s'}" % str(ex))
Example #5
0
 def runTest(self):
     r = HttpResponse("", "text/plain")
     
     try:
         self._req.session.destroy()
         r.write("{'result': 'OK'}")
     except Exception, ex:
         r.write("{'result': 'FAIL', 'message': '%s'}" % str(ex))
Example #6
0
 def runTest(self):
     r = HttpResponse("", "text/plain")
     try:
         test_attr = self._req.GET.get("name", "test")
         test_str = self._req.GET.get("value", "test_value")
         self._req.session[test_attr] = test_str
         r.write("{'result': 'OK'}")
     except Exception, ex:
         r.write("{'result': 'FAIL', 'message': '%s'}" % str(ex))
Example #7
0
 def runTest(self):
     r = HttpResponse("", "text/plain")
     try:
         test_attr = self._req.GET.get("name", "test")
         test_str  = self._req.GET.get("value", "test_value")
         self._req.session[test_attr] = test_str
         r.write("{'result': 'OK'}")
     except Exception, ex:
         r.write("{'result': 'FAIL', 'message': '%s'}" % str(ex))
Example #8
0
    def runTest(self):
        r = HttpResponse("", "text/plain")
        try:
            test_attr = self._req.GET.get("name", "test")
            del self._req.session[test_attr]
            r.write("{'result': 'OK'}")

        except Exception, ex:
            r.write("{'result': 'FAIL', 'message': '%s'}" % str(ex).replace("'", "\""))
def get_profiles(req):
    profile = CommandProfile()
    profiles = profile.sections()
    response = HttpResponse()
    response['Content-type'] = "text/plain"
    ret = []
    for section in profiles:
        ret.append([section, profile.get_command(section) % "<target>"])
    response.write(str(ret))
    return response
def get_profiles(req):
    profile = CommandProfile()
    profiles = profile.sections()
    response = HttpResponse()
    response['Content-type'] = "text/plain"
    ret = []
    for section in profiles:
        ret.append([section, profile.get_command(section) % "<target>"])
    response.write(str(ret))
    return response
Example #11
0
    def runTest(self):
        r = HttpResponse("", "text/plain")
        try:
            test_attr = self._req.GET.get("name", "test")
            del self._req.session[test_attr]
            r.write("{'result': 'OK'}")

        except Exception, ex:
            r.write("{'result': 'FAIL', 'message': '%s'}" %
                    str(ex).replace("'", "\""))
Example #12
0
def diff_colors(req):
    response = HttpResponse("", "text/plain")
    dc = DiffColors()
    data = []
    toHex = lambda value: "%0.2x" % floor(sqrt(value))
    logger.debug(tuple(map(toHex, dc.unchanged)))
    data.append("'unchanged': '#%s%s%s'" % tuple(map(toHex, dc.unchanged)))
    data.append("'added': '#%s%s%s'" % tuple(map(toHex, dc.added)))
    data.append("'modified': '#%s%s%s'" % tuple(map(toHex, dc.modified)))
    data.append("'not_present': '#%s%s%s'" % tuple(map(toHex, dc.not_present)))
    response.write("var diff_colors = {%s}" % ",".join(data))
    return response
def diff_colors(req):
    response = HttpResponse("", "text/plain")
    dc = DiffColors()
    data = []
    toHex = lambda value: "%0.2x" % floor(sqrt(value))
    logger.debug(tuple(map(toHex, dc.unchanged)))
    data.append("'unchanged': '#%s%s%s'" % tuple(map(toHex, dc.unchanged)))
    data.append("'added': '#%s%s%s'" % tuple(map(toHex, dc.added)))
    data.append("'modified': '#%s%s%s'" % tuple(map(toHex, dc.modified)))
    data.append("'not_present': '#%s%s%s'" % tuple(map(toHex, dc.not_present)))
    response.write("var diff_colors = {%s}" % ",".join(data))
    return response
Example #14
0
def serve_media(req, path):
    response = HttpResponse()
    
    filename = join(Path.media_dir, *(path.split("/")))
    
    if not exists(filename):
        raise Http404
    
    response['Content-type'] = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
    response['Content-type'] += '; charset=utf-8'
    cntFile = None
    if sys.platform == 'win32':
        if response['Content-type'].startswith("text"):
            cntFile = open(filename, 'r')
        else:
            cntFile = open(filename, 'rb')
    else:
        cntFile = open(filename, 'r')
    response.write(cntFile.read())
    return response
Example #15
0
def login(req):
    resp = HttpResponse()
    ctx = Context()
    if req.POST:
        resp['Content-type'] = "text/plain"
        user = ctx.get_user(req.POST['login'], req.POST['password'])
        
        if req.GET.has_key("json"):
            if user:
                req.session['umit_user'] = user
                resp.write('OK')
            else:
                resp.write('FAIL')
            return resp
        else:
            if user:
                req.session['umit_user'] = user
                return HttpResponseRedirect("/")
    else:
        resp.loadTemplate("login.html")
        return resp
Example #16
0
 def runTest(self):
     r = HttpResponse("", "text/plain")
     cookies = {}
     files = {}
     for key in self._req.COOKIES.keys():
         cookies[key] = self._req.COOKIES[key].value
     
     for key in self._req.FILES.keys():
         files[key] = {'name': self._req.FILES[key]['name'], 'size': self._req.FILES[key]['size']}
         
     r_dict = {}
     r_dict['GET'] = self._req.GET
     r_dict['POST'] = self._req.POST
     r_dict['COOKIES'] = cookies
     r_dict['FILES'] = files
     #self.logger.debug("REQUEST received: %s" % str(vars(self._req)))
     session_items = self._req.session.items()
     session_attributes = {}
     map(lambda d: session_attributes.update(d), [{items[0]: items[1]} for items in session_items])
     r_dict['SESSION'] = session_attributes
     r.write(str(r_dict))
     return r
Example #17
0
def new(req):
    response = HttpResponse()
    response["Content-type"] = "text/plain"

    # Replace dangerous commands
    command = re.sub(r"[\\;|`&]", "", req.POST["command"])
    if req.session.user.is_permitted(command):
        try:
            nmap_version = os.system("nmap --version")
            nmapCommand = NmapCommand(command)
            instance = server.currentInstance
            resourceID = instance.addResource(nmapCommand)
            assert isinstance(instance, UmitWebServer)
            th = server.currentInstance.fireResourceEvent(resourceID, "run_scan")
            # instance.updateResource(resourceID, [nmapCommand, th])

            req.session["command_" + resourceID] = command
            req.session["profile_" + resourceID] = req.POST["profile_name"]
            req.session["target_" + resourceID] = req.POST["target"]
            response.write("{'result': 'OK', 'status': 'RUNNING', 'id': '%s'}" % resourceID)
        except Exception, e:
            response.write("{'result': 'FAIL', 'status': '%s'}" % str(e).replace("'", "\\'"))
        return response
Example #18
0
def output_highlight(req):
    response = HttpResponse()
    response['Content-type'] = "text/javascript; charset=utf-8"
    highlight = JsOutputHighlight()
    attrDic = {}

    response.write("highlights = {};\n")
    for attr in ["closed_port", "date", "details", "filtered_port",
                 "hostname", "ip", "open_port", "port_list"]:
        attribute = getattr(highlight, attr)
        response.write("highlights['%s'] = {};\n" % attr)
        for index, value in enumerate(['bold', 'italic', 'underline', 'text', 'highlight', 'regex']):
            if type(attribute[index]) == ListType:
                propValue = "#%s%s%s" % tuple(map(lambda value: "%0.2x" % floor(sqrt(value)), attribute[index]))
            elif type(attribute[index]) == StringType:
                propValue = attribute[index].replace("\\", "\\\\")
            else:
                propValue = attribute[index]
            response.write("highlights['%s']['%s'] = '%s';\n" % (attr, value, propValue))
    return response
Example #19
0
def check(req, resource_id):
    response = HttpResponse()
    response["Content-type"] = "text/javascript"

    nmapCommand = server.currentInstance.getResource(resource_id)
    server_thread = None
    if isinstance(nmapCommand, list):
        nmapCommand, server_thread = nmapCommand
        assert isinstance(server_thread, ServerThread)

    assert isinstance(nmapCommand, NmapCommand)
    if nmapCommand is None:
        raise Http404

    if server_thread and len(server_thread.exceptions) > 0:
        server.currentInstance.removeResource(resource_id)
        raise Http500("Nmap command raised an exception!\n%s" % "\n".join(str(e) for e in server_thread.exceptions))

    output = nmapCommand.get_output()
    error = nmapCommand.get_error()
    if nmapCommand.scan_state():
        response.write(
            "{'result': 'OK', 'status': 'RUNNING', "
            + "'output': {'text': '%s', 'error': '%s'}}"
            % (
                output.replace("'", "\\'").replace("\n", "\\n' + \n'"),
                error.replace("'", "\\'").replace("\n", "\\n' + \n'"),
            )
        )
    else:
        profile = CommandProfile()
        parser = NmapParser()
        parser.set_xml_file(nmapCommand.get_xml_output_file())
        parser.parse()

        parser.profile_name = req.session["profile_" + resource_id]
        parser.target = req.session["target_" + resource_id]
        parser.nmap_command = req.session["command_" + resource_id]
        parser.profile = profile.get_command(parser.profile_name)
        parser.profile_hint = profile.get_hint(parser.profile_name)
        parser.profile_description = profile.get_description(parser.profile_name)
        parser.profile_annotation = profile.get_annotation(parser.profile_name)
        parser.profile_options = profile.get_options(parser.profile_name)
        try:
            parser.nmap_output = nmapCommand.get_raw_output()
        except:
            parser.nmap_output = "\\n".join(self.scan_result.get_nmap_output().split("\n"))
        # del parser['nmap']
        # parsed_scan = #str(__scan_to_json(parser))
        parsed_scan = ScanJsonParser(parser).parse()
        text_out = nmapCommand.get_output().replace("'", "\\'").replace("\n", "\\n' + \n'")
        response.write(
            "{'result': 'OK', 'status': 'FINISHED', 'output':"
            + " {'full': %s, 'plain': '%s'}}" % (parsed_scan, text_out)
        )
        server.currentInstance.removeResource(resource_id)
        fname = mktemp()
        fresult = open(fname, "w", 0)
        parser.write_xml(fresult)
        req.session["scan_result_" + resource_id] = open(fname, "r").read()

    return response