• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python hosts.get_host_record函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中skaldship.hosts.get_host_record函数的典型用法代码示例。如果您正苦于以下问题:Python get_host_record函数的具体用法?Python get_host_record怎么用?Python get_host_record使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_host_record函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: update_db

def update_db(f_type=None, record=None, data=None, filename=None, ipaddr=None):
    """Adds or updates an existing record id"""

    if record is None:
        # inserting a new record into the database
        if ipaddr is None:
            print "ERROR: No IPv4 address provided"
            return False

        host_id = get_host_record(ipaddr)
        if not host_id:
            print "ERROR: %s is not a host in the database" % (ipaddr)
            return False

        try:
            db.t_evidence.insert(
                f_hosts_id = host_id.id,
                f_filename = filename,
                f_data = data,
                f_type = f_type
            )
        except Exception, e:
            print "ERROR inserting record:", e
            db.commit()
            return False
开发者ID:KvasirSecurity,项目名称:Kvasir,代码行数:25,代码来源:update_evidence.py


示例2: add

def add():
    if request.args(0):
        record = get_host_record(request.args(0))
        db.t_netbios.f_hosts_id.default = record.id
    response.title = "%s :: Add NetBIOS Data" % (settings.title)
    form=crud.create(db.t_netbios, next='edit/[id]', message="NetBIOS data added")
    return dict(form=form)
开发者ID:KvasirSecurity,项目名称:Kvasir,代码行数:7,代码来源:netbios.py


示例3: process_screenshot_loot

def process_screenshot_loot(loot_list=[], msf=None):
    """
    Takes an array of loot records in loot_list, downloads the screenshot and
    adds it to the database
    """

    db = current.globalenv['db']
    #cache = current.globalenv['cache']

    loot_count = 0
    for loot_id in loot_list:
        loot = msf.loot_download(loot_id)
        ip = loot_list[loot_id]
        if loot['ltype'] != 'host.windows.screenshot':
            logging.error(" [!] %s/%s is not a screenshot, it is a %s" % (ip, loot['name'], loot['ltype']))
        else:
            record = get_host_record(ip)
            if not record:
                logging.error(" [!] Cannot find record for %s" % ip)
                continue

            db.t_evidence.update_or_insert(
                f_hosts_id=record.id,
                f_filename="%s-msfpro-%s.png" % (ip, loot['name']),
                f_evidence="%s-msfpro-%s.png" % (ip, loot['name']),
                f_data=loot['data'],
                f_type='Screenshot',
                f_text='From MetasploitPRO'
            )
            db.commit()
            loot_count += 1

    return loot_count
开发者ID:j4schur,项目名称:Kvasir,代码行数:33,代码来源:pro.py


示例4: add

def add():
    if request.args(0) is not None:
        record = get_host_record(request.args(0))
        db.t_evidence.f_hosts_id.default = record.id
    else:
        record = None

    if request.extension == 'load':
        buttons=[]
    else:
        buttons=['submit']

    if record:
        form=SQLFORM(db.t_evidence, buttons=buttons, upload=URL('download'), fields=['f_type', 'f_other_type', 'f_text', 'f_evidence'],
                     _action=URL('add', args=[ record.id ]), _id="evidence_add_form")
    else:
        form=SQLFORM(db.t_evidence, buttons=buttons, upload=URL('download'), fields=['f_hosts_id', 'f_type', 'f_other_type', 'f_text', 'f_evidence'],
                     _action=URL('add'), _id="evidence_add_form")

    if request.vars.f_evidence is not None:
        form.vars.f_filename = request.vars.f_evidence.filename
    if form.accepts(request.vars, session):
        response.flash = "Evidence added"
        response.headers['web2py-component-command'] = 'evidencetable.fnReloadAjax();'
        return ""
    elif form.errors:
        response.flash = "Error in form submission"
        return TABLE(*[TR(k, v) for k, v in form.errors.items()])

    db.t_evidence.f_hosts_id.default = None
    response.title = "%s :: Add Evidence" % (settings.title)
    return dict(form=form)
开发者ID:KvasirSecurity,项目名称:Kvasir,代码行数:32,代码来源:evidence.py


示例5: mass_assign

