Example #1
0
    def getEventFromWin32_UserAccountQuery(self, data):
        '''
        Query parser:
        Example data - 
        {'Status': 'OK', 
        'Domain': 'LOCAL', 
        'Description': '', 
        'InstallDate': '(null)', 
        'PasswordChangeable': 'True', 
        'Disabled': 'False', 
        'Caption': 'LOCAL\\wmiuser',
        'Lockout': 'False', 
        'AccountType': '512', 
        'SID': 'S-1-5-21-2973305993-3644778160-3199891575-1003', 
        'LocalAccount': 'True', 
        'FullName': 'wmiuser', 
        'SIDType': '1', 
        'PasswordRequired': 'True', 
        'PasswordExpires': 'False', 
        'Name': 'wmiuser'}
        '''

        event = HostInfoEvent()
        try:
            event['ip'] = self._remoteIPAddress
            event['domain'] = data['Domain']
            event['username'] = data['Name']
        except:
            event = ''
        return event
Example #2
0
 def doJob(self):
     self._running = True
     logger.info("OCS Process")
     data = self.getOCSInventory()
     if not data or data == '':
         return
     xml = re.findall("ocsinventory=\"([^\"]+)\"", data)
     if len(xml) > 0:
         try:
             dom = minidom.parseString(xml[0])
         except Exception, e:
             logger.warning("OCS: invalid data:%s,%s" % (xml[0], str(e)))
         else:
             for host in dom.getElementsByTagName('host'):
                 hostData = HostInfoEvent()
                 tmp = host.getElementsByTagName('ip')
                 if tmp and len(tmp) == 1:
                     tmp = tmp[0]
                     hostData['ip'] = self.getText(tmp.childNodes)
                 tmp = host.getElementsByTagName('hostname')
                 if tmp and len(tmp) == 1:
                     tmp = tmp[0]
                     hostData['hostname'] = self.getText(tmp.childNodes)
                 tmp = host.getElementsByTagName('mac')
                 if tmp and len(tmp) == 1:
                     tmp = tmp[0]
                     hostData['mac'] = self.getText(tmp.childNodes)
                 tmp = host.getElementsByTagName('os')
                 if tmp and len(tmp) == 1:
                     tmp = tmp[0]
                     hostData['os'] = self.getText(tmp.childNodes)
                 tmp = host.getElementsByTagName('video')
                 if tmp and len(tmp) == 1:
                     tmp = tmp[0]
                     hostData['video'] = self.getText(tmp.childNodes)
                 tmp = host.getElementsByTagName('memory')
                 if tmp and len(tmp) == 1:
                     tmp = tmp[0]
                     hostData['memory'] = self.getText(tmp.childNodes)
                 tmp = host.getElementsByTagName('video')
                 if tmp and len(tmp) == 1:
                     tmp = tmp[0]
                     hostData['video'] = self.getText(tmp.childNodes)
                 #tmp = host.getElementsByTagName('domain')
                 #if tmp and len(tmp) == 1:
                 #    tmp = tmp[0]
                 #    hostData['domain'] = self.getText(tmp.childNodes)
                 self.send_message(hostData)
