Example #1
0
    def set_field(self, fieldname, value):
        if isinstance(value, MetaPacket):
            value = value.root

        try:
            ret = fieldname.split(".")
            layer = self.root.getlayer(global_trans[ret[0]][0])

            if not layer:
                return None

            if len(ret) == 2:
                setattr(layer, ret[1], value)
            elif len(ret) == 3:
                val = getattr(layer, ret[1])

                if val is not None:
                    setattr(val, ret[2], value)
                else:
                    raise Exception("Middle value is None")
            else:
                log.error("Cannot set an entire protocol")

        except Exception, err:
            log.error("Error while setting %s field to %s. Traceback:" % (fieldname, repr(value)))
            log.error(generate_traceback())
Example #2
0
    def __do_trace(self):
        try:
            dport = self.dport.get_value_as_int()
            maxttl = self.maxttl.get_value_as_int()
            timeout = self.timeout.get_value_as_int()
            target = self.target.get_text()

            log.debug("Starting %s (%s, dport=%d, maxttl=%d, timeout=%d)" %
                      (traceroute, target, dport, maxttl, timeout))

            ans, unans = traceroute(target,
                                    dport,
                                    maxttl=maxttl,
                                    timeout=timeout,
                                    verbose=False)

            self.session.context.set_trace(ans, unans)
            gobject.idle_add(self.session.reload)

        except Exception, err:
            self.session.context.set_trace(None, err)
            gobject.idle_add(self.session.reload)

            log.error("Exception in tracert:")
            log.error(generate_traceback())
Example #3
0
    def set_field(self, fieldname, value):
        if isinstance(value, MetaPacket):
            value = value.root

        try:
            ret = fieldname.split('.')
            layer = self.root.getlayer(global_trans[ret[0]][0])

            if not layer:
                return None

            if len(ret) == 2:
                setattr(layer, ret[1], value)
            elif len(ret) == 3:
                val = getattr(layer, ret[1])

                if val is not None:
                    setattr(val, ret[2], value)
                else:
                    raise Exception('Middle value is None')
            else:
                log.error('Cannot set an entire protocol')

        except Exception, err:
            log.error('Error while setting %s field to %s. Traceback:' % \
                      (fieldname, repr(value)))
            log.error(generate_traceback())
Example #4
0
    def get_field(self, fieldname, default=None):
        try:
            ret = fieldname.split('.')
            layer = self.root.getlayer(global_trans[ret[0]][0])

            if not layer:
                return default

            if len(ret) > 1:
                val = getattr(layer, ret[1])

                if len(ret) == 3 and val:
                    val = getattr(val, ret[2])

                if isinstance(val, Packet):
                    return MetaPacket(val)

                if val is None:
                    return default

                return val
            else:
                return str(layer)
        except Exception, err:
            log.error('Error while getting %s field. Traceback:' % fieldname)
            log.error(generate_traceback())
            return default
Example #5
0
    def get_field(self, fieldname, default=None):
        try:
            ret = fieldname.split(".")
            layer = self.root.getlayer(global_trans[ret[0]][0])

            if not layer:
                return default

            if len(ret) > 1:
                val = getattr(layer, ret[1])

                if len(ret) == 3 and val:
                    val = getattr(val, ret[2])

                if isinstance(val, Packet):
                    return MetaPacket(val)

                if val is None:
                    return default

                return val
            else:
                return str(layer)
        except Exception, err:
            log.error("Error while getting %s field. Traceback:" % fieldname)
            log.error(generate_traceback())
            return default
Example #6
0
def load_sequence(fname):
    try:
        return SequenceLoader(fname)
    except Exception, err:
        log.error("Error while loading sequence from %s" % fname)
        log.error(generate_traceback())

        raise err
def load_sequence(fname):
    try:
        return SequenceLoader(fname)
    except Exception, err:
        log.error("Error while loading sequence from %s" % fname)
        log.error(generate_traceback())

        raise err