def mass_assign():
    """
    Upload a CSV file that mass-assigns OS records to Hosts. If a CPE record is provided, look it up in the DB.
    If not lookup the vendor and product in the DB

    File format:

     ipaddress,cpe,family,vendor,product,certainty,osclass

    """
    response.title = "%s :: Mass OS Update" % (settings.title)
    form = SQLFORM.factory(
        Field('osfile', 'upload', uploadfolder=os.path.join(request.folder, 'data', 'misc'), label=T('OS CSV File')),
    )

    if form.accepts(request.vars,session):
        filename = os.path.join(request.folder,'data/misc',form.vars.osfile)
        import csv
        from skaldship.cpe import lookup_cpe
        #from skaldship.general import
        counter = 0
        with open(filename, "rb") as f:
            for row in csv.reader(f):
                host_id = get_host_record(row[0])
                if not host_id:
                    print "[%s] - Record not found" % (row[0])
                    continue

                cpe = row[1]
                family = row[2]
                vendor = row[3]
                product = row[4]
                certainty = row[5]
                osclass = row[6]
                os_id = None
                if cpe:
                    # we have a cpe entry from xml! hooray!
                    cpe_name = cpe.replace('cpe:/o:', '')
                    os_id = lookup_cpe(cpe_name)
                #else:
                    # no cpe attribute in xml, go through our messsy lookup
                #    os_id = guess_cpe_os(os_rec)

                if os_id:
                    db.t_host_os_refs.insert(f_certainty=certainty,
                                             f_family=family,
                                             f_class=osclass,
                                             f_hosts_id=host_id,
                                             f_os_id=os_id)
                    db.commit()
                    counter += 1
                else:
                    logger.error("OS not found: %s" % (row))
        response.flash = "%s Hosts updated with new OS records" % (counter)

    elif form.errors:
        response.flash = 'Error in form'

    return dict(form=form)
开发者ID:SecurityTW,项目名称:Kvasir,代码行数:59,代码来源:os.py


示例6: add

def add():
    if request.args(0) is not None:
        record = get_host_record(request.args(0))
        db.t_snmp.f_hosts_id.default = record.id

    response.title = "%s :: Create SNMP Entry" % (settings.title)
    form=crud.create(db.t_snmp,next='edit/[id]')
    db.t_snmp.f_hosts_id.default = None
    return dict(form=form)
开发者ID:LucaBongiorni,项目名称:Kvasir,代码行数:9,代码来源:snmp.py


示例7: by_host

def by_host():
    """
    Returns a list of OS records based upon an host identifier
    (id, ipv4, ipv6)
    """
    if request.args(0) is None: redirect(URL('default', 'error', vars={'msg': T('Host record not found')}))

    record = get_host_record(request.args(0))

    if record is None:
        redirect(URL('default', 'error', vars={'msg': T('Host record not found')}))

    response.title = "%s :: SNMP Records for %s" % (settings.title, host_title_maker(record))
    snmplist = db(db.t_snmp.f_hosts_id==record.id).select()

    aaData = []
    if request.extension == "json":
        for snmp in snmplist:
            # datatables json requires aaData to be specificly formatted
            aaData.append({
                '0': A("edit", _target="snmp_update_%s" % (snmp.id), _href=URL('edit',extension='html',args=snmp.id)).xml(),
                '1': snmp.f_community,
                '2': snmp.f_version,
                '3': snmp.f_access,
                'DT_RowId': snmp.id,
            })

        result = { 'sEcho': request.vars.sEcho,
                   'iTotalRecords': len(aaData),
                   'aaData': aaData,
                   }

        return result

    form = TABLE(THEAD(TR(TH(T('ID'), _width="5%"),
                          TH(T('Community')),
                          TH(T('Version')),
                          TH(T('Access')),
                          )  ),
                 _class="datatable",
                 _id="snmptable",
                 _style="width:100%")

    add = AddModal(
        db.t_snmp, 'Add', 'Add', 'Add SNMP String',
        fields=[ 'f_community', 'f_version', 'f_access'],
        cmd='snmptable.fnReloadAjax();'
    )
    db.t_snmp.f_hosts_id.default = record.id
    db.t_snmp.id.comment = add.create()

    return dict(form=form, host=record, add=add)
开发者ID:LucaBongiorni,项目名称:Kvasir,代码行数:52,代码来源:snmp.py


示例8: process_file

def process_file(filename=None, asset_group=None, engineer=None):

    # Upload and process hping Scan file
    from skaldship.hosts import get_host_record, do_host_status, add_or_update

    log(" [*] Processing hping scan file %s" % filename)

    hoststats = 0
    nodefields = {'f_engineer': engineer, 'f_asset_group': asset_group, 'f_confirmed': False}

    svc_db = db.t_services

    host_ip = None
    ICMP_type = ''
    answer_ip = ''

    with open(filename) as f:
        for line in f:
            if "IP: " in line:
                host_ip = line.split()[1]
                if IS_IPADDRESS()(host_ip)[1] == None:
                    nodefields['f_ipaddr'] = host_ip
                    host_rec = add_or_update(nodefields, update=True)
                    hoststats += 1
                else:
                    log(" [!] ERROR: Not a valid IP Address (%s)" % host_ip, logging.ERROR)
            if "[*] " in line:
                ICMP_type = line.split()[1]
            if "ip=" in line:
                ip = line.split('=')[2]
                answer_ip = ip.split()[0]
            if "transmitted" in line:
                packets = line.split()
                if packets[0] == packets[3]:
                    if answer_ip != host_ip:
                        response = T("No")
                    else:
                        response = T("Yes")
                else:
                    response = T("No")
                get_id = get_host_record(host_ip)
                svc_db.update_or_insert(
                    f_hosts_id=get_id.id, f_proto='ICMP', f_number='0', f_status=response, f_name=ICMP_type
                )
                db.commit()
    f.close()
    do_host_status(asset_group=asset_group)
    log(" [*] Import complete, %s hosts added/updated" % hoststats)