Example #3
0
class NMAP_TASK(InventoryTask):
    '''
    NMAP-OPTIONS
    -O Sistema operativo
    -sV Deteccion de version
    --allports :No excluir ningĂșn puerto de la deteccion de versiones
    -sS (sondeo TCP SYN)
    -PE; -PP; -PM (Tipos de ping ICMP)
    -PA [lista de puertos] (Ping TCP ACK)
    -PS [lista de puertos] (Ping TCP SYN)
    -P0 (No realizar ping)
    -sP (Sondeo ping)
    -sL (Sondeo de lista)
    '''


    def __init__(self, task_name, task_params, task_period, task_reliability, task_enable, task_type,task_type_name):
        '''
        Constructor
        '''
        self._running = False
        self._nm = nmap.PortScanner()
        InventoryTask.__init__(self, task_name, task_params, task_period, task_reliability, task_enable, task_type,task_type_name)


    def runQuery(self):
        #print "Query: hosts: %s - args: %s" % (query.get_hosts(),query.get_args())
        try:
            host_arg, args_arg = self._task_params.split ('#', 1)
            self._nm.scan(hosts=host_arg, arguments=args_arg)
            xmldata = self._nm.get_nmap_last_output()
        except Exception, e:
            logger.error("ERRROR :%s" % str(e))
            return
        dom = xml.dom.minidom.parseString(xmldata)
        for nmaphost in  dom.getElementsByTagName('host'):
            host = HostInfoEvent()
            for status in nmaphost.getElementsByTagName('status'):
                # States: (up|down|unknown|skipped)
                host['state'] = status.getAttributeNode('state').value
            for address in nmaphost.getElementsByTagName('address'):
                if address.getAttributeNode('addrtype').value == 'ipv4' or address.getAttributeNode('addrtype').value == 'ipv6':
                    host['ip'] = address.getAttributeNode('addr').value
                if address.getAttributeNode('addrtype').value == 'mac':
                    host['mac'] = address.getAttributeNode('addr').value
            hostnames = nmaphost.getElementsByTagName('hostnames')
            if hostnames:
                for hn in nmaphost.getElementsByTagName('hostname'):
                    host['hostname'] = hn.getAttributeNode('name').value

            str_ports = ''
            software = set()
            operative_system = set()
            hardware = set()

            ports = nmaphost.getElementsByTagName('ports')
            if ports:
                for port in nmaphost.getElementsByTagName('port'):
                    protocol = port.getAttributeNode('protocol').value
                    portnumber = port.getAttributeNode('portid').value
                    portstates = port.getElementsByTagName('state')
                    state = 'unknown'
                    if portstates:
                        if portstates[0].getAttributeNode('state'):
                            state = portstates[0].getAttributeNode('state').value
                    portservices = port.getElementsByTagName('service')
                    if state != "open":
                        continue
                    str_services = ''
                    tunnel=''
                    ocpe = ''
                    product = ''
                    version = ''
                    extrainfo = ''
                    services = []
                    str_cpe = ''
                    for ps in portservices:
                        try:
                            product = ps.getAttributeNode('product').value
                        except AttributeError:
                            pass
                        try:
                            version = ps.getAttributeNode('version').value
                        except AttributeError:
                            pass
                        try:
                            extrainfo = ps.getAttributeNode('extrainfo').value
                        except AttributeError:
                            pass

                        service_name = ps.getAttributeNode('name').value
                        if service_name == '' or service_name is None:
                            continue;
                            
                        try:
                            tunnel = ps.getAttributeNode('tunnel').value
                            if tunnel=='ssl' and service_name=='http':
                                service_name = 'https'
                        except AttributeError:
                            pass
                            
                        services.append(service_name)
                            
                        #create banner
                        banner = []
                        if product:
                            banner.append(product)
                        if version:
                            banner.append(version)
                        if extrainfo:
                            banner.append(extrainfo)

                        for cpe in ps.getElementsByTagName('cpe'):
                            if not banner:
                                banner.append(' '.join([s[0].upper() + s[1:] for s in re.sub(':',' ',re.sub(r"^cpe:/.:", '', re.sub(r":+", ':', cpe.firstChild.nodeValue))).split(' ')]))

                            ocpe = cpe.firstChild.nodeValue # save the original cpe

                            cpe.firstChild.nodeValue += '|'
                            cpe.firstChild.nodeValue += (' '.join(banner)).lstrip(' ')

                            if cpe.firstChild.nodeValue.startswith('cpe:/o:'):
                                operative_system.add (cpe.firstChild.nodeValue)
                            elif cpe.firstChild.nodeValue.startswith('cpe:/h:'):
                                hardware.add (cpe.firstChild.nodeValue)
                            else:
                                if str_cpe:
                                    str_cpe += ','
                                str_cpe += ocpe

                                software.add (cpe.firstChild.nodeValue)

                        if not str_cpe and banner:
                            str_cpe = (' '.join(banner)).lstrip(' ')

                    if len(services) > 0:
                        str_services = ','.join(["%s" % s for s in services])
                    if str_ports:
                        str_ports += ','
                    if str_cpe:
                        str_ports += '%s|%s|%s|%s' % (protocol, portnumber, str_services, str_cpe)
                    else:
                        str_ports += '%s|%s|%s|unknown' % (protocol, portnumber,str_services)

            os = nmaphost.getElementsByTagName('os')
            if os:
                str_os = ''
                last_accuracy = 0
                for os in nmaphost.getElementsByTagName('osclass'):
                    osfamily = ''
                    try:
                        osfamily = os.getAttributeNode('osfamily').value
                    except:
                        pass

                    if not osfamily in ['embedded', '', 'unknown']:
                        accuracy = 0
                        try:
                            accuracy = os.getAttributeNode('accuracy').value
                        except:
                            pass
                        if accuracy > last_accuracy:
                            last_accuracy = accuracy
                            if os.getAttributeNode('osfamily') and os.getAttributeNode('osgen'):
                                str_os = '%s %s' % (osfamily, os.getAttributeNode('osgen').value)
                            operative_system_new = set()
                            hardware_new = set()
                            for cpe in os.getElementsByTagName('cpe'):
                                banner = ' '.join([s[0].upper() + s[1:] for s in re.sub(':',' ',re.sub(r"^cpe:/.:", '', re.sub(r":+", ':', cpe.firstChild.nodeValue))).split(' ')])
                                if cpe.firstChild.nodeValue.startswith('cpe:/o:'):
                                    operative_system_new.add(cpe.firstChild.nodeValue + '|' + banner)
                                elif cpe.firstChild.nodeValue.startswith('cpe:/h:'):
                                    hardware_new.add(cpe.firstChild.nodeValue + '|' + banner)
                            if len(operative_system_new) > 0 or len(hardware_new) > 0:
                                operative_system = operative_system_new
                                hardware = hardware_new

                if str_os != '':
                    host['os'] = str_os

            str_software = ''
            software.update(operative_system)
            software.update(hardware)
            for s in software:
                if str_software == '':
                    str_software += '%s' % (s)
                else:
                    str_software += ',%s' % (s)

            host['service'] = str_ports
            host['software'] = str_software

            host['inventory_source'] = 5; # SELECT id FROM host_source_reference WHERE name = 'NMAP';
            self.send_message(host)