Example #8
0
    def internal(mpkt):
        try:
            finger.push(mpkt, finger.TTL, mpkt.get_field('ip.ttl'))
            finger.push(mpkt, finger.DF, mpkt.get_field('ip.frag', 0) & 0x400)
            finger.push(mpkt, finger.LT, mpkt.get_field('ip.ihl', 0) * 4)

            tcpraw = mpkt.get_field('tcp')
            flags = mpkt.get_field('tcp.flags')

            if flags and finger and flags & TH_SYN:
                opt_start = 20
                opt_end = mpkt.get_field('tcp.dataofs') * 4

                finger.push(mpkt, finger.WINDOW, mpkt.get_field('tcp.window', 0))
                finger.push(mpkt, finger.TCPFLAG, (flags & TH_ACK) and 1 or 0)
                finger.push(mpkt, finger.LT, opt_end)

                while opt_start < opt_end:
                    val = ord(tcpraw[opt_start])

                    if val == TCPOPT_EOL:
                        opt_start = opt_end
                    elif val == TCPOPT_NOP:
                        finger.push(mpkt, finger.NOP, 1)
                        opt_start += 1
                    elif val == TCPOPT_SACKOK:
                        finger.push(mpkt, finger.SACK, 1)
                        opt_start += 2
                    elif val == TCPOPT_MAXSEG:
                        opt_start += 2
                        finger.push(mpkt, finger.MSS, pntos(unpack("H",
                                    tcpraw[opt_start:opt_start + 2])[0]))
                        opt_start += 2
                    elif val == TCPOPT_WSCALE:
                        opt_start += 2
                        finger.push(mpkt, finger.WS, ord(tcpraw[opt_start]))
                        opt_start += 1
                    elif val == TCPOPT_TIMESTAMP:
                        finger.push(mpkt, finger.TIMESTAMP, 1)
                        opt_start +=1
                        opt_start += ord(tcpraw[opt_start]) - 1
                    else:
                        opt_start += 1
                        if opt_start < len(tcpraw):# and ord(tcpraw[opt_start]):
                            opt_start += val - 1

                remote_os = finger.report(mpkt)

                mpkt.set_cfield('remote_os', remote_os)
                manager.user_msg(_('%s is running %s') % (mpkt.get_field('ip.src'),
                                                          remote_os),
                                 5, 'fingerprint')
        except Exception, err:
            log.error('Ignoring exception while setting fingerprint.')
            log.error(generate_traceback())

            log.debug('Clearing fingerprint.')
            finger.clear(mpkt)
Example #9
0
    def __thread_main(self):
        try:
            log.debug('Entered in __thread_main')

            packets = 0
            probes = self.probes

            while probes != 0 and self.internal:
                pkt = MetaPacket.new('ip') / MetaPacket.new('tcp')

                if self.sip is True:
                    sip = random_ip()
                elif self.sip != '0.0.0.0':
                    sip = self.sip

                if self.sport is True:
                    sport = randint(1, 65535)
                else:
                    sport = self.sport

                pkt.set_fields('ip', {
                    'dst' : self.dip,
                    'src' : sip})

                pkt.set_fields('tcp', {
                    'sport' : sport,
                    'dport' : self.dport,
                    'flags' : TH_SYN,
                    'seq' : randint(0, 2L**32-1)})

                self.context.si_l3(pkt)
                sleep(self.delay)

                probes -= 1
                packets += 1

                if self.probes > 0:
                    self.summary = AUDIT_MSG % _('%d of %d sent' \
                                   % (packets, self.probes))
                    self.percentage = (packets / float(self.probes)) * 100.0
                else:
                    self.summary = AUDIT_MSG % _('%d sent' % packets)
                    self.percentage = (self.percentage + 536870911) % \
                                      gobject.G_MAXINT

            if self.internal:
                self.summary = AUDIT_MSG % _('Finished with %d sent' % packets)
                self.internal = False
            else:
                self.summary = AUDIT_MSG % _('stopped')

            self.percentage = 100.0
            self.state = self.NOT_RUNNING

        except Exception, err:
            log.error(generate_traceback())
Example #10
0
    def __thread_main(self):
        try:
            log.debug('Entered in __thread_main')

            packets = 0
            probes = self.probes

            while probes != 0 and self.internal:
                pkt = MetaPacket.new('ip') / MetaPacket.new('tcp')

                if self.sip is True:
                    sip = random_ip()
                elif self.sip != '0.0.0.0':
                    sip = self.sip

                if self.sport is True:
                    sport = randint(1, 65535)
                else:
                    sport = self.sport

                pkt.set_fields('ip', {'dst': self.dip, 'src': sip})

                pkt.set_fields(
                    'tcp', {
                        'sport': sport,
                        'dport': self.dport,
                        'flags': TH_SYN,
                        'seq': randint(0, 2L**32 - 1)
                    })

                self.context.si_l3(pkt)
                sleep(self.delay)

                probes -= 1
                packets += 1

                if self.probes > 0:
                    self.summary = AUDIT_MSG % _('%d of %d sent' \
                                   % (packets, self.probes))
                    self.percentage = (packets / float(self.probes)) * 100.0
                else:
                    self.summary = AUDIT_MSG % _('%d sent' % packets)
                    self.percentage = (self.percentage + 536870911) % \
                                      gobject.G_MAXINT

            if self.internal:
                self.summary = AUDIT_MSG % _('Finished with %d sent' % packets)
                self.internal = False
            else:
                self.summary = AUDIT_MSG % _('stopped')

            self.percentage = 100.0
            self.state = self.NOT_RUNNING

        except Exception, err:
            log.error(generate_traceback())