开发者ID:zbyufei,项目名称:Kvasir,代码行数:48,代码来源:hping.py


示例9: add_host

    def add_host(self, address=None, ports=None):
        """Looks up the host and adds the result to the query"""
        host_rec = get_host_record(address)
        if host_rec is None:
            sys.stderr.write("%s invalid address!\n" % (address))
        else:
            q = (db.t_services.f_hosts_id == host_rec.id)
            for port in ports:
                q &= (db.t_services.f_proto == port[0])
                q &= (db.t_services.f_number == port[1])
            if self.host_query is None:
                self.host_query = q
            else:
                self.host_query |= q

        return
开发者ID:LucaBongiorni,项目名称:Kvasir,代码行数:16,代码来源:gen_pwfile.py


示例10: add_ajax

def add_ajax():
    record = None
    if request.vars.has_key('f_hosts_id'):
        record = get_host_record(request.vars.f_hosts_id)
    if record:
        db.t_host_notes.f_hosts_id.default = record.id

    form=SQLFORM(db.t_host_notes, buttons=[], _action=URL('add_ajax', extension='json'), _id="notes_add_form")
    if form.accepts(request.vars, formname='t_host_notes_create'):
        response.flash = 'Note added'
        response.headers['web2py-component-command'] = 'notesumstable.fnReloadAjax(); notestable.fnReloadAjax();'
        return
    elif form.errors:
        response.flash = "Error in form submission"
        return TABLE(*[TR(k, v) for k, v in form.errors.items()])

    db.t_host_notes.f_hosts_id.default = None
    return dict(form=form)
开发者ID:caoimhinp,项目名称:Kvasir,代码行数:18,代码来源:notes.py


示例11: process_pwdump_loot

def process_pwdump_loot(loot_list=[], msf=None):
    """
    Takes an array of loot records in loot_list, downloads the pwdump file and
    adds the users.
    """
    from skaldship.passwords import process_password_file, insert_or_update_acct

    db = current.globalenv['db']
    cache = current.globalenv['cache']

    logging.debug('loot_list = %s' % (loot_list))
    data = []
    for loot_id in loot_list:
        loot = msf.loot_download(loot_id)
        if loot['ltype'] not in ['host.windows.pwdump', 'windows.hashes']:
            logging.error("Loot is not a pwdump, it is a %s" % loot['ltype'])
            continue
        else:
            # process the pwdump file
            pw_data = loot['data'].split('\n')
            accounts = process_password_file(
                pw_data=pw_data,
                file_type='PWDUMP',
                source='Metasploit',
            )

            # find the info/0 service id for the host
            host_id = get_host_record(loot['host'])
            query = (db.t_services.f_number == '0') & (db.t_services.f_proto == 'info') & (db.t_services.f_hosts_id == host_id)
            svc_id = db(query).select().first()
            if svc_id is None:
                # info/0 not found.. add it!
                svc_id = db.t_services.insert(f_proto="info", f_number="0", f_status="info", f_hosts_id=host_id)
                db.commit()

            # insert or update the account records
            resp_text = insert_or_update_acct(svc_id.id, accounts)
            logging.info("Added pwdump records for host: %s" % (loot['host']))
            data.append({ loot['host']: resp_text })

    return data
开发者ID:LucaBongiorni,项目名称:Kvasir,代码行数:41,代码来源:metasploit.py


示例12: summary_by_host

def summary_by_host():
    """
    Returns a list of notes records based upon an host identifier
    (id, ipv4, ipv6)
    """
    if request.args(0) is None: redirect(URL('default', 'error', vars={'msg': T('No host record provided')}))

    record = get_host_record(request.args(0))

    if record is None:
        redirect(URL('default', 'error', vars={'msg': T('Host record not found')}))

    response.title = "%s :: Notes for host %s" % (settings.title, host_title_maker(record))
    rows = db(db.t_host_notes.f_hosts_id == record.id)(db.t_host_notes).select(db.t_host_notes.id, db.t_host_notes.f_note)

    aaData = []
    if request.extension == "json":
        for r in rows:
            # datatables json requires aaData to be specificly formatted
            atxt = []
            atxt.append('<a href="javascript:void()" onclick="delnotes_summ(' + str(r.id)  +')">X</a>')
            atxt.append(r.f_note)
            # add columns after this, don't do anything prior since it'll affect the hidden fields

            aaData.append(atxt)

        result = { 'sEcho': request.vars.sEcho,
                   'iTotalRecords': len(aaData),
                   'aaData': aaData,
                   }
        return result

    notes = TABLE(THEAD(TR(TH(T('[X]'), _width="5%"),
                           TH(T('Note'), _width="90%"),
                           ), _style="display:none" ),
                  _class="table table-condensed", _id="notestable_summary", _style="width:100%")

    return dict(notes=notes)