class LDAP_TASK(InventoryTask):
    '''
    '''
    def __init__(self, task_name, task_params, task_period, task_reliability,
                 task_enable, task_type, task_type_name):
        '''
        Constructor
        '''
        self._running = False
        self._validTask = True
        #ldaphost:192.168.12.200;ldapport:389;ldapuser:admin;ldappass:temporal;ldapdomain:alienvault.com;ldapbasedn:"ou=kktuaDevel,dc=testcfg,dc=qa,dc=alienvault,dc=com"
        self._pattern = re.compile(
            "ldaphost:(?P<ldaphost>[^;]+);ldapport:(?P<ldapport>[^;]+);ldapuser:(?P<ldapuser>[^;]+);ldappass:(?P<ldappass>[^;]+);ldapdomain:(?P<ldapdomain>[^;]+);ldapbasedn:\"(?P<basedn>[^;]+)\""
        )
        values = self._pattern.match(task_params)
        self._ldapHost = ''
        self._ldapPort = ''
        self._ldapUser = ''
        self._ldapPass = ''
        self._ldapDomain = ''
        self._ldapBasedn = ''

        if values:
            groupdict = values.groupdict()
            self._ldapHost = groupdict['ldaphost']
            self._ldapPort = groupdict['ldapport']
            self._ldapUser = groupdict['ldapuser']
            self._ldapPass = groupdict['ldappass']
            self._ldapDomain = groupdict['ldapdomain']
            self._ldapBasedn = groupdict['basedn']
        else:
            logger.warning("Invalid ldap task")
            self._validTask = False
        self._ldapURL = 'ldap://%s:%s' % (self._ldapHost, self._ldapPort)
        self._ldapInstance = None
        InventoryTask.__init__(self, task_name, task_params, task_period,
                               task_reliability, task_enable, task_type,
                               task_type_name)

    def doJob(self):
        logger.info("Starting LDAP")
        try:
            self._ldapInstance = ldap.initialize(self._ldapURL)
            self._ldapInstance.simple_bind_s()
        except ldap.LDAPError, e:
            logger.error("Error creating LDAP instance: %s -  %s" %
                         (self._ldapURL, str(e)))
            logger.info("Ending collector...")
            return
        logger.info("Connected to LDAP Server")
        try:
            data = self._ldapInstance.search_s(self._ldapBasedn,
                                               ldap.SCOPE_SUBTREE)
            organizationunit = ''
            for dn, entry in data:
                event = HostInfoEvent()
                if entry.has_key('ou'):
                    organizationunit = ','.join(
                        ["%s" % s for s in entry['ou']])
                    event['organization'] = organizationunit
                if entry.has_key('cn'):
                    tmp = ','.join(["%s" % s for s in entry['cn']])
                    event['username'] = tmp
                if entry.has_key('mail'):
                    tmp = ','.join(["%s" % s for s in entry['mail']])
                    event['mail'] = tmp
                self.send_message(event)
            self._ldapInstance.unbind_s()
        except Exception, e:
            logger.error("Error running ldap query: %s" % str(e))
    def doJob(self):
        self._running = True
        logger.info("Nagios Process")
        data = self.getNagiosInventory()
        '''
        control action="getNagiosInventory" nagiosinventory="
        <nagiosdiscovery>
            <host>
                <ip>127.0.0.1</ip>
                <hostname>localhost</hostname>
                <host_state>0</host_state>
                <services>
                    <service>
                        <name>Current Load</name>
                        <state>2</state>
                    </service>
                    <service>
                        <name>Current Users</name>
                        <state>0</state>
                    </service>
                    <service>
                        <name>Disk Space</name>
                        <state>0</state>
                    </service>
                    <service>
                        <name>HTTP</name>
                        <state>0</state>
                    </service>
                    <service>
                        <name>SSH</name>
                        <state>0</state>
                    </service>
                    <service>
                        <name>Total Processes</name>
                        <state>0</state>
                    </service>
                </services>
            </host>
        </nagiosdiscovery>"
        '''
        if not data or data == '':
            return
        xml = re.findall("nagiosinventory=\"([^\"]+)\"", data)
        if len(xml) > 0:
            try:
                dom = minidom.parseString(xml[0])
            except Exception, e:
                logger.warning("Nagios: invalid data:%s,%s" % (xml[0], str(e)))
            else:
                for host in dom.getElementsByTagName('host'):
                    hostData = HostInfoEvent()
                    hostData['ip'] = 'unknown'
                    hostData['hostname'] = 'unknown'

                    tmp = host.getElementsByTagName('ip')
                    if tmp and len(tmp) == 1:
                        tmp = tmp[0]
                        hostData['ip'] = self.getText(tmp.childNodes)
                    tmp = host.getElementsByTagName('hostname')
                    if tmp and len(tmp) == 1:
                        tmp = tmp[0]
                        hostData['hostname'] = self.getText(tmp.childNodes)
                    tmp = host.getElementsByTagName('host_state')
                    if tmp and len(tmp) == 1:
                        tmp = tmp[0]
                        hostData['state'] = self.getText(tmp.childNodes)
                    str_ports = ''
                    first = True
                    for service in host.getElementsByTagName('service'):

                        service_state = 'unknown'
                        service_name = 'unknown'
                        tmp = service.getElementsByTagName('name')
                        if tmp and len(tmp) == 1:
                            service_name = self.getText(tmp[0].childNodes)
                        tmp = service.getElementsByTagName('state')
                        if tmp and len(tmp) == 1:
                            service_state = self.getText(tmp[0].childNodes)
                        if not first:
                            str_ports += ','
                        str_ports += '%s|%s|%s|%s' % (
                            'unknown', 'unknown', service_name, service_state)
                        first = False
                    hostData['service'] = str_ports
                    self.send_message(hostData)
class NMAP_TASK(InventoryTask):
    '''
    NMAP-OPTIONS
    -O Sistema operativo
    -sV Deteccion de version
    --allports :No excluir ningĂșn puerto de la deteccion de versiones
    -sS (sondeo TCP SYN)
    -PE; -PP; -PM (Tipos de ping ICMP)
    -PA [lista de puertos] (Ping TCP ACK)
    -PS [lista de puertos] (Ping TCP SYN)
    -P0 (No realizar ping)
    -sP (Sondeo ping)
    -sL (Sondeo de lista)
    '''
    def __init__(self, task_name, task_params, task_period, task_reliability,
                 task_enable, task_type, task_type_name):
        '''
        Constructor
        '''
        self._running = False
        self._nm = nmap.PortScanner()
        InventoryTask.__init__(self, task_name, task_params, task_period,
                               task_reliability, task_enable, task_type,
                               task_type_name)

    def runQuery(self):
        #print "Query: hosts: %s - args: %s" % (query.get_hosts(),query.get_args())
        try:
            host_arg, args_arg = self._task_params.split('#', 1)
            self._nm.scan(hosts=host_arg, arguments=args_arg)
            xmldata = self._nm.get_nmap_last_output()
        except Exception, e:
            logger.error("ERRROR :%s" % str(e))
            return
        dom = xml.dom.minidom.parseString(xmldata)
        for nmaphost in dom.getElementsByTagName('host'):
            host = HostInfoEvent()
            for status in nmaphost.getElementsByTagName('status'):
                # States: (up|down|unknown|skipped)
                host['state'] = status.getAttributeNode('state').value
            for address in nmaphost.getElementsByTagName('address'):
                if address.getAttributeNode(
                        'addrtype'
                ).value == 'ipv4' or address.getAttributeNode(
                        'addrtype').value == 'ipv6':
                    host['ip'] = address.getAttributeNode('addr').value
                if address.getAttributeNode('addrtype').value == 'mac':
                    host['mac'] = address.getAttributeNode('addr').value
            hostnames = nmaphost.getElementsByTagName('hostnames')
            if hostnames:
                for hn in nmaphost.getElementsByTagName('hostname'):
                    host['hostname'] = hn.getAttributeNode('name').value

            str_ports = ''
            software = set()
            hardware = set()

            ports = nmaphost.getElementsByTagName('ports')
            if ports:
                for port in nmaphost.getElementsByTagName('port'):
                    protocol = port.getAttributeNode('protocol').value
                    portnumber = port.getAttributeNode('portid').value
                    portstates = port.getElementsByTagName('state')
                    state = 'unknown'
                    if portstates:
                        if portstates[0].getAttributeNode('state'):
                            state = portstates[0].getAttributeNode(
                                'state').value
                    portservices = port.getElementsByTagName('service')
                    if state != "open":
                        continue
                    str_services = 'unknown'
                    services = []
                    str_cpe = ''
                    for ps in portservices:
                        service_name = ps.getAttributeNode('name').value
                        if service_name == '' or service_name is None:
                            service_name = 'unknown'
                        services.append(service_name)

                        for cpe in ps.getElementsByTagName('cpe'):
                            if str_cpe:
                                str_cpe += ','
                            str_cpe += cpe.firstChild.nodeValue
                            software.add(cpe.firstChild.nodeValue)

                    if len(services) > 0:
                        str_services = ','.join(["%s" % s for s in services])
                    if str_ports:
                        str_ports += ','
                    if str_cpe:
                        str_ports += '%s|%s|%s|%s' % (protocol, portnumber,
                                                      str_services, str_cpe)
                    else:
                        str_ports += '%s|%s|%s' % (protocol, portnumber,
                                                   str_services)

            os = nmaphost.getElementsByTagName('os')
            if os:
                str_os = ''
                last_accuracy = 0
                for os in nmaphost.getElementsByTagName('osclass'):
                    # por aqui dentro se saca el cpe hardware
                    accuracy = 0
                    try:
                        accuracy = os.getAttributeNode('accuracy').value
                    except:
                        pass
                    if accuracy > last_accuracy:
                        last_accuracy = accuracy
                        if os.getAttributeNode(
                                'osfamily') and os.getAttributeNode('osgen'):
                            str_os = '%s|%s' % (
                                os.getAttributeNode('osfamily').value,
                                os.getAttributeNode('osgen').value)
                        hardware.clear()
                        for cpe in os.getElementsByTagName('cpe'):
                            hardware.add(cpe.firstChild.nodeValue)

                if str_os != '':
                    host['os'] = str_os

            str_software = ''
            software.update(hardware)
            for s in software:
                if str_software == '':
                    str_software += '%s|' % (s)
                else:
                    str_software += ',%s|' % (s)

            host['service'] = str_ports
            host['software'] = str_software

            host['inventory_source'] = 5
            # SELECT id FROM host_source_reference WHERE name = 'NMAP';
            self.send_message(host)