Example #11
0
def save_sequence(fname, sequence, strict=True, report_recv=False, \
                  report_sent=True, tot_loop_count=None, inter=None):
    assert isinstance(sequence, Node)

    try:
        return SequenceWriter(fname, sequence, strict, report_recv, \
                              report_sent, tot_loop_count, inter).save_async()
    except Exception, err:
        log.error("Cannot while saving sequence to %s" % fname)
        log.error(generate_traceback())
        raise err
def save_sequence(fname, sequence, strict=True, report_recv=False, \
                  report_sent=True, tot_loop_count=None, inter=None):
    assert isinstance(sequence, Node)

    try:
        return SequenceWriter(fname, sequence, strict, report_recv, \
                              report_sent, tot_loop_count, inter).save_async()
    except Exception, err:
        log.error("Cannot while saving sequence to %s" % fname)
        log.error(generate_traceback())
        raise err
Example #13
0
    def load_directory(self, modpath):
        if not PM_DEVELOPMENT:
            log.error("This method should not be called in release.")
            return

        start_file = 'main'

        log.warning("You are loading a plugin without checking for needs, " \
                    "provides or conflitcts")
        log.warning("* You have been warned! *")

        log.warning("Assuming `%s' as start file!" % start_file)

        # Load the plugin
        sys.path.insert(0, os.path.abspath(modpath))

        if start_file in sys.modules:
            sys.modules.pop(start_file)

        try:
            __builtin__.__import__ = hook_import
            module = hook_import(start_file, level=0)

            if hasattr(module, "__plugins__") and \
               isinstance(module.__plugins__, list):
                lst = module.__plugins__
                ret = []

                for plug in lst:
                    try:
                        if issubclass(plug, PassiveAudit):
                            is_audit = 1
                        elif issubclass(plug, ActiveAudit):
                            is_audit = 2
                        else:
                            is_audit = 0

                        inst = plug()
                        inst.start(None)

                        if is_audit:
                            inst.register_decoders()
                            inst.register_hooks()

                        ret.append(inst)
                    except Exception, err:
                        log.critical("Error while starting %s:" % (plug))
                        log.critical(generate_traceback())
                        log.critical("Ignoring instance.")

                if not ret:
                    log.error("Not startable plugin defined in main file")
            else:
Example #14
0
    def map_thread(self, ans):
        try:
            log.debug("Plotting async")

            global glocator
            self.html_map = tracert.create_map(ans, glocator)

            log.info("Plotted")
        except Exception, err:
            log.error("Error while plotting")
            log.error(generate_traceback())

            self.html_map = "<pre>Error while plotting</pre>"
Example #15
0
    def map_thread(self, ans):
        try:
            log.debug("Plotting async")

            global glocator
            self.html_map = tracert.create_map(ans, glocator)

            log.info("Plotted")
        except Exception, err:
            log.error("Error while plotting")
            log.error(generate_traceback())

            self.html_map = "<pre>Error while plotting</pre>"
Example #16
0
    def reset_field(self, fieldname):
        try:
            ret = fieldname.split(".")
            layer = self.root.getlayer(global_trans[ret[0]][0])

            if not layer:
                return None

            if len(ret) > 1:
                delattr(layer, ret[1])
            else:
                log.error("Cannot reset an entire protocol")

        except Exception, err:
            log.error("Error while resetting %s field. Traceback:" % fieldname)
            log.error(generate_traceback())
Example #17
0
    def set_fields(self, proto, dict):
        try:
            layer = self.root.getlayer(global_trans[proto][0])

            if not layer:
                return None

            for key, value in dict.items():
                if isinstance(value, MetaPacket):
                    setattr(layer, key, value.root)
                else:
                    setattr(layer, key, value)

        except Exception, err:
            log.error("Error while setting %s fields to %s. Traceback:" % (dict, proto))
            log.error(generate_traceback())
Example #18
0
    def reset_field(self, fieldname):
        try:
            ret = fieldname.split('.')
            layer = self.root.getlayer(global_trans[ret[0]][0])

            if not layer:
                return None

            if len(ret) > 1:
                delattr(layer, ret[1])
            else:
                log.error('Cannot reset an entire protocol')

        except Exception, err:
            log.error('Error while resetting %s field. Traceback:' % \
                      fieldname)
            log.error(generate_traceback())