开发者ID:caoimhinp,项目名称:Kvasir,代码行数:38,代码来源:notes.py


示例13: popover

def popover():
    """
    Returns the detail of a host for popovers
    """
    host_rec = get_host_record(request.args(0))
    resp = {}
    if not host_rec:
        resp['title'] = "Host not found"
        resp['content'] = ""
    else:
        svcs = host_rec.t_services
        svc_cnt = 0
        vuln_cnt = 0
        acct_cnt = 0
        for svc in svcs.select():
            svc_cnt += 1
            vuln_cnt += svc.t_service_vulns.count()
            acct_cnt += svc.t_accounts.count()

        host_os = (0, 'Unknown')
        for os_rec in host_rec.t_host_os_refs.select():
            if os_rec.f_certainty > host_os[0]:
                host_os = (os_rec.f_certainty, db.t_os[os_rec.f_os_id].f_title)

        resp['title'] = host_title_maker(host_rec)
        resp['content'] = XML(TABLE(
            TR(TD(T('Asset Group')), TD(host_rec.f_asset_group)),
            TR(TD(T('Engineer')), TD(db.auth_user[host_rec.f_engineer].username)),
            TR(TD(T('OS')), TD("%s (%s)" % (host_os[1], host_os[0]))),
            TR(TD(T('Services')), TD(svc_cnt), _class="success"),
            TR(TD(T('Vulnerabilities')), TD(vuln_cnt), _class="error"),
            TR(TD(T('Accounts')), TD(acct_cnt), _class="warning"),
            _class="table table-condensed",
        ))

    return resp
开发者ID:SecurityTW,项目名称:Kvasir,代码行数:36,代码来源:hosts.py


示例14: launch_terminal

def launch_terminal(record=None, launch_cmd=None):
    """
    Opens a terminal on the Web Server. This only works if the
    web2py server is running on the user's workstation.

    The command to execute is stored in the user's settings db
    under auth_user.f_launch_cmd. Variables translated:

       _IP_      -- The current IP Address (v4 by default, v6 if exists)
       _LOGFILE_ -- Session logfile name (we prepend the path)

    If an IPv6 address is used then ':' is changed to '_'

    Example:

    xterm -sb -sl 1500 -vb -T 'manual hacking: _IP_' -n 'manual hacking: _IP_' -e script _LOGFILE_
    """

    record = get_host_record(record)

    # only execute launch on requests from localhost!
    if request.env['remote_addr'] != '127.0.0.1':
        logger.error("Can only launch from localhost! remote_addr = %s" % (request.env['remote_addr']))
        return "Can only launch from localhost"

    if record is None:
        return "No record found"

    import string, os, subprocess
    import time
    from gluon.validators import IS_IPADDRESS

    # if no launch command use the default
    if not launch_cmd:
        launch_cmd = "xterm -sb -sl 1500 -vb -T 'manual hacking: _IP_' -n 'manual hacking: _IP_' -e 'script _LOGFILE_'"

    # check ip address
    ip = record.f_ipaddr
    logip = ip
    if IS_IPADDRESS(is_ipv6=True)(ip)[0] == None:
        logip = ip.replace(":", "_")

    logdir = "session-logs"
    logfilename = "%s-%s.log" % (logip, time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())))
    logfile = os.path.join(logdir, logfilename)
    launch_cmd = launch_cmd.replace("_IP_", ip)
    launch_cmd = launch_cmd.replace("_LOGFILE_", logfile)

    from skaldship.general import check_datadir
    # Check to see if data directories exist, create otherwise
    check_datadir(request.folder)
    datadir = os.path.join(os.getcwd(), request.folder, "data")

    # chdir to datadir!
    launch_cmd = launch_cmd.replace("_DATADIR_", datadir)
    os.chdir(datadir)

    # set environment variables
    os.environ['IP'] = ip
    os.environ['HOSTNAME'] = record.f_hostname or ""
    os.environ['DATADIR'] = datadir

    try:
        logger.info("Spawning: %s\n" % (launch_cmd))
        print("Spawning: %s" % (launch_cmd))
        subprocess.Popen(launch_cmd, shell=True)#, stdout=None, stdin=None, stderr=None)
    except Exception, e:
        logger.error("Error spawning launch cmd (%s): %s\n" % (launch_cmd, e))
        print("Error spawning launch cmd (%s): %s\n" % (launch_cmd, e))
