Example #1
0
    def bind_perspective(self, ptype, callback):
        """
        Bind the perspective 'type'

        The callback should be of the type
          def perspective_cb(perspective, type, already_present, added)

        @param type the perspective's type (see also PerspectiveType)
        @param callback the callback to execute when a new
               perspective of type 'type' is created
        """

        log.debug(
            "Binding method %s for perspective of type %s" % \
            (callback, PerspectiveType.types[ptype])
        )

        self.perspective_binder[ptype].append(callback)

        for page in ServiceBus().call('pm.sessions', 'get_sessions'):
            if not isinstance(page, Session):
                continue

            for perspective in page.perspectives:
                idx = PerspectiveType.types[type(perspective)]

                callback(perspective, idx, True, True)
Example #2
0
    def unbind_session(self, ptype, persp_klass):
        try:
            for i in range(len(self.session_binder[ptype])):
                (klass, show, resize) = self.session_binder[ptype][i]

                if klass is not persp_klass:
                    continue

                del self.session_binder[ptype][i]

                klass = SessionType.types[ptype]

                for page in ServiceBus().call('pm.sessions', 'get_sessions'):
                    if isinstance(page, klass):
                        page.remove_perspective(persp_klass)

                log.debug(
                    "Binding method %s for perspective of type %s removed" % \
                    (persp_klass, SessionType.types[ptype])
                )

                return True
        except:
            log.error(
                "Failed to remove binding method %s for session of type %s" % \
                (persp_klass, SessionType.type[ptype])
            )

        return False
Example #3
0
    def debind_perspective(self, type, callback):
        """
        Remove the binding callback for perspective of type 'type'

        @param type the perspective type
        @param callback the callback to remove
        @return True if the callback is removed correctly
        """

        try:
            self.perspective_binder[type].remove(callback)

            for page in ServiceBus().call('pm.sessions', 'get_sessions'):
                if not isinstance(page, Session):
                    continue

                for perspective in page.perspectives:
                    idx = PerspectiveType.types[type(perspective)]

                    callback(perspective, idx, True, False)

            log.debug(
                "Binding method %s for perspective of type %s removed" % \
                (callback, PerspectiveType.types[type])
            )

            return True
        except:
            log.error(
                "Failed to remove binding method %s "
                "for perspective of type %s" % \
                (callback, PerspectiveType.types[type])
            )

        return False
Example #4
0
    def register_session(self, sessklass, ctxklass=None):
        """
        Register a custom session class and returns the new id
        of the SessionType

        @param sessklass the custom session class
        @param ctxklass the context class to use
        @return id
        """

        log.debug('Registering a new session')

        if sessklass.session_menu is not None:
            log.debug('Creating new menu entry named %s for the session' % \
                      sessklass.session_menu)

            item = self.ui_manager.get_widget('/menubar/File')
            menu = item.get_submenu()

            item = gtk.MenuItem(sessklass.session_menu)
            item.connect('activate', self.create_session, (sessklass, ctxklass))
            item.show()

            menu.insert(item, 2)

            sessklass.session_menu_object = item

        return SessionType.add_session(sessklass)
    def __on_idle(self, udata):
        if self.type == FileOperation.TYPE_LOAD:
            ctx, rctx = udata

            self.loading_view = True

            log.debug('Creating a new session after loading for %s' % str(ctx))

            if ctx is backend.SequenceContext:
                from umit.pm.gui.sessions.sequencesession import SequenceSession

                ServiceBus().call('pm.sessions', 'bind_session',
                                  SequenceSession, rctx)

            elif ctx is backend.SniffContext or \
                 ctx is backend.StaticContext:

                from umit.pm.gui.sessions.sniffsession import SniffSession

                ServiceBus().call('pm.sessions', 'bind_session',
                                  SniffSession, rctx)

        else:
            from umit.pm.gui.sessions.sniffsession import SniffSession

            if isinstance(self.session, SniffSession):
                self.session.sniff_page.statusbar.label = '<b>%s</b>' % \
                                                          self.ctx.summary
        self.loading_view = False
        self.percentage = 100.0
        self.state = self.NOT_RUNNING

        # Force update.
        self.notify_parent()
        return False