Example #19
0
    def set_fields(self, proto, dict):
        try:
            layer = self.root.getlayer(global_trans[proto][0])

            if not layer:
                return None

            for key, value in dict.items():
                if isinstance(value, MetaPacket):
                    setattr(layer, key, value.root)
                else:
                    setattr(layer, key, value)

        except Exception, err:
            log.error('Error while setting %s fields to %s. Traceback:' % \
                      (dict, proto))
            log.error(generate_traceback())
Example #20
0
    def __unload_hook(self, pkg):
        """
        This is the real unload procedure of plugin.
        Raise a PluginException on fail

        @return None or raise a PluginException
        """

        if not pkg in self.instances:
            raise PluginException(pkg, "Already unloaded")

        for inst in self.instances[pkg]:
            try:
                inst.stop()
            except Exception, err:
                log.critical("Error while stopping %s from %s:" % (inst, pkg))
                log.critical(generate_traceback())
                log.critical("Ignoring instance.")
    def startElement(self, name, attrs):
        if name == 'PMScapySequence':
            self.in_sequence = True

            try:
                self.attr_loopcnt = int(attrs['loopcnt'])
                self.attr_inter = float(attrs['inter'])

                self.attr_recv = int(attrs['report_recv']) != 0
                self.attr_sent = int(attrs['report_sent']) != 0
                self.attr_strict = int(attrs['strict']) != 0
            except Exception:
                if not isinstance(self.attr_loopcnt, int):
                    self.attr_loopcnt = 1
                if not isinstance(self.attr_inter, (float, int)):
                    self.attr_inter = 500
                if not isinstance(self.attr_recv, bool):
                    self.attr_recv = False
                if not isinstance(self.attr_sent, bool):
                    self.attr_sent = True
                if not isinstance(self.attr_strict, bool):
                    self.attr_strict = True

        elif self.in_sequence and name == 'SequencePacket':

            self.add_pending()

            try:
                self.packet_interval = eval(attrs['interval']) or 0
                self.packet_filter = attrs['filter']

                node = Node(
                    SequencePacket(None, self.packet_interval,
                                   self.packet_filter))

                self.current_node.append_node(node)
                self.current_node = node

                self.tree_len += 1

            except Exception, err:
                log.debug(generate_traceback())
            else:
                self.in_packet = True
Example #22
0
    def startElement(self, name, attrs):
        if name == 'PMScapySequence':
            self.in_sequence = True

            try:
                self.attr_loopcnt = int(attrs['loopcnt'])
                self.attr_inter = float(attrs['inter'])

                self.attr_recv = int(attrs['report_recv']) != 0
                self.attr_sent = int(attrs['report_sent']) != 0
                self.attr_strict = int(attrs['strict']) != 0
            except Exception:
                if not isinstance(self.attr_loopcnt, int):
                    self.attr_loopcnt = 1
                if not isinstance(self.attr_inter, (float, int)):
                    self.attr_inter = 500
                if not isinstance(self.attr_recv, bool):
                    self.attr_recv = False
                if not isinstance(self.attr_sent, bool):
                    self.attr_sent = True
                if not isinstance(self.attr_strict, bool):
                    self.attr_strict = True

        elif self.in_sequence and name == 'SequencePacket':

            self.add_pending()

            try:
                self.packet_interval = eval(attrs['interval']) or 0
                self.packet_filter = attrs['filter']

                node = Node(SequencePacket(None,
                                           self.packet_interval,
                                           self.packet_filter))

                self.current_node.append_node(node)
                self.current_node = node

                self.tree_len += 1

            except Exception, err:
                log.debug(generate_traceback())
            else:
                self.in_packet = True
Example #23
0
    def __do_trace(self):
        try:
            dport = self.dport.get_value_as_int()
            maxttl = self.maxttl.get_value_as_int()
            timeout = self.timeout.get_value_as_int()
            target = self.target.get_text()

            log.debug("Starting %s (%s, dport=%d, maxttl=%d, timeout=%d)" %
                      (traceroute, target, dport, maxttl, timeout))

            ans, unans = traceroute(target, dport, maxttl=maxttl,
                                    timeout=timeout, verbose=False)

            self.session.context.set_trace(ans, unans)
            gobject.idle_add(self.session.reload)

        except Exception, err:
            self.session.context.set_trace(None, err)
            gobject.idle_add(self.session.reload)

            log.error("Exception in tracert:")
            log.error(generate_traceback())