开发者ID:KvasirSecurity,项目名称:Kvasir,代码行数:69,代码来源:scheduler.py


示例15: parse

    def parse(self, host_properties):
        """
        Parse out the <HostProperties> xml content or CSV line.

        There can be a number of <tag> entries that are either useful to us in
        t_hosts or other areas. These are processed and returned as dictionary
        entries in 'hostdata'

        Args:
            host_properties: A <HostProperties> section from .nessus or a CSV line

        Returns:
            t_hosts.id, { hostdata }
        """
        from gluon.validators import IS_IPADDRESS
        hostdata = {}
        if etree.iselement(host_properties):
            for tag in host_properties.findall('tag'):
                hostdata[tag.get('name')] = tag.text
            ipaddr = hostdata.get('host-ip')
        else:
            # with CSV each line has all the hostdata fields so we set them here for use later
            ipaddr = host_properties.get('IP Address')
            if not ipaddr:
                # Scanner CSV, use Host
                ipaddr = host_properties.get('Host')
            hostdata['mac-address'] = host_properties.get('MAC Address', '')
            hostdata['host-fqdn'] = host_properties.get('DNS Name', '')
            hostdata['netbios-name'] = host_properties.get('NetBIOS Name', '')

        if (ipaddr not in self.ip_include and self.ip_include) or (ipaddr in self.ip_exclude):
            log("Host in exclude or not in include list, skipping")
            self.stats['skipped'] += 1
            return None, {}

        host_id = get_host_record(ipaddr)
        if host_id and not self.update_hosts:
            return host_id, hostdata

        # new host found, pull what we need for t_hosts
        hostfields = {}
        hostfields['f_engineer'] = self.engineer
        hostfields['f_asset_group'] = self.asset_group
        hostfields['f_confirmed'] = False

        # check ipv4/ipv6 and set hostfields accordingly
        if IS_IPADDRESS(is_ipv4=True)(ipaddr)[1] is None:
            hostfields['f_ipv4'] = ipaddr
        elif IS_IPADDRESS(is_ipv6=True)(ipaddr)[1] is None:
            hostfields['f_ipv6'] = ipaddr
        else:
            log("Invalid IP Address in HostProperties: %s" % ipaddr, logging.ERROR)
            return None, {}

        # pull out relevant hostfields
        for (k,v) in hostdata.iteritems():
            if k == 'mac-address':
                # multiple mac addrs may appear wildly, just pull the first
                hostfields['f_macaddr'] = v[:v.find('\n')]
            elif k == 'host-fqdn':
                hostfields['f_hostname'] = v
            elif k == 'netbios-name':
                hostfields['f_netbios_name'] = v

        if not self.update_hosts and not host_id:
            result = self.db.t_hosts.validate_and_insert(**hostfields)
            if not result.id:
                log("Error adding host to DB: %s" % result.errors, logging.ERROR)
                return None, {}
            self.stats['added'] += 1
            host_id = result.id
            log(" [-] Adding host: %s" % ipaddr)
        elif self.update_hosts:
            if hostfields['f_ipv4']:
                host_id = self.db(self.db.t_hosts.f_ipv4 == hostfields['f_ipv4']).update(**hostfields)
                self.db.commit()
                host_id = get_host_record(hostfields['f_ipv4'])
                if host_id:
                    host_id = host_id.id
                log(" [-] Updating IP: %s" % (hostfields['f_ipv4']))
            else:
                host_id = self.db(self.db.t_hosts.f_ipv6 == hostfields['f_ipv6']).update(**hostfields)
                self.db.commit()
                host_id = get_host_record(hostfields['f_ipv6'])
                host_id = host_id.id
                log(" [-] Updating IP: %s" % (hostfields['f_ipv6']))
            self.stats['updated'] += 1

        return host_id, hostfields
开发者ID:LucaBongiorni,项目名称:Kvasir,代码行数:89,代码来源:nessus.py


示例16: detail