Example #6
0
    def __on_selection_changed(self, sel):
        sel = self.tree.get_selection()

        if self.active_packets:
            self.active_packets = []

        if sel.get_mode() == gtk.SELECTION_MULTIPLE:
            model, lst = sel.get_selected_rows()

            for path in lst:
                # We are the list store
                packet = model.get_value(model.get_iter(path), 1)
                self.active_packets.append(packet)

            log.debug("Repopulating active_packets with selection %s" % \
                      self.active_packets)

            self.session.set_active_packet(None)

        elif sel.get_mode() == gtk.SELECTION_SINGLE:
            ret = sel.get_selected()

            if ret:
                model, iter = ret

                if iter:
                    self.session.set_active_packet(model.get_value(iter, 0))
Example #7
0
def create_map(ans, locator):
    log.debug("Creating map")

    dct = ans.get_trace()

    if not dct.keys():
        return ""

    if not locator:
        return "<pre>Locator is not available.<br/>" \
               "Probably the geoip database is not present.</pre>"

    key = dct.keys()[0]
    routes = dct[key].items()
    routes.sort()

    ip = get_my_ip()
    last = locator.lon_lat(ip)

    points = []

    for k, (ip, is_ok) in routes:
        loc = locator.lon_lat(ip)

        if loc is None:
            loc = last
        else:
            last = loc

        points.append((ip, loc))

    return generate_map(points)
    def __init__(self, packet, count, inter, \
                 iface=None, strict=True, report_recv=False, \
                 report_sent=True, background=True):
        """
        Construct a SendReceive Operation

        @param packet the packet to send
        @param count how many times the packet will be sent
        @param inter the interval between emission
        @param iface the iface to listen to
        @param strict strict checking for reply
        @param report_recv report received packets
        @param report_sent report sent packets
        @param background if the operation should have a session when starts
        """

        capmethod = Prefs()['backend.system.sendreceive.capmethod'].value

        if capmethod < 0 or capmethod > 2:
            Prefs()['backend.system.sendreceive.capmethod'].value = 0
            capmethod = 0

        log.debug('Using %d as capmethod for SendReceiveContext' % capmethod)

        Operation.__init__(self)
        backend.SendReceiveContext.__init__(self, packet, count, inter, iface,
                                            strict, report_recv, report_sent,
                                            capmethod, self.__send_callback,
                                            self.__receive_callback, None,
                                            None)

        if background:
            self.session = None
        else:
            self.__create_session()
Example #9
0
    def remove_session(session):
        del SessionType.types[session.session_id]
        del SessionType.types[session]

        log.debug("Deregistering %s (%d, %s)" % (session,
                                                 session.session_id,
                                                 session.session_name))
    def __on_idle(self, udata):
        if self.type == FileOperation.TYPE_LOAD:
            ctx, rctx = udata

            self.loading_view = True

            log.debug('Creating a new session after loading for %s' % str(ctx))

            if ctx is backend.SequenceContext:
                from umit.pm.gui.sessions.sequencesession import SequenceSession

                ServiceBus().call('pm.sessions', 'bind_session',
                                  SequenceSession, rctx)

            elif ctx is backend.SniffContext or \
                 ctx is backend.StaticContext:

                from umit.pm.gui.sessions.sniffsession import SniffSession

                ServiceBus().call('pm.sessions', 'bind_session', SniffSession,
                                  rctx)

        else:
            from umit.pm.gui.sessions.sniffsession import SniffSession

            if isinstance(self.session, SniffSession):
                self.session.sniff_page.statusbar.label = '<b>%s</b>' % \
                                                          self.ctx.summary
        self.loading_view = False
        self.percentage = 100.0
        self.state = self.NOT_RUNNING

        # Force update.
        self.notify_parent()
        return False
Example #11
0
    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 register_session(self, sessklass, ctxklass=None):
        """
        Register a custom session class and returns the new id
        of the SessionType

        @param sessklass the custom session class
        @param ctxklass the context class to use
        @return id
        """

        log.debug('Registering a new session')

        if sessklass.session_menu is not None:
            log.debug('Creating new menu entry named %s for the session' % \
                      sessklass.session_menu)

            item = self.ui_manager.get_widget('/menubar/File')
            menu = item.get_submenu()

            item = gtk.MenuItem(sessklass.session_menu)
            item.connect('activate', self.create_session,
                         (sessklass, ctxklass))
            item.show()

            menu.insert(item, 2)

            sessklass.session_menu_object = item

        return SessionType.add_session(sessklass)
    def __on_field_selected(self, tree, packet=None, proto=None, field=None):
        if not proto or not field:
            return

        if packet in self.notify:
            for cb in self.notify[packet]:
                cb(packet, proto, field, False)

        # We should select also the bounds in HexView
        page = ServiceBus().call('pm.sessions', 'get_current_session')

        if page:
            start = backend.get_field_offset(packet, proto, field)
            length = backend.get_field_size(proto, field)

            log.debug('Field %s start at %d and finish at %d' %
                      (field, start, length))

            if length == 0:
                # Deselect all
                page.packet_page.hexview.select_block(0, 0)
                return

            page.packet_page.hexview.select_block(start / 8,
                                                  max(length / 8, 1))
Example #14
0
    def reload_webpage(self):
        if not self.session.packet:
            return

        page = self.session.packet.cfields.get('dissector.http.response', None)
        headers = self.session.packet.cfields.get('dissector.http.headers',
                                                  None)

        if not page:
            self.webview.load_html_string('<pre>No HTTP payload set.<pre>',
                                          'file:///')
            return

        log.debug('These are the available headers: %s' % headers)
        log.debug('Looking for content type ...')

        if headers and 'content-type' in headers:
            conttype = headers['content-type'][0]

            if not conttype.startswith('text/'):
                self.webview.load_html_string(g_js_text % conttype, 'file:///')
                return
        try:
            self.webview.load_html_string(unicode(page), 'file:///')
        except:
            self.webview.load_html_string('<pre>Not plain text</pre>',
                                          'file:///')
    def register_notify_for(self, packet, callback):
        if packet in self.notify:
            self.notify[packet].append(callback)
        else:
            self.notify[packet] = [callback]

        log.debug("%d callbacks for %s" % (len(self.notify[packet]), packet))
    def update(self, conn, mpkt):
        log.debug("Updating connection %s" % conn)

        conn.ts = time.time()

        if mpkt.l4_flags & TH_SYN:
            conn.status = CN_OPENING
        elif mpkt.l4_flags & TH_FIN:
            conn.status = CN_CLOSING
        elif mpkt.l4_flags & TH_ACK:
            if conn.status == CN_OPENING:
                conn.status = CN_OPEN
            elif conn.status == CN_CLOSING:
                conn.status = CN_CLOSED

        if mpkt.l4_flags & TH_PSH:
            conn.status = CN_ACTIVE

        if mpkt.l4_flags & TH_RST:
            conn.status = CN_KILLED

        conn.add_buf(mpkt)

        if mpkt.l4_proto == NL_TYPE_UDP:
            conn.status = CN_ACTIVE

        if mpkt.flags & MPKT_MODIFIED or mpkt.flags & MPKT_DROPPED:
            conn.flags |= CN_MODIFIED
    def _thread_main(self, udata=None):
        if self.type == FileOperation.TYPE_LOAD:
            ctx = udata
            rctx = None

            log.debug('Loading file as %s' % str(ctx))

            if ctx is backend.SequenceContext:
                rctx = backend.SequenceContext(self.file)

            elif ctx is backend.SniffContext or \
                 ctx is backend.StaticContext:

                rctx = backend.StaticContext(self.file, self.file,
                                 Prefs()['backend.system.static.audits'].value)

            if rctx is not None:
                # Let's update our operation directly from load
                if rctx.load(operation=self) == True:
                    # Now let's add a callback to when
                    gobject.idle_add(self.__on_idle, (ctx, rctx))
                else:
                    log.error('Error while loading context on %s.' % self.file)
                    self.state = self.NOT_RUNNING
        else:
            log.debug('Saving %s to %s' % (self.ctx, self.ctx.cap_file))

            if self.ctx.save(operation=self) == True:
                gobject.idle_add(self.__on_idle, ())
            else:
                log.error('Error while saving context on %s.' % \
                          self.ctx.cap_file)
                self.state = self.NOT_RUNNING

        self.thread = None
Example #18
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())
    def update(self, conn, mpkt):
        log.debug("Updating connection %s" % conn)

        conn.ts = time.time()

        if mpkt.l4_flags & TH_SYN:
            conn.status = CN_OPENING
        elif mpkt.l4_flags & TH_FIN:
            conn.status = CN_CLOSING
        elif mpkt.l4_flags & TH_ACK:
            if conn.status == CN_OPENING:
                conn.status = CN_OPEN
            elif conn.status == CN_CLOSING:
                conn.status = CN_CLOSED

        if mpkt.l4_flags & TH_PSH:
            conn.status = CN_ACTIVE

        if mpkt.l4_flags & TH_RST:
            conn.status = CN_KILLED

        conn.add_buf(mpkt)

        if mpkt.l4_proto == NL_TYPE_UDP:
            conn.status = CN_ACTIVE

        if mpkt.flags & MPKT_MODIFIED or mpkt.flags & MPKT_DROPPED:
            conn.flags |= CN_MODIFIED
Example #20
0
    def run(self):
        packet = self.metapacket.root

        # If is setted to 0 we need to do an infinite loop
        # so this variable should be negative

        if not self.count:
            log.debug("This is an infinite loop.")
            self.count = -1

        try:
            while self.count:
                self.socket.send(packet)

                if self.count > 0:
                    self.count -= 1

                if self.callback(self.metapacket, self.udata) == True:
                    log.debug("The send callback want to exit")
                    return

                time.sleep(self.inter)

        except socket.error, (errno, err):
            self.callback(Exception(err), self.udata)
            return
Example #21
0
    def __on_quit(self, *args):
        self.hide()

        # We need to stop the pending sniff threads
        lst = []

        for page in ServiceBus().call('pm.sessions', 'get_sessions'):
            if isinstance(page, Session) and \
               isinstance(page.context, backend.TimedContext):
                lst.append(page.context)

        for ctx in lst:
            ctx.stop()

        # Avoids joining all threads are daemon
        #for ctx in lst:
        #    ctx.join()

        errs = []

        try:
            log.debug('Saving options before exiting')
            Prefs().write_options()
        except IOError, err:
            errs.append(err)
Example #22
0
def reset_routes(to=None):
    """
    Reset the routes
    @param to a list of tuples in the form of (net, mask, gw, iface, outip) or
              None
    """

    if not to:
        conf.route.resync()
    else:
        conf.route.routes = []

        for (net, msk, gw, iface, outip) in to:
            # We need to pack netmask to net
            # so we need to count the bits of the netmask

            try:
                if bin(0): pass
            except NameError, ne:
                bin = lambda x: (lambda: '-' + bin(-x), lambda: '0b' + '01'[
                    x & 1], lambda: bin(x >> 1) + '01'[x & 1])[1 + (x > 1) -
                                                               (x < 0)]()

            mask = bin(struct.unpack(">L", socket.inet_aton(msk))[0])[2:]

            try:
                bits = mask.index("0")
            except:
                bits = len(mask)

            log.debug("Mask: %s -> %d bits" % (msk, bits))
            log.debug("%s/%d on %s (%s) -> %s" % (net, bits, outip, iface, gw))
            conf.route.add(net=("%s/%d" % (net, bits)), gw=gw, dev=iface)
Example #23
0
    def __send_thread(self):
        try:
            packet = self.metapacket.root

            if not self.scount:
                log.debug("This is an infinite loop")
                self.scount = -1

            while self.scount:
                self.send_sock.send(packet)

                if self.scount > 0:
                    self.scount -= 1

                if self.scallback(self.metapacket, self.count - self.scount, \
                                  self.sudata):

                    log.debug("send callback want to exit")
                    break

                time.sleep(self.inter)
        except SystemExit:
            pass
        except Exception, err:
            log.error("Error in _sndrecv_sthread(PID: %d EXC: %s)" % \
                      (os.getpid(), str(err)))
Example #24
0
    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
Example #25
0
    def reload_webpage(self):
        if not self.session.packet:
            return

        page = self.session.packet.cfields.get('dissector.http.response', None)
        headers = self.session.packet.cfields.get('dissector.http.headers',
                                                  None)

        if not page:
            self.webview.load_html_string('<pre>No HTTP payload set.<pre>',
                                          'file:///')
            return

        log.debug('These are the available headers: %s' % headers)
        log.debug('Looking for content type ...')

        if headers and 'content-type' in headers:
            conttype = headers['content-type'][0]

            if not conttype.startswith('text/'):
                self.webview.load_html_string(g_js_text % conttype,
                                              'file:///')
                return
        try:
            self.webview.load_html_string(unicode(page), 'file:///')
        except:
            self.webview.load_html_string('<pre>Not plain text</pre>',
                                          'file:///')
Example #26
0
    def __on_selection_changed(self, sel):
        sel = self.tree.get_selection()

        if self.active_packets:
            self.active_packets = []

        if sel.get_mode() == gtk.SELECTION_MULTIPLE:
            model, lst = sel.get_selected_rows()

            for path in lst:
                # We are the list store
                packet = model.get_value(model.get_iter(path), 1)
                self.active_packets.append(packet)

            log.debug("Repopulating active_packets with selection %s" % \
                      self.active_packets)

            self.session.set_active_packet(None)

        elif sel.get_mode() == gtk.SELECTION_SINGLE:
            ret = sel.get_selected()

            if ret:
                model, iter = ret

                if iter:
                    self.session.set_active_packet(model.get_value(iter, 0))
Example #27
0
    def __init__(self, value, \
                 name=None, def_value=None, desc=None, \
                 attrs=(), parent=None):
        """
        Create a variable

        @param value the value for variable
        @param name the name for variable (optional if are in list)
        @param def_val the default value for variable (optional if is user conf)
        @param desc the description of value (optional if in user conf)
        @param attrs a list of attributes
        @param sectiondict the section dict
        """
        self._value = self.__class__.convert(value)
        self._name = name
        self._def_val = self.__class__.convert(def_value)
        self._desc = desc
        self._parent = parent

        # Compatibility for child objects
        self.add_attribute(attrs, 'id', Integer, '_id')

        self.set_attributes(attrs)
        self.check_validity()

        if not Variable.setted(self._value):
            raise Exception("Value not setted")
        
        if not isinstance(self._value, self.__class__.element_type):
            raise Exception("Unable to set a valid type")
        
        log.debug(">>> Variable named '%s' allocate with value '%s'" % (self._name, self._value))
Example #28
0
    def __on_discover(self, mpkt):
        values = self.get_values(mpkt)

        spoof = MetaPacket.new_from_layer(mpkt, 'bootp')
        spoof.set_field('bootp.op', BOOTP_REPLY)

        try:
            client_ip = self.pool_iter.next()
        except StopIteration:
            log.debug('No available IP address')
            return

        spoof.set_field('bootp.yiaddr', client_ip)
        spoof.set_field('bootp.siaddr', self.session.context.get_ip1())

        options = self.setup_options(values).items()
        options.append(('message-type', 'offer'))
        options.append('end')

        spoof.set_field('dhcp.options', options)

        self.send_dhcp(
            self.session.context.get_ip1(),
            mpkt.l3_src != '0.0.0.0' and mpkt.l3_src or '255.255.255.255',
            mpkt.l2_src, spoof)
    def bind_perspective(self, ptype, callback):
        """
        Bind the perspective 'type'

        The callback should be of the type
          def perspective_cb(perspective, type, already_present, added)

        @param type the perspective's type (see also PerspectiveType)
        @param callback the callback to execute when a new
               perspective of type 'type' is created
        """

        log.debug(
            "Binding method %s for perspective of type %s" % \
            (callback, PerspectiveType.types[ptype])
        )

        self.perspective_binder[ptype].append(callback)

        for page in ServiceBus().call('pm.sessions', 'get_sessions'):
            if not isinstance(page, Session):
                continue

            for perspective in page.perspectives:
                idx = PerspectiveType.types[type(perspective)]

                callback(perspective, idx, True, True)
    def unbind_session(self, ptype, persp_klass):
        try:
            for i in range(len(self.session_binder[ptype])):
                (klass, show, resize) = self.session_binder[ptype][i]

                if klass is not persp_klass:
                    continue

                del self.session_binder[ptype][i]

                klass = SessionType.types[ptype]

                for page in ServiceBus().call('pm.sessions', 'get_sessions'):
                    if isinstance(page, klass):
                        page.remove_perspective(persp_klass)

                log.debug(
                    "Binding method %s for perspective of type %s removed" % \
                    (persp_klass, SessionType.types[ptype])
                )

                return True
        except:
            log.error(
                "Failed to remove binding method %s for session of type %s" % \
                (persp_klass, SessionType.type[ptype])
            )

        return False
    def debind_perspective(self, type, callback):
        """
        Remove the binding callback for perspective of type 'type'

        @param type the perspective type
        @param callback the callback to remove
        @return True if the callback is removed correctly
        """

        try:
            self.perspective_binder[type].remove(callback)

            for page in ServiceBus().call('pm.sessions', 'get_sessions'):
                if not isinstance(page, Session):
                    continue

                for perspective in page.perspectives:
                    idx = PerspectiveType.types[type(perspective)]

                    callback(perspective, idx, True, False)

            log.debug(
                "Binding method %s for perspective of type %s removed" % \
                (callback, PerspectiveType.types[type])
            )

            return True
        except:
            log.error(
                "Failed to remove binding method %s "
                "for perspective of type %s" % \
                (callback, PerspectiveType.types[type])
            )

        return False
Example #32
0
    def register_notify_for(self, packet, callback):
        if packet in self.notify:
            self.notify[packet].append(callback)
        else:
            self.notify[packet] = [callback]

        log.debug("%d callbacks for %s" % (len(self.notify[packet]), packet))
Example #33
0
    def run(self):
        packet = self.metapacket.root

        # If is setted to 0 we need to do an infinite loop
        # so this variable should be negative

        if not self.count:
            log.debug("This is an infinite loop.")
            self.count = -1

        try:
            while self.count:
                self.socket.send(packet)

                if self.count > 0:
                    self.count -= 1

                if self.callback(self.metapacket, self.udata) == True:
                    log.debug("The send callback want to exit")
                    return

                time.sleep(self.inter)

        except socket.error, (errno, err):
            self.callback(Exception(err), self.udata)
            return
Example #34
0
    def __send_thread(self):
        try:
            packet = self.metapacket.root

            if not self.scount:
                log.debug("This is an infinite loop")
                self.scount = -1

            while self.scount:
                self.send_sock.send(packet)

                if self.scount > 0:
                    self.scount -= 1

                if self.scallback(self.metapacket, self.count - self.scount, \
                                  self.sudata):

                    log.debug("send callback want to exit")
                    break

                time.sleep(self.inter)
        except SystemExit:
            pass
        except Exception, err:
            log.error("Error in _sndrecv_sthread(PID: %d EXC: %s)" % \
                      (os.getpid(), str(err)))
Example #35
0
def reset_routes(to=None):
    """
    Reset the routes
    @param to a list of tuples in the form of (net, mask, gw, iface, outip) or
              None
    """

    if not to:
        conf.route.resync()
    else:
        conf.route.routes = []

        for (net, msk, gw, iface, outip) in to:
            # We need to pack netmask to net
            # so we need to count the bits of the netmask

            try:
                if bin(0): pass
            except NameError, ne:
                bin = lambda x: (
                                 lambda: '-' + bin(-x),
                                 lambda: '0b' + '01'[x & 1],
                                 lambda: bin(x >> 1) + '01'[x & 1]
                                )[1 + (x > 1) - (x < 0)]()

            mask = bin(struct.unpack(">L", socket.inet_aton(msk))[0])[2:]

            try:
                bits = mask.index("0")
            except:
                bits = len(mask)

            log.debug("Mask: %s -> %d bits" % (msk, bits))
            log.debug("%s/%d on %s (%s) -> %s" % (net, bits, outip, iface, gw))
            conf.route.add(net=("%s/%d" % (net, bits)), gw=gw, dev=iface)
Example #36
0
    def __init__(self, value, \
                 name=None, def_value=None, desc=None, \
                 attrs=(), parent=None):
        """
        Create a variable

        @param value the value for variable
        @param name the name for variable (optional if are in list)
        @param def_val the default value for variable (optional if is user conf)
        @param desc the description of value (optional if in user conf)
        @param attrs a list of attributes
        @param sectiondict the section dict
        """
        self._value = self.__class__.convert(value)
        self._name = name
        self._def_val = self.__class__.convert(def_value)
        self._desc = desc
        self._parent = parent

        # Compatibility for child objects
        self.add_attribute(attrs, 'id', Integer, '_id')

        self.set_attributes(attrs)
        self.check_validity()

        if not Variable.setted(self._value):
            raise Exception("Value not setted")

        if not isinstance(self._value, self.__class__.element_type):
            raise Exception("Unable to set a valid type")

        log.debug(">>> Variable named '%s' allocate with value '%s'" %
                  (self._name, self._value))
    def __on_quit(self, *args):
        self.hide()

        # We need to stop the pending sniff threads
        lst = []

        for page in ServiceBus().call('pm.sessions', 'get_sessions'):
            if isinstance(page, Session) and \
               isinstance(page.context, backend.TimedContext):
                lst.append(page.context)

        for ctx in lst:
            ctx.stop()

        # Avoids joining all threads are daemon
        #for ctx in lst:
        #    ctx.join()

        errs = []

        try:
            log.debug('Saving options before exiting')
            Prefs().write_options()
        except IOError, err:
            errs.append(err)
    def add(self, mpkt, hv):
        conn = Connection(mpkt)

        log.debug("Adding new connection %s" % conn)

        self.connections[hv].append(conn)
        self.update(conn, mpkt)
        self.conn_list.append(conn)
    def start_new_audit(self, dev1, dev2, bpf_filter, skipfwd, unoffensive):
        log.debug('Creating a new AuditOperation using dev1: %s dev2: %s '
                  'bpf: %s skipfwd: %s unoffensive: %s' \
                  % (dev1, dev2, bpf_filter, skipfwd, unoffensive))

        tab = self.get_tab('OperationsTab')
        tab.tree.append_operation(AuditOperation(dev1, dev2, bpf_filter, \
                                                 skipfwd, unoffensive))
    def add(self, mpkt, hv):
        conn = Connection(mpkt)

        log.debug("Adding new connection %s" % conn)

        self.connections[hv].append(conn)
        self.update(conn, mpkt)
        self.conn_list.append(conn)
Example #41
0
    def start_new_audit(self, dev1, dev2, bpf_filter, skipfwd, unoffensive):
        log.debug('Creating a new AuditOperation using dev1: %s dev2: %s '
                  'bpf: %s skipfwd: %s unoffensive: %s' \
                  % (dev1, dev2, bpf_filter, skipfwd, unoffensive))

        tab = self.get_tab('OperationsTab')
        tab.tree.append_operation(AuditOperation(dev1, dev2, bpf_filter, \
                                                 skipfwd, unoffensive))
Example #42
0
    def add_mitm_attack(self, name, lbl, tooltip, stock):
        log.debug('Registering new MITM menu entry for \'%s\' attack' % lbl)

        import umit.pm.gui.core.app

        return umit.pm.gui.core.app.PMApp().main_window.\
               register_audit_mitm_item(name, lbl, tooltip, stock,
                                        self.on_input_request)
Example #43
0
 def run_hook_point(self, name, *args, **kwargs):
     idx = 0
     log.debug('Starting hook cascade for %s' % name)
     while name in self._hooks and idx < len(self._hooks[name]):
         callback = self._hooks[name][idx]
         log.debug('Callback %d is %s' % (idx, callback))
         callback(*args, **kwargs)
         idx += 1
    def add_mitm_attack(self, name, lbl, tooltip, stock):
        log.debug('Registering new MITM menu entry for \'%s\' attack' % lbl)

        import umit.pm.gui.core.app

        return umit.pm.gui.core.app.PMApp().main_window.\
               register_audit_mitm_item(name, lbl, tooltip, stock,
                                        self.on_input_request)
 def run_hook_point(self, name, *args, **kwargs):
     idx = 0
     log.debug('Starting hook cascade for %s' % name)
     while name in self._hooks and idx < len(self._hooks[name]):
         callback = self._hooks[name][idx]
         log.debug('Callback %d is %s' % (idx, callback))
         callback(*args, **kwargs)
         idx += 1
Example #46
0
    def add_new_tcp(self, mpkt):
        """
        @param mpkt a MetaPacket object
        """
        ctup = (inet_aton(mpkt.l3_src),
                inet_aton(mpkt.l3_dst),
                mpkt.l4_src, mpkt.l4_dst)

        hash_idx = hash(ctup[0]) ^ hash(ctup[1]) ^ hash(ctup[2] ^ ctup[3])

        if self.n_streams >= self.max_streams:
            orig_client_state = self.oldest_stream.client.state
            self.oldest_stream.state = CONN_TIMED_OUT

            for listener in self.oldest_stream.listeners:
                listener(self.oldest_stream, mpkt, None)

            self.free_tcp_stream(self.oldest_stream)

            if orig_client_state != TCP_SYN_SENT:
                log.debug('Removing last stream. Limit hit.')

        new_stream = self.free_streams

        if not new_stream:
            raise Exception('No mem')

        self.free_streams = new_stream.next_free

        new_stream.reset(*ctup)

        self.n_streams += 1
        tolink = self.tcp_streams.get(hash_idx, None)

        new_stream.client.state = TCP_SYN_SENT
        new_stream.client.seq = \
        new_stream.client.first_data_seq = mpkt.l4_seq + 1
        new_stream.client.window = mpkt.get_field('tcp.window', 0)

        new_stream.client.ts_on, new_stream.client.curr_ts = get_ts(mpkt)
        new_stream.client.wscale_on, new_stream.client.wscale = get_wscale(mpkt)

        new_stream.server.state = TCP_CLOSE
        new_stream.next_node = tolink

        if tolink:
            tolink.prev_node = new_stream

        self.tcp_streams[hash_idx] = new_stream

        new_stream.next_time = self.latest_stream

        if not self.oldest_stream:
            self.oldest_stream = new_stream
        if self.latest_stream:
            self.latest_stream.prev_time = new_stream

        self.latest_stream = new_stream
Example #47
0
        def load(self, operation=None):
            log.debug("Loading sequence from %s" % self.cap_file)

            if self.cap_file:
                self.seq = None

                try:
                    plen = 0
                    fsize = None

                    loader = load_sequence(self.cap_file)

                    for tree, tlen, perc, size in loader.parse_async():
                        if operation and tlen % 10 == 0 :

                            if not fsize:
                                if size >= 1024 ** 3:
                                    fsize = "%.1f GB" % (size / (1024.0 ** 3))
                                elif size >= 1024 ** 2:
                                    fsize = "%.1f MB" % (size / (1024.0 ** 2))
                                else:
                                    fsize = "%.1f KB" % (size / 1024.0)

                            operation.summary = \
                                _('Loading sequence %s - %d packets (%s)') % \
                                 (self.cap_file, tlen, fsize)
                            operation.percentage = perc

                        self.seq = tree
                        plen = tlen

                    self.tot_loop_count = loader.attr_loopcnt
                    self.inter = loader.attr_inter

                    self.strict = loader.attr_strict
                    self.report_sent = loader.attr_sent
                    self.report_recv = loader.attr_recv

                    self.title = self.cap_file
                    self.summary = \
                        _('Sequence %s loaded - %d packets (%s)') % \
                         (self.cap_file, plen, fsize)

                    if operation:
                        operation.summary = self.summary
                        operation.percentage = 100.0

                except Exception, err:
                    self.seq = None
                    self.summary = str(err)

                    if operation:
                        operation.summary = str(err)
                        operation.percentage = 100.0

                if self.seq is not None:
                    self.status = self.SAVED
                    return True
Example #48
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 #49
0
        def load(self, operation=None):
            log.debug("Loading sequence from %s" % self.cap_file)

            if self.cap_file:
                self.seq = None

                try:
                    plen = 0
                    fsize = None

                    loader = load_sequence(self.cap_file)

                    for tree, tlen, perc, size in loader.parse_async():
                        if operation and tlen % 10 == 0:

                            if not fsize:
                                if size >= 1024**3:
                                    fsize = "%.1f GB" % (size / (1024.0**3))
                                elif size >= 1024**2:
                                    fsize = "%.1f MB" % (size / (1024.0**2))
                                else:
                                    fsize = "%.1f KB" % (size / 1024.0)

                            operation.summary = \
                                _('Loading sequence %s - %d packets (%s)') % \
                                 (self.cap_file, tlen, fsize)
                            operation.percentage = perc

                        self.seq = tree
                        plen = tlen

                    self.tot_loop_count = loader.attr_loopcnt
                    self.inter = loader.attr_inter

                    self.strict = loader.attr_strict
                    self.report_sent = loader.attr_sent
                    self.report_recv = loader.attr_recv

                    self.title = self.cap_file
                    self.summary = \
                        _('Sequence %s loaded - %d packets (%s)') % \
                         (self.cap_file, plen, fsize)

                    if operation:
                        operation.summary = self.summary
                        operation.percentage = 100.0

                except Exception, err:
                    self.seq = None
                    self.summary = str(err)

                    if operation:
                        operation.summary = str(err)
                        operation.percentage = 100.0

                if self.seq is not None:
                    self.status = self.SAVED
                    return True
Example #50
0
    def start(self):
        if self.internal or self.receiving:
            log.debug("Pool already started")
            return

        self.receiving = True
        self.internal = True

        self.pool.start()
Example #51
0
    def start(self):
        if self.internal or self.receiving:
            log.debug("Pool already started")
            return

        self.receiving = True
        self.internal = True

        self.pool.start()
Example #52
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 #53
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 #54
0
    def remove_notify_for(self, packet, callback):
        if packet in self.notify:
            self.notify[packet].remove(callback)

            log.debug("Removing callback for %s" % packet)

            if not self.notify[packet]:
                del self.notify[packet]

                log.debug("No callbacks for %s" % packet)
Example #55
0
 def add_injector(self, level, type, injector):
     """
     Add a injector for the given level
     @param level the level where the injector works on
     @param type the type of injector
     @param injector a callable object
     """
     log.debug("Registering injector %s for level %s with type %s" % \
               (injector, level, type))
     self._injectors[level][type] = injector
Example #56
0
def get_iface_from_ip(metapacket):
    if metapacket.haslayer(IP):
        iff, a, gw = conf.route.route(metapacket.getlayer(IP).dst)
        log.debug("Using %s interface to send packet to %s" % \
                  (iff, metapacket.root.dst))
    else:
        iff = conf.iface
        log.debug("Using default %s interface" % iff)

    return iff
Example #57
0
 def add_decoder(self, level, type, decoder):
     """
     Add a decoder for the given level
     @param level the level where the decoder works on
     @param type the type of decoder
     @param decoder a callable object
     """
     log.debug("Registering dissector %s for level %s with type %s" % \
               (decoder, level, type))
     self._decoders[level][type] = (decoder, [], [])