Example #24
0
    def get_fields(self, proto, tup):
        try:
            layer = self.root.getlayer(global_trans[proto][0])

            if not layer:
                return (None,) * len(tup)

            out = []

            for key in tup:
                value = getattr(layer, key)

                if isinstance(value, Packet):
                    value = MetaPacket(value)

                out.append(value)

            return out
        except Exception, err:
            log.error("Error while getting %s fields from %s. Traceback:" % (tup, proto))
            log.error(generate_traceback())
            return (None,) * len(tup)
Example #25
0
    def get_fields(self, proto, tup):
        try:
            layer = self.root.getlayer(global_trans[proto][0])

            if not layer:
                return (None, ) * len(tup)

            out = []

            for key in tup:
                value = getattr(layer, key)

                if isinstance(value, Packet):
                    value = MetaPacket(value)

                out.append(value)

            return out
        except Exception, err:
            log.error('Error while getting %s fields from %s. Traceback:' % \
                      (tup, proto))
            log.error(generate_traceback())
            return (None, ) * len(tup)
                except Exception, err:
                    if not options.quiet:
                        print "Wrong set expression %s" % exp

        try:
            for plug_inst in instances:
                plug_inst.start(None)

                if isinstance(plug_inst, AuditPlugin):
                    plug_inst.register_decoders()
                    plug_inst.register_hooks()

        except Exception, err:
            if not options.quiet:
                print "Error while starting plugin"
                print generate_traceback()

        AuditManager().global_conf['debug'] = True

        tester.start()
        tester.join()


if __name__ == "__main__":
    parser = optparse.OptionParser(usage='%s [options] FILE' % sys.argv[0])

    parser.add_option('-q',
                      '--quiet',
                      action='store_true',
                      dest='quiet',
                      help='If quiet suppress useless output messages')
Example #27
0
                except Exception, err:
                    if not options.quiet:
                        print "Wrong set expression %s" % exp

        try:
            for plug_inst in instances:
                plug_inst.start(None)

                if isinstance(plug_inst, AuditPlugin):
                    plug_inst.register_decoders()
                    plug_inst.register_hooks()

        except Exception, err:
            if not options.quiet:
                print "Error while starting plugin"
                print generate_traceback()

        AuditManager().global_conf['debug'] = True

        tester.start()
        tester.join()

if __name__ == "__main__":
    parser = optparse.OptionParser(usage='%s [options] FILE' % sys.argv[0])

    parser.add_option('-q', '--quiet', action='store_true', dest='quiet',
                      help='If quiet suppress useless output messages')
    parser.add_option('-f', '--passive', action='store', dest='passive',
                      help='Comma separated list of passive plugins to use')
    parser.add_option('-n', '--active', action='store', dest='active',
                      help='Comma separated list of active plugins to use')
Example #28
0
    def __init__(self, options, args):
        if not args or not os.path.exists(args[0]):
            print "I need a pcap file as input to work."
            sys.exit(-1)

        if options.datalink is None:
            datalink = IL_TYPE_ETH
        else:
            datalink = options.datalink

        tester = AuditTester(args[0], datalink)

        modules = []
        filters = []

        if options.passive:
            filters = options.passive.replace(' ', '').split(',')

        if options.active:
            filters += options.active.replace(' ', '').split(',')

        instances = []

        for passive in filters:
            if not options.quiet:
                print 'Loading plugin: %s ...' % passive,

            if os.path.exists(os.path.join(os.getcwd(), 'passive', passive)):
                path = os.path.join(os.getcwd(), 'passive', passive, 'sources')
            else:
                path = os.path.join(os.getcwd(), 'active', passive, 'sources')

            sys.path.insert(0, os.path.abspath(path))

            try:
                mod = __import__('main')
                modules.append(mod)

                pkg = None

                for name, needs, provides, conflicts in \
                    getattr(mod, '__plugins_deps__', []):

                    pkg = Package(name, needs, provides, conflicts)
                    PluginEngine().tree.add_plugin_to_cache(pkg)

                ret = []

                for kplug in getattr(mod, '__plugins__', []):
                    confs = getattr(mod, '__configurations__', [])

                    for conf_name, conf_dict in confs:
                        AuditManager().register_configuration(conf_name, conf_dict)

                    plug_inst = kplug()

                    ret.append(plug_inst)

                instances.extend(ret)

                if pkg:
                    PluginEngine().tree.modules[pkg] = mod
                    PluginEngine().tree.instances[pkg] = ret

                if not options.quiet:
                    print "OK"
            except Exception, err:
                if not options.quiet:
                    print "FAILED"

                print generate_traceback()
            finally:
Example #29
0
class SnoopTab(UmitView):
    icon_name = gtk.STOCK_INFO
    tab_position = gtk.POS_LEFT
    label_text = _('DNS Cache snoop')
    name = 'DNSCacheSnoop'

    def create_ui(self):
        self.active = False
        self.output = []

        self.toolbar = gtk.Toolbar()
        self.toolbar.set_style(gtk.TOOLBAR_ICONS)
        self.toolbar.set_orientation(gtk.ORIENTATION_HORIZONTAL)

        for name, stock, cb in (('Copy', gtk.STOCK_COPY, self.__on_copy),
                                ('Open', gtk.STOCK_OPEN, self.__on_open),
                                ('Execute', gtk.STOCK_EXECUTE,
                                 self.__on_execute)):

            act = gtk.Action(name, name, '', stock)
            act.connect('activate', cb)

            self.toolbar.insert(act.create_tool_item(), -1)

        self._main_widget.pack_start(self.toolbar, False, False)

        self.server = gtk.Entry()
        self._main_widget.pack_start(self.server, False, False)

        self.store = gtk.ListStore(bool, str, int)
        self.tree = gtk.TreeView(self.store)

        self.tree.append_column(
            gtk.TreeViewColumn('', gtk.CellRendererToggle(), active=0))

        rend = gtk.CellRendererText()
        rend.connect('edited', self.__edited_cb)
        rend.set_property('editable', True)

        col = gtk.TreeViewColumn('Host', rend, text=1)
        col.set_expand(True)

        self.tree.append_column(col)

        self.tree.append_column(
            gtk.TreeViewColumn('TTL', gtk.CellRendererText(), text=2))

        self.tree.set_rules_hint(True)

        self.selection = self.tree.get_selection()

        self.menu = gtk.Menu()

        for name, stock, cb in (('Add', gtk.STOCK_ADD, self.__on_add),
                                ('Remove', gtk.STOCK_REMOVE,
                                 self.__on_remove)):
            act = gtk.Action(name, name, '', stock)
            act.connect('activate', cb)
            self.menu.append(act.create_menu_item())

        self.tree.connect('button-press-event', self.__on_button)

        sw = gtk.ScrolledWindow()
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        sw.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        sw.add(self.tree)

        self._main_widget.pack_start(sw)
        self._main_widget.show_all()

    def __edited_cb(self, rend, path, new_text):
        iter = self.store.get_iter_from_string(path)
        self.store.set_value(iter, 1, new_text)

    def __on_button(self, tree, evt):
        if evt.button != 3:
            return False

        self.menu.show_all()
        self.menu.popup(None, None, None, evt.button, evt.time)

        return True

    def __on_add(self, widget):
        model, iter = self.selection.get_selected()
        newrow = (False, 'edit me', 0)

        if not iter:
            self.store.append(newrow)
        else:
            self.store.insert_after(None, iter, newrow)

    def __on_remove(self, widget):
        model, iter = self.selection.get_selected()

        if iter:
            self.store.remove(iter)

    def __on_copy(self, act):
        out = ''

        for row in self.store:
            out += "[%s] %s (%d)\n" % (row[0] and '+' or '-', row[1], row[2])

        if out:
            clip = gtk.clipboard_get()
            clip.set_text('Result for %s DNS server\n' %
                          self.server.get_text() + out)

    def __on_execute(self, act):
        if self.active:
            return

        self.active = True
        self.thread = None
        self.tree.set_sensitive(False)
        self.server.set_sensitive(False)
        self.toolbar.set_sensitive(False)

        server = self.server.get_text()
        targets = [row[1] for row in self.store]

        self.thread = Thread(target=self.__main_thread,
                             name='DNSCacheSnoop',
                             kwargs={
                                 'targets': targets,
                                 'server': server
                             })
        self.thread.setDaemon(True)
        self.thread.start()

        gobject.timeout_add(1000, self.__check_finished)

    def __check_finished(self):
        if self.thread is not None:
            return True

        log.debug(str(self.output))

        idx = 0
        while idx < len(self.output):
            present, ttl = self.output[idx]

            iter = self.store.get_iter((idx, ))

            if iter:
                self.store.set(iter, 0, present, 2, ttl)

            idx += 1

        self.output = []

        self.tree.set_sensitive(True)
        self.server.set_sensitive(True)
        self.toolbar.set_sensitive(True)

        self.active = False

        return False

    def __on_open(self, act):
        dialog = gtk.FileChooserDialog(_('Select a query file'),
                                       PMApp().main_window,
                                       gtk.FILE_CHOOSER_ACTION_OPEN,
                                       (gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT,
                                        gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT))

        if dialog.run() == gtk.RESPONSE_ACCEPT:
            fname = dialog.get_filename()

            if fname:
                fd = open(fname, 'r')
                contents = fd.read()
                fd.close()

                self.store.clear()

                for line in contents.splitlines():
                    line = line.strip()

                    if line:
                        self.store.append((False, line, 0))

        dialog.hide()
        dialog.destroy()

    def __main_thread(self, server, targets):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.settimeout(5)

        if ':' in server:
            server, port = server.split(':', 1)
        else:
            port = 53

        try:
            port = int(port)
        except:
            port = 53

        sock.connect((server, port))

        for target in targets:
            dnsqr = MetaPacket.new('dnsqr')
            dnsqr.set_field('dnsqr.qname', target)

            mpkt = MetaPacket.new('dns')
            mpkt.set_fields('dns', {'id': randint(0, 2L**16 - 1), 'qd': dnsqr})

            sock.send(mpkt.get_raw())

            try:
                buff = sock.recv(1024)
                mpkt = MetaPacket.new_from_str('dns', buff)

                if mpkt.get_field('dns.ancount', 0) == 0:
                    self.output.append((False, 0))
                else:
                    found = False
                    qd = mpkt.get_field('dns.an', None)

                    while qd is not None:
                        rrname = qd.get_field('dnsrr.rrname', '')

                        if rrname.startswith(target):
                            self.output.append((True, \
                                                qd.get_field('dnsrr.ttl', 0)))
                            log.debug('Reply for %s' % target)
                            found = True
                            break

                        qd = mpkt.get_field('dnsrr.payload', None)

                    if not found:
                        self.output.append((False, 0))
                        log.debug('No reply for %s' % target)
            except Exception, exc:
                log.debug('Cannot parse DNS reply for %s ' \
                          'or timeout occurred' % target)
                log.error(generate_traceback())

                self.output.append((False, 0))
    def __init__(self, options, args):
        if not args or not os.path.exists(args[0]):
            print "I need a pcap file as input to work."
            sys.exit(-1)

        if options.datalink is None:
            datalink = IL_TYPE_ETH
        else:
            datalink = options.datalink

        tester = AuditTester(args[0], datalink)

        modules = []
        filters = []

        if options.passive:
            filters = options.passive.replace(' ', '').split(',')

        if options.active:
            filters += options.active.replace(' ', '').split(',')

        instances = []

        for passive in filters:
            if not options.quiet:
                print 'Loading plugin: %s ...' % passive,

            if os.path.exists(os.path.join(os.getcwd(), 'passive', passive)):
                path = os.path.join(os.getcwd(), 'passive', passive, 'sources')
            else:
                path = os.path.join(os.getcwd(), 'active', passive, 'sources')

            sys.path.insert(0, os.path.abspath(path))

            try:
                mod = __import__('main')
                modules.append(mod)

                pkg = None

                for name, needs, provides, conflicts in \
                    getattr(mod, '__plugins_deps__', []):

                    pkg = Package(name, needs, provides, conflicts)
                    PluginEngine().tree.add_plugin_to_cache(pkg)

                ret = []

                for kplug in getattr(mod, '__plugins__', []):
                    confs = getattr(mod, '__configurations__', [])

                    for conf_name, conf_dict in confs:
                        AuditManager().register_configuration(
                            conf_name, conf_dict)

                    plug_inst = kplug()

                    ret.append(plug_inst)

                instances.extend(ret)

                if pkg:
                    PluginEngine().tree.modules[pkg] = mod
                    PluginEngine().tree.instances[pkg] = ret

                if not options.quiet:
                    print "OK"
            except Exception, err:
                if not options.quiet:
                    print "FAILED"

                print generate_traceback()
            finally:
class SequenceLoader(handler.ContentHandler):
    def __init__(self, fname):
        self.fname = fname

        self.in_node = False
        self.in_packet = False

        # Various attributes
        self.packet_interval = None
        self.packet_filter = None

        self.attr_strict = None
        self.attr_sent = None
        self.attr_recv = None
        self.attr_loopcnt = None
        self.attr_inter = None

        # Variables used to track document
        self.in_proto = False
        self.protocol = None
        self.current_protocol = None
        self.in_field = False
        self.field_id = False
        self.field_value = None

        self.tree = Node()
        self.current_node = self.tree
        self.tree_len = 0

        handler.ContentHandler.__init__(self)

    def parse(self):
        parser = make_parser()
        parser.setContentHandler(self)
        parser.parse(self.fname)
        parser.close()
        parser.reset()

        return self.tree

    def parse_async(self):
        """
        @attention Use try/except for this function
        the functions will be iterable and at every iteration will return a
        tuple of the type (tree, pktidx, percentage of loading, fsize)
        """
        parser = make_parser()
        parser.setContentHandler(self)

        position = 0
        fd = open(self.fname, 'r')
        fd.seek(0, 2)
        size = float(fd.tell())
        fd.seek(0)

        for data in fd:
            parser.feed(data)
            position += len(data)

            yield self.tree, self.tree_len, (position / size) * 100.0, size

        parser.close()
        parser.reset()

    def add_pending(self):
        if self.current_protocol:

            if self.protocol:
                self.protocol = self.protocol / self.current_protocol
            else:
                self.protocol = self.current_protocol

            self.protocol.time = self.current_protocol.time

            self.current_node.data.packet = MetaPacket(self.protocol)
            self.protocol = self.current_protocol = None

    def startElement(self, name, attrs):
        if name == 'PMScapySequence':
            self.in_sequence = True

            try:
                self.attr_loopcnt = int(attrs['loopcnt'])
                self.attr_inter = float(attrs['inter'])

                self.attr_recv = int(attrs['report_recv']) != 0
                self.attr_sent = int(attrs['report_sent']) != 0
                self.attr_strict = int(attrs['strict']) != 0
            except Exception:
                if not isinstance(self.attr_loopcnt, int):
                    self.attr_loopcnt = 1
                if not isinstance(self.attr_inter, (float, int)):
                    self.attr_inter = 500
                if not isinstance(self.attr_recv, bool):
                    self.attr_recv = False
                if not isinstance(self.attr_sent, bool):
                    self.attr_sent = True
                if not isinstance(self.attr_strict, bool):
                    self.attr_strict = True

        elif self.in_sequence and name == 'SequencePacket':

            self.add_pending()

            try:
                self.packet_interval = eval(attrs['interval']) or 0
                self.packet_filter = attrs['filter']

                node = Node(
                    SequencePacket(None, self.packet_interval,
                                   self.packet_filter))

                self.current_node.append_node(node)
                self.current_node = node

                self.tree_len += 1

            except Exception, err:
                log.debug(generate_traceback())
            else:
                self.in_packet = True

        elif self.in_packet and name == 'proto':
            try:
                proto_id = attrs['id']
                proto_time = eval(attrs['time'])

                protocol = get_proto(proto_id)()
                protocol.time = proto_time

                if self.current_protocol is not None:

                    if self.protocol is not None:
                        self.protocol = self.protocol / self.current_protocol
                    else:
                        self.protocol = self.current_protocol

                self.current_protocol = protocol
            except Exception, err:
                log.debug(generate_traceback())
Example #32
0
    def __load_hook(self, pkg):
        """
        This is the real load procedure of plugin.
        We'll use zipmodule to import and a global function expose
        to provide a simple method to access files inside the zip file
        to plugin.

        Raise a PluginException on fail

        @return None or raise a PluginException
        """

        if pkg in self.instances:
            raise PluginException(pkg, "Already present")

        # We need to get the start-file field from pkg and then try
        # to import it

        modpath = os.path.join(pkg.get_path(), 'lib')
        sys.path.insert(0, os.path.abspath(modpath))

        # This were removed
        fname = os.path.join(pkg.get_path(), 'bin', pkg.start_file)
        sys.path.insert(0, os.path.abspath(os.path.dirname(fname)))

        if pkg.start_file in sys.modules:
            sys.modules.pop(pkg.start_file)

        try:
            try:
                # We add to modules to avoid deleting and stop working plugin ;)
                sys.plugins_path.insert(0, pkg)
                module = self.__cache_import(pkg)

            except Exception, err:
                sys.plugins_path.pop(0)
                raise PluginException(pkg, str(err))

        finally:
            # Check that
            sys.path.pop(0)

        if hasattr(module, "__plugins__") and \
           isinstance(module.__plugins__, list):
            lst = module.__plugins__
            ret = []

            for plug in lst:
                try:

                    if issubclass(plug, PassiveAudit):
                        is_audit = 1
                    elif issubclass(plug, ActiveAudit):
                        is_audit = 2
                    else:
                        is_audit = 0

                    inst = plug()
                    inst.start(pkg)

                    if is_audit:
                        inst.register_decoders()
                        inst.register_hooks()

                    ret.append(inst)
                except Exception, err:
                    log.critical("Error while starting %s from %s:" % (plug,
                                                                       pkg))
                    log.critical(generate_traceback())
                    log.critical("Ignoring instance.")

            if not ret:
                raise PluginException(pkg, \
                              "No startablePlugin subclass in %s" % pkg)

            self.instances[pkg] = ret