def detail():

    if request.args(0) is None: redirect(URL('default', 'error', vars={'msg': T('Host record not found')}))

    response.files.append(URL(request.application,'static','js/jquery.sparkline.js'))
    response.files.append(URL(request.application,'static','jstree/jstree.min.js'))

    #query = db.t_hosts.id == request.args(0)
    #query = create_hostfilter_query(session.hostfilter, query)

    record = get_host_record(request.args(0))

    if record is None:
        redirect(URL('hosts', 'list'))

    hostipv4=record.f_ipv4
    engineername = db.auth_user[record.f_engineer].username

    # to allow updating of the host record from this page
    host=crud.read(db.t_hosts,record)
    host.attributes['_id'] = "host_record"

    host_points = {}
    # build the host_points field which will cover:
    # the top t_host_os_ref cpe string
    os_list = db(db.t_host_os_refs.f_hosts_id == record.id).select()
    host_points['os'] = (0, 'Unknown')
    for os_rec in os_list:
        if os_rec.f_certainty > host_points['os'][0]:
            host_points['os'] = (os_rec.f_certainty, db.t_os[os_rec.f_os_id].f_title)

    host_points['account_cnt'] = 0
    host_points['password_cnt'] = 0
    host_points['cracked_pct'] = 0
    host_points['vuln_cnt'] = 0
    host_points['vuln_exploited_cnt'] = 0
    host_points['vuln_potential_cnt'] = 0
    vulns = {}
    vuln_list = []
    services = db(db.t_services.f_hosts_id == record.id).select()
    for svc in services:
        for vuln in db(db.t_service_vulns.f_services_id == svc.id).select():
            vulndata = db.t_vulndata[vuln.f_vulndata_id]
            vulns[vulndata.f_vulnid] = ( vulndata.f_severity, vulndata.f_cvss_score )
            vuln_list.append(vulndata)
        host_points['vuln_exploited_cnt'] += db((db.t_service_vulns.f_services_id==svc.id) & (db.t_service_vulns.f_status.like('%exploited%'))).count()
        host_points['vuln_potential_cnt'] += db((db.t_service_vulns.f_services_id==svc.id) & (db.t_service_vulns.f_status.like('%potential%'))).count()
        host_points['vuln_cnt'] += db(db.t_service_vulns.f_services_id==svc.id).count()
        host_points['account_cnt'] += db(db.t_accounts.f_services_id==svc.id).count()
        pwq = ((db.t_accounts.f_services_id==svc.id) & (db.t_accounts.f_compromised == True))
        #pwq &= (((db.t_accounts.f_password != None) | (db.t_accounts.f_password != '')) | (db.t_accounts.f_compromised == True))
        host_points['password_cnt'] += db(pwq).count()
        try:
            host_points['cracked_pct'] = 100 * (host_points['password_cnt'] / host_points['account_cnt'])
        except ZeroDivisionError:
            host_points['cracked_pct'] = 0

    # breakdown of vuln severity
    sev_sum_dict = {}
    for a in range(1, 11):
        sev_sum_dict[a] = 0

    for k,v in vulns.iteritems():
        # take the severity and increment the sev_sum set item
        if settings.use_cvss:
            severity = int(float(v[1]))
        else:
            severity = v[0]

        count = sev_sum_dict.setdefault(severity, 1)
        count += 1
        sev_sum_dict[severity] = count

    sev_sum_spark = []
    sev_sum = []
    for k,v in sev_sum_dict.iteritems():
        sev_sum_spark.append(str(v))
        if v > 0:
            sev_sum.append("%s: %s" % (k, v))

    host_points['sev_sum_spark'] = ",".join(sev_sum_spark)
    host_points['sev_sum'] = " / ".join(sev_sum)

    # netbios record (or none if it's empty)
    netb_record = db(db.t_netbios.f_hosts_id == record.id).select().first() or None
    if netb_record is not None:
        netbios=crud.update(db.t_netbios, netb_record,
                            ondelete=lambda netbios: redirect(URL('host_detail', args=[ record.id ])))
        host_points['netb_domain'] = netb_record.f_domain
        host_points['netb_type'] = netb_record.f_type
    else:
        db.t_netbios.f_hosts_id.default = record.id
        netbios = LOAD('netbios', 'add.load', args=[host.record.id], ajax=True, target='netbios_info')

    host_pagination = pagination(request, record)

    response.title = "%s :: Host info :: %s" % (settings.title, host_title_maker(record))
    return dict(host=host,
                netbios=netbios,
                host_points=host_points,
#.........这里部分代码省略.........
开发者ID:SecurityTW,项目名称:Kvasir,代码行数:101,代码来源:hosts.py


示例17: refs_by_host

def refs_by_host():
    """
    Returns a list of OS records based upon an host identifier
    (id, ipv4, ipv6)
    """
    if request.args(0) is None: redirect(URL('default', 'error', vars={'msg': T('No host record sent')}))

    record = get_host_record(request.args(0))

    if record is None:
        redirect(URL('default', 'error', vars={'msg': T('Host record not found')}))

    response.title = "%s :: OS Records for %s" % (settings.title, host_title_maker(record))
    oslist = db(db.t_host_os_refs.f_hosts_id==record.id).select()

    aaData = []
    if request.extension == "json":
        for osdetail in oslist:
            osinfo = db.t_os(osdetail['f_os_id'])
            # datatables json requires aaData to be specificly formatted
            atxt = {}
            atxt['0'] = A('edit', _target="oswindow_%s" % (osdetail.id), _href=URL('refs_edit', args=[osdetail.id], extension='html')).xml()
            atxt['1'] = osdetail.f_family
            atxt['2'] = osdetail.f_class
            atxt['3'] = osdetail.f_certainty
            atxt['4'] = osinfo.f_cpename
            atxt['5'] = osinfo.f_title
            atxt['DT_RowId'] = osdetail.id

            aaData.append(atxt)

        result = { 'sEcho': request.vars.sEcho,
                   'iTotalRecords': len(aaData),
                   'aaData': aaData,
                   }

        return result

    form = TABLE(THEAD(TR(TH(T(''), _width="5%"),
                          TH(T('Family')),
                          TH(T('Class')),
                          TH(T('Certainty')),
                          TH(T('CPE Name')),
                          TH(T('Title')),
                          )  ),
                 _class="datatable",
                 _id="ostable",
                 _style="width:100%")

    add_os_refs = AddModal(
        db.t_host_os_refs, 'Add', 'Add', 'Add OS',
        fields=['f_certainty', 'f_class', 'f_family', 'f_os_id'],
        cmd='ostable.fnReloadAjax();'
    )
    db.t_host_os_refs.f_hosts_id.default = record.id
    db.t_host_os_refs.id.comment = add_os_refs.create()

    add_non_cpe = AddModal(
        db.t_os, 'Add Non-CPE OS', 'Add Non-CPE OS', 'Add Non-CPE OS',
        #fields=[],
        #cmd='ostable.fnReloadAjax();'
    )
    db.t_os.id.comment = add_non_cpe.create()

    return dict(form=form, host=record, add_os_refs=add_os_refs, add_non_cpe=add_non_cpe)
开发者ID:SecurityTW,项目名称:Kvasir,代码行数:65,代码来源:os.py


示例18: aa_by_host

def aa_by_host():
    """
    Returns a list of vulnerabilties per port in a tree view format based upon an host identifier
    (id, ipv4, ipv6)
    """
    record = get_host_record(request.args(0))
    if record is None:
        redirect(URL('default', 'error', vars={'msg': T('Host record not found')}))

    treeul=UL(_id='aatree_ul')

    db_svcs = db.t_services
    db_svulns = db.t_service_vulns
    db_vulns = db.t_vulndata

    services = db(db_svcs.f_hosts_id==record.id).select(db_svcs.f_number, db_svcs.id,
                                                        db_svcs.f_proto, db_svcs.f_name,orderby=db_svcs.id)

    if settings.use_cvss:
        db_vsevs = db_vulns.f_cvss_score
    else:
        db_vsevs = db_vulns.f_severity

    tree = DIV(_id="aatree")
    for svc in services:

        nexlist = []
        nexlist_single = []
        expl_count = 0
        exploit_list = UL()
        exploitdb = 0
        metasploit = 0
        canvas = 0
        prev_f_status = ''
        vulnclass = ''
        for vulninfo in db(
                (db_svulns.f_services_id == svc.id) & (db_vulns.id == db_svulns.f_vulndata_id)
                ).select(orderby=~db_svulns.f_status|~db_vsevs, cache=(cache.ram, 120)):

            #init variables
            vulndetails = vulninfo.t_vulndata
            vulninfo = vulninfo.t_service_vulns

            cur_f_status = vulninfo.f_status

            #Generating the exploit lists

            exploits = db(db.t_exploit_references.f_vulndata_id == vulninfo.f_vulndata_id).select(orderby=~db.t_exploit_references.id)

            exploit_list_single = UL()
            if len(exploits) > 0:

                for expl in exploits:
                    for expl_data in db(db.t_exploits.id == expl.f_exploit_id).select(db.t_exploits.f_source, db.t_exploits.f_title, db.t_exploits.f_name, db.t_exploits.f_rank, db.t_exploits.f_level):
                        exp_link = expl_data.f_name
                        if expl_data.f_source == 'exploitdb':
                            exploitdb += 1
                            if db.t_exploitdb[expl_data.f_title]:
                                exploitdb_href = URL('exploitdb', 'detail.html', args=expl_data.f_title)
                            else:
                                exploitdb_href = URL('default', 'redirect', extension='html', vars={'url': 'http://www.exploit-db.com/exploits/%s' % expl_data.f_title})
                            exp_link = A(IMG(_align="absmiddle", _width=16, _height=16, _src=URL('static','images/exploitdb.ico')), ' exploitdb - ' + expl_data.f_name,_href=exploitdb_href, _target="exploitdb_%s" % (expl_data.f_name))
                        elif expl_data.f_source == 'metasploit':
                            metasploit += 1
                            if session.msf_workspace:
                                msf_uri = os.path.join(msf_settings['url'], session.msf_workspace, 'modules', expl_data.f_title)
                            else:
                                msf_uri = URL('default', 'redirect', extension='html', vars={'url': 'http://www.rapid7.com/db/modules/%s' % expl_data.f_title})
                            exp_link = A(IMG(_align="absmiddle", _width=16, _height=16, _src=URL('static','images/msf.gif')), ' metasploit - ' + expl_data.f_name, _href=msf_uri, _target="msf_%s" % (expl_data.f_name))
                        elif expl_data.f_source == 'canvas':
                            canvas += 1
                            exp_link = SPAN(IMG(_align="absmiddle", _width=16, _height=16, _src=URL('static','images/canvas.png')), ' canvas - ' + expl_data.f_name)
                            #expl_link = ' canvas - ' + expl_data.f_name
                        expl_count += 1
                        exploit_list_single.append(LI(expl_data.f_title , " : " , exp_link , " (" , expl_data.f_rank , "/" , expl_data.f_level, ")"))

            textdecoration=""
            if vulninfo.f_exploited == True and len(exploits) > 0:
                textdecoration="text-decoration:line-through underline; "
            elif vulninfo.f_exploited == True and len(exploits) == 0:
                textdecoration="text-decoration: line-through; "
            elif (vulninfo.f_exploited == False or vulninfo.f_exploited == None) and len(exploits) == 0:
                textdecoration="text-decoration: none;"

            #generation vuln link
            if settings.use_cvss:
                severity = int(float(vulndetails.f_cvss_score))
            else:
                severity = int(vulndetails.f_severity)
            style = textdecoration + "color:" + severity_mapping(severity - 1)[2]
            vuln_title_link = A(vulndetails.f_vulnid, _title = vulninfo.f_status+ ' Severity: ' + str(severity),
                                _style=style, _target="vulndata_%s" % (vulndetails.id),
                                _href=URL(request.application,'vulns', 'vulninfo_by_vulnid',
                                          args=vulndetails.f_vulnid, extension='html'))

            if cur_f_status != prev_f_status and prev_f_status != '':
                nexlist.append(SPAN(nexlist_single, _class=vulnclass)) #for a line in the bottom
                nexlist.append(' ')
                nexlist_single = []
            else:
#.........这里部分代码省略.........
开发者ID:stepcellwolf,项目名称:Kvasir,代码行数:101,代码来源:vulns.py


示例19: list

def list():
    """
    Returns a list of evidence based on a host (id, ipv4, ipv6) or all
    """
    import os, string

    if request.args(0) is not None:
        record = get_host_record(request.args(0))
        if record is None:
            redirect(URL("default", "error", vars={"msg": T("Host record not found")}))
        response.title = "%s :: Evidence for host %s" % (settings.title, host_title_maker(record))
    else:
        response.title = "%s :: Evidence listing" % (settings.title)
        record = None

    aaData = []
    if request.extension == "json":
        if record is None:
            rows = db(db.t_evidence).select(
                db.t_evidence.id,
                db.t_evidence.f_hosts_id,
                db.t_evidence.f_type,
                db.t_evidence.f_other_type,
                db.t_evidence.f_text,
                db.t_evidence.f_filename,
                db.t_evidence.f_evidence,
                db.t_evidence.f_data.len() + 1,
            )
        else:
            rows = db(db.t_evidence.f_hosts_id == record.id).select(
                db.t_evidence.id,
                db.t_evidence.f_hosts_id,
                db.t_evidence.f_type,
                db.t_evidence.f_other_type,
                db.t_evidence.f_text,
                db.t_evidence.f_filename,
                db.t_evidence.f_evidence,
                db.t_evidence.f_data.len() + 1,
            )

        for r in rows:
            atxt = {}
            cnt = 0
            atxt[cnt] = A(
                "edit",
                _target="evidence_edit_%s" % (r.t_evidence.id),
                _href=URL("edit", extension="html", args=r.t_evidence.id),
            ).xml()
            cnt += 1
            if record is None:
                atxt[cnt] = host_a_maker(r.t_evidence.f_hosts_id).xml()
                cnt += 1
            if r.t_evidence.f_other_type:
                atxt[cnt] = "Other: %s" % (r.t_evidence.f_other_type)
            else:
                atxt[cnt] = r.t_evidence.f_type
            cnt += 1
            atxt[cnt] = r.t_evidence.f_text
            cnt += 1
            if r.t_evidence.f_filename is not None:
                if string.lower(os.path.splitext(r.t_evidence.f_filename)[1]) in (".png", ".jpeg", ".jpg", ".gif"):
                    atxt[cnt] = A(
                        IMG(_src=URL("download", args=[r.t_evidence.f_evidence]), _width="50%", _height="20%"),
                        _href=URL("download", args=[r.t 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python hosts.host_title_maker函数代码示例发布时间:2022-05-27
下一篇:
Python general.check_datadir函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap