Beispiel #1
0
 def parse(self, data):
     self.next_hop = dnet.ip_ntoa(data[:4])
     (self.delay, self.bandwidth, mtu_and_hop, self.reliability, self.load,
      self.prefix) = struct.unpack("!IIIBBxxB", data[4:21])
     self.mtu = mtu_and_hop >> 8
     self.hop_count = mtu_and_hop & 0x000000ff
     self.dest = dnet.ip_ntoa(data[21:] + '\0' * (25 - len(data)))
Beispiel #2
0
    def start_pcap(self):
        (self.dpktfh, self.dpktfile) = tempfile.mkstemp()
        if self.debug:
            print "Starting pcap capture, saving in file", self.dpktfile
        self.pid_pcap = os.fork()
        if self.pid_pcap == 0:
            # Child, reads pcap, outputs to a file in dpkt format
            pc = 0
            try:
                pc = pcap.pcap(self.interface)
            except:
                print >> sys.stderr, "Cannot run packet filter, aborting"
                sys.exit(1)

            # filter on our dedciated subnets
            pc.setfilter('net 192.18.0.0/15 and net 192.0.2.0/24')
            for ts, pkt in pc:
                lp = dpkt.loopback.Loopback(pkt)
                ip = dpkt.ip.IP(str(lp.data))
                os.write(self.dpktfh, "SRC=" + dnet.ip_ntoa(ip.src) + "\n")
                os.write(self.dpktfh, "DST=" + dnet.ip_ntoa(ip.dst) + "\n")
                os.write(self.dpktfh, "ID=%d\n" % ip.id)
                os.write(self.dpktfh, "TTL=%d\n" % ip.ttl)
                os.write(self.dpktfh, "DATA=" + ` ip.data ` + "\n")
                os.write(self.dpktfh, "\n")
            exit
            # Parent returns
        return 0
Beispiel #3
0
 def input_udp(self, eth, ip, udp, timestamp):
     if ip.dst == dnet.ip_aton(RIP_MULTICAST_ADDRESS) and ip.src != self.ip:
         if ip.src not in self.hosts:
             src = dnet.ip_ntoa(ip.src)
             iter = self.host_treestore.append(None, [src])
             self.log("RIP: Got new host %s" % (src))
             self.hosts[ip.src] = (iter, src)
             msg = rip_message()
             msg.parse(udp.data)
             for i in msg.entries:
                 nh = dnet.ip_ntoa(i.nh)
                 if nh == "0.0.0.0":
                     nh = src
                 self.host_treestore.append(iter, ["%s/%s via %s metric %d" % (dnet.ip_ntoa(i.addr), dnet.ip_ntoa(i.mask), nh, i.metric)])
         else:
             (iter, src) = self.hosts[ip.src]
             msg = rip_message(None, [])
             msg.parse(udp.data)
             path = self.host_treestore.get_path(iter)
             expanded = self.host_treeview.row_expanded(path)
             child = self.host_treestore.iter_children(iter)
             while child:
               self.host_treestore.remove(child)
               child = self.host_treestore.iter_children(iter)
             for i in msg.entries:
                 nh = dnet.ip_ntoa(i.nh)
                 if nh == "0.0.0.0":
                     nh = src
                 self.host_treestore.append(iter, ["%s/%s via %s metric %d" % (dnet.ip_ntoa(i.addr), dnet.ip_ntoa(i.mask), nh, i.metric)])
             if expanded:
                 self.host_treeview.expand_row(path, False)
Beispiel #4
0
 def input_udp(self, eth, ip, udp, timestamp):
     if ip.src != self.ip:
         if ip.src not in self.peers:
             pkg = hsrp_packet()
             auth = None
             data = pkg.parse(str(udp.data))
             if len(data) >= 30:
                 auth = hsrp_auth_tlv()
                 auth.parse(data)
             src = dnet.ip_ntoa(ip.src)
             if not auth is None:
                 auth_str = "MD5: %s key#%d" % (auth.csum.encode("hex"), auth.keyid)
             else:
                 auth_str = pkg.auth_data
             if self.ui == 'gtk':
                 iter = self.liststore.append([src, dnet.ip_ntoa(pkg.ip), pkg.prio, "Seen", auth_str])
             elif self.ui == 'urw':
                 label = "%s - %s PRIO(%d) AUTH(%s)" % (src, dnet.ip_ntoa(pkg.ip), pkg.prio, auth_str)
                 self.hostlist.append(self.parent.menu_button(label + " - Seen", self.urw_hostlist_activated, (ip.src, label)))
                 iter = None
             self.peers[ip.src] = {
                 "iter"  :   iter,
                 "pkg"   :   pkg,
                 "auth"  :   auth,
                 "state" :   False,
                 "arp"   :   False
                 }
             self.log("HSRP: Got new peer %s" % (src))
Beispiel #5
0
    def input_tcp(self, eth, ip, tcp, timestamp):
        if not eth.src == self.mac:
            header = tacacs_plus_header()
            data = header.parse(str(tcp.data))
            server = tcp.sport == TACACS_PLUS_PORT
            if server:
                ident = "%s -> %s" % (dnet.ip_ntoa(ip.dst), dnet.ip_ntoa(
                    ip.src))
            else:
                ident = "%s -> %s" % (dnet.ip_ntoa(ip.src), dnet.ip_ntoa(
                    ip.dst))

            if not ident in self.peers:
                encrypt = not (header.flags
                               & tacacs_plus_header.FLAGS_UNENCRYPTED)
                #add to gui
                if self.ui == "gtk":
                    row_iter = self.treestore.append(
                        None, [ident, encrypt, False, ""])
                elif self.ui == "urw":
                    column = [
                        ('weight', 3,
                         self.PopUpButton(
                             "%s - ENCRYPTED(%s)" % (ident, str(encrypt)),
                             self, ident))
                    ]
                    if not header.flags & tacacs_plus_header.FLAGS_UNENCRYPTED:
                        column.append(
                            self.parent.menu_button("Crack",
                                                    self.crack_activated,
                                                    ident))
                        column.append(self.PwPopUpButton(self, ident))
                    column = urwid.Columns(column)
                    self.peerlist.append(column)
                    row_iter = self.peerlist.index(column)

                self.peers[ident] = {
                    'encrypt': encrypt,
                    'secret': None,
                    'iter': row_iter,
                    'packets': [],
                    'log': [],
                    'crack': False,
                    'crack_pkg': None,
                }
                self.log("TACACS+: Got connection %s" % ident)
            if header.flags & tacacs_plus_header.FLAGS_UNENCRYPTED:
                #cleartext
                self.peers[ident]['log'].append(self.body_to_str(header, data))
            else:
                #crypted
                if not self.peers[ident]['secret'] is None:
                    self.peers[ident]['log'].append(
                        self.body_to_str(
                            header,
                            self.decrypt(header, data,
                                         self.peers[peer]['secret']), server))
                self.peers[ident]['packets'].append((header, data, server))
                if server and header._type == tacacs_plus_header.TYPE_AUTHEN:
                    self.peers[ident]['crack_pkg'] = (header, data)
Beispiel #6
0
    def start_pcap(self):
        (self.dpktfh, self.dpktfile) = tempfile.mkstemp()
        if self.debug:
            print "Starting pcap capture, saving in file", self.dpktfile
        self.pid_pcap = os.fork()
        if self.pid_pcap == 0:
            # Child, reads pcap, outputs to a file in dpkt format
            pc = 0
            try:
                pc = pcap.pcap(self.interface)
            except:
                print >> sys.stderr, "Cannot run packet filter, aborting"
                sys.exit(1)

            # filter on our dedciated subnets
            pc.setfilter("net 192.18.0.0/15 and net 192.0.2.0/24")
            for ts, pkt in pc:
                eth = dpkt.ethernet.Ethernet(pkt)
                ip = eth.data

                os.write(self.dpktfh, "SRC=" + dnet.ip_ntoa(ip.src) + "\n")
                os.write(self.dpktfh, "DST=" + dnet.ip_ntoa(ip.dst) + "\n")
                os.write(self.dpktfh, "ID=%d\n" % ip.id)
                os.write(self.dpktfh, "TTL=%d\n" % ip.ttl)
                os.write(self.dpktfh, "DATA=" + ` ip.data ` + "\n")
                os.write(self.dpktfh, "\n")
            exit
            # Parent returns
        return 0
Beispiel #7
0
 def parse(self, data):
     self.next_hop = dnet.ip_ntoa(data[:4])
     (self.delay, self.bandwidth, mtu_and_hop, self.reliability, self.load, self.prefix) = struct.unpack(
         "!IIIBBxxB", data[4:21]
     )
     self.mtu = mtu_and_hop >> 8
     self.hop_count = mtu_and_hop & 0x000000FF
     self.dest = dnet.ip_ntoa(data[21:] + "\0" * (25 - len(data)))
Beispiel #8
0
 def parse(self, data):
     self.next_hop = dnet.ip_ntoa(data[:4])
     self.originating_router = dnet.ip_ntoa(data[4:8])
     (self.originating_as, self.arbitrary_tag, self.external_metric,
      self.external_proto, self.flags, self.delay, self.bandwidth,
      mtu_and_hop, self.reliability, self.load,
      self.prefix) = struct.unpack("!IIIxxBBIIIBBxxB", data[8:41])
     self.mtu = mtu_and_hop >> 8
     self.hop_count = mtu_and_hop & 0x000000ff
     self.dest = dnet.ip_ntoa(data[41:] + '\0' * (45 - len(data)))
Beispiel #9
0
 def input_eth(self, eth, timestamp):
     arp = dpkt.arp.ARP(str(eth.data))
     mac = dnet.eth_ntoa(str(eth.src))
     if self.flood_thread and self.flood_thread.is_alive():
         return
     if self.mac:
         if not eth.src == self.mac:
             if arp.op == dpkt.arp.ARP_OP_REQUEST and arp.spa != arp.tpa:
                 ip_dst = dnet.ip_ntoa(str(arp.tpa))
                 for h in self.hosts:
                     if mac == h:
                         (ip_src, rand_mac_src, iter_src, reply_src) = self.hosts[mac]
                         for i in self.hosts:
                             (ip, rand_mac_dst, iter_dst, reply_dst) = self.hosts[i]
                             if ip_dst == ip:
                                 break
                             else:
                                 reply_dst = None
                         if reply_src and reply_dst:
                             _arp = dpkt.arp.ARP(    hrd=dpkt.arp.ARP_HRD_ETH,
                                                     pro=dpkt.arp.ARP_PRO_IP,
                                                     op=dpkt.arp.ARP_OP_REPLY,
                                                     sha=dnet.eth_aton(rand_mac_dst),
                                                     spa=arp.tpa,
                                                     tha=arp.sha,
                                                     tpa=arp.spa
                                                     )
                             _eth = dpkt.ethernet.Ethernet(  dst=arp.sha,
                                                             src=dnet.eth_aton(rand_mac_dst),
                                                             type=dpkt.ethernet.ETH_TYPE_ARP,
                                                             data=str(_arp)
                                                             )
                             self.dnet.send(str(_eth))
                             break
             #return #???
     for h in self.hosts:
         if mac == h:
             return
         (ip, random_mac, iter, reply) = self.hosts[h]
         if mac == random_mac:
             return
     ip = dnet.ip_ntoa(str(arp.spa))
     if ip == "0.0.0.0":
         return
     rand_mac = [ 0x00, random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff) ]
     rand_mac = ':'.join(map(lambda x: "%02x" % x, rand_mac))
     if self.ui == 'gtk':
         iter = self.hosts_liststore.append([mac, ip, self.mac_to_vendor(mac)])
     elif self.ui == 'urw':
         self.hostlist.append(self.parent.menu_button("%s(%s) - %s" % (mac, self.mac_to_vendor(mac), ip), self.urw_hostlist_activated, mac))
         iter = None
     self.hosts[mac] = (ip, rand_mac, iter, False)
     if self.ui == 'gtk':
         self.mappings_liststore.append([mac, rand_mac])
Beispiel #10
0
 def input_tcp(self, eth, ip, tcp, timestamp):
     opts = dpkt.tcp.parse_opts(tcp.opts)
     for (opt, data) in opts:
         if opt == dpkt.tcp.TCP_OPT_MD5:
             src = dnet.ip_ntoa(ip.src)
             dst = dnet.ip_ntoa(ip.dst)
             ident = "%s:%i->%s:%i" % (src, tcp.sport, dst, tcp.dport)
             if ident not in self.opts:
                 if self.ui == 'gtk':
                     iter = self.liststore.append(["%s:%i" % (src, tcp.sport), "%s:%i" % (dst, tcp.dport), "CAPTURED"])
                 self.opts[ident] = (iter, str(eth.data), data, None)
                 self.log("TCP-MD5: Got MD5 data for connection %s" % (ident))
Beispiel #11
0
 def input_ip(self, eth, ip, timestamp):
     if ip.src != self.ip:
         if ip.src not in self.peers:
             pkg = vrrp_packet()
             pkg.parse(str(ip.data))
             src = dnet.ip_ntoa(ip.src)
             ips = []
             for i in pkg.ips:
                 ips.append(dnet.ip_ntoa(i))
             iter = self.liststore.append([src, " ".join(ips), pkg.id, pkg.prio, "Seen"])
             self.peers[ip.src] = (iter, pkg, False, False)
             self.log("VRRP: Got new peer %s" % (src))
Beispiel #12
0
 def input_ip(self, eth, ip, timestamo):
     if ip.src != self.ip:
         if ip.src not in self.peers:
             pkg = vrrp_packet()
             pkg.parse(str(ip.data))
             src = dnet.ip_ntoa(ip.src)
             ips = []
             for i in pkg.ips:
                 ips.append(dnet.ip_ntoa(i))
             iter = self.liststore.append([src, " ".join(ips), pkg.id, pkg.prio, "Seen"])
             self.peers[ip.src] = (iter, pkg, False, False)
             self.log("VRRP-3: Got new peer %s" % (src))
Beispiel #13
0
 def input(self, data):
     packet = eigrp_packet()
     payload = packet.parse(data)
     if not packet.optcode == eigrp_packet.EIGRP_OPTCODE_HELLO:
         reply = eigrp_packet(eigrp_packet.EIGRP_OPTCODE_HELLO, 0, 0,
                              packet.seq_num, self.as_num)
         self.seq_num = packet.seq_num + 1
         self.sem.acquire()
         self.msg = reply
         self.sem.release()
         if packet.optcode == eigrp_packet.EIGRP_OPTCODE_UPDATE and len(
                 payload) > 4:
             tlv = eigrp_tlv()
             while payload:
                 payload = tlv.parse(payload)
                 if tlv.type == eigrp_tlv.EIGRP_TYPE_INTERNAL_ROUTE:
                     route = eigrp_internal_route()
                     route.parse(tlv.data)
                     if route.next_hop == "0.0.0.0":
                         route.next_hop = dnet.ip_ntoa(self.peer)
                     route_str = route.dest + "/" + str(
                         route.prefix) + " via " + route.next_hop
                     for i in xrange(
                             self.parent.treestore.iter_n_children(
                                 self.iter)):
                         (test_str, ) = self.parent.treestore.get(
                             self.parent.treestore.iter_nth_child(
                                 self.iter, i), self.parent.TREE_AS_ROW)
                         if test_str == route_str:
                             return
                     self.parent.treestore.append(
                         self.iter, ["INTERNAL_ROUTE", route_str])
                 if tlv.type == eigrp_tlv.EIGRP_TYPE_EXTERNAL_ROUTE:
                     route = eigrp_external_route()
                     route.parse(tlv.data)
                     if route.next_hop == "0.0.0.0":
                         route.next_hop = dnet.ip_ntoa(self.peer)
                     route_str = route.dest + "/" + str(
                         route.prefix
                     ) + " via " + route.next_hop + " on AS# " + str(
                         route.originating_as) + ", type " + str(
                             route.external_proto)
                     for i in xrange(
                             self.parent.treestore.iter_n_children(
                                 self.iter)):
                         (test_str, ) = self.parent.treestore.get(
                             self.parent.treestore.iter_nth_child(
                                 self.iter, i), self.parent.TREE_AS_ROW)
                         if test_str == route_str:
                             return
                     self.parent.treestore.append(
                         self.iter, ["EXTERNAL_ROUTE", route_str])
Beispiel #14
0
 def recv_pkt(self, pc, pkt):
     arp = dpkt.ethernet.Ethernet(pkt).arp
     try:
         old = self.cache[arp.spa]
         if old != arp.sha:
             self.cache[arp.spa] = arp.sha
             print 'CHANGE: %s is-at %s (was-at %s)' % \
                   (dnet.ip_ntoa(arp.spa), dnet.eth_ntoa(arp.sha),
                    dnet.eth_ntoa(old))
     except KeyError:
         self.cache[arp.spa] = arp.sha
         print 'NEW: %s is-at %s' % (dnet.ip_ntoa(arp.spa),
                               dnet.eth_ntoa(arp.sha))
Beispiel #15
0
 def recv_pkt(self, pc, pkt):
     arp = dpkt.ethernet.Ethernet(pkt).arp
     try:
         old = self.cache[arp.spa]
         if old != arp.sha:
             self.cache[arp.spa] = arp.sha
             print 'CHANGE: %s is-at %s (was-at %s)' % \
                   (dnet.ip_ntoa(arp.spa), dnet.eth_ntoa(arp.sha),
                    dnet.eth_ntoa(old))
     except KeyError:
         self.cache[arp.spa] = arp.sha
         print 'NEW: %s is-at %s' % (dnet.ip_ntoa(
             arp.spa), dnet.eth_ntoa(arp.sha))
Beispiel #16
0
 def input_udp(self, eth, ip, udp, timestamp):
     if ip.src != self.ip:
         pkg = glbp_packet()
         data = pkg.parse(str(udp.data))
         req_resp = []
         auth = None
         nonce = None
         auth_str = "Unauthenticated"
         while len(data) > 0:
             #~ print "len: %d data: %s" % (len(data), data.encode("hex"))
             tlv = glbp_tlv()
             tlv.parse(data)
             if tlv.tlv_type == glbp_tlv.TYPE_HELLO:                    
                 hello = glbp_tlv_hello()
                 data = hello.parse(data)
             elif tlv.tlv_type == glbp_tlv.TYPE_REQ_RESP:
                 tmp = glbp_tlv_req_resp()
                 data = tmp.parse(data)
                 if not tmp.vmac == "\x00\x00\x00\x00\x00\x00":
                     req_resp.append(tmp)
             elif tlv.tlv_type == glbp_tlv.TYPE_AUTH:
                 auth = glbp_tlv_auth()
                 data = auth.parse(data)
                 if auth.auth_type == glbp_tlv_auth.TYPE_PLAIN:
                     auth_str = "Plaintext: '%s'" % auth.secret[:-1]
                 elif auth.auth_type == glbp_tlv_auth.TYPE_MD5_STRING:
                     auth_str = "MD5 String: '%s'" % auth.secret.encode("hex")
                 elif auth.auth_type == glbp_tlv_auth.TYPE_MD5_CHAIN:
                     auth_str = "MD5 Chain: '%s'" % auth.secret.encode("hex")
                 else:
                     auth_str = "Unknown"
             else:
                 #~ print "type: %d len: %d" % (tlv.tlv_type, tlv.tlv_length)
                 data = data[tlv.tlv_length:]
         try:
             src = dnet.ip_ntoa(ip.src)
         except:
             pass
         
         if ip.src in self.peers:
             (iter, _, _, req_resp_old, _, _, _) = self.peers[ip.src]
             for i in req_resp:
                 if not i in req_resp_old:
                     req_resp_old.append(i)
                     self.treestore.append(iter, ["", "", i.weight, dnet.eth_ntoa(i.vmac), ""])
         else:
             iter = self.treestore.append(None, [src, dnet.ip_ntoa(hello.addr), hello.prio, "Seen", auth_str])
             for req in req_resp:
                 self.treestore.append(iter, ["", "", req.weight, dnet.eth_ntoa(req.vmac), ""])
             self.peers[ip.src] = (iter, pkg, hello, req_resp, auth, False, False)
             self.log("GLBP: Got new peer %s" % (src))
Beispiel #17
0
 def input(self, data):
     packet = eigrp_packet()
     payload = packet.parse(data)
     if not packet.optcode == eigrp_packet.EIGRP_OPTCODE_HELLO:
         reply = eigrp_packet(eigrp_packet.EIGRP_OPTCODE_HELLO, 0, 0, packet.seq_num, self.as_num)
         self.seq_num = packet.seq_num + 1
         self.sem.acquire()
         self.msg = reply
         self.sem.release()
         if packet.optcode == eigrp_packet.EIGRP_OPTCODE_UPDATE and len(payload) > 4:
             tlv = eigrp_tlv()
             while payload:
                 payload = tlv.parse(payload)
                 if tlv.type == eigrp_tlv.EIGRP_TYPE_INTERNAL_ROUTE:
                     route = eigrp_internal_route()
                     route.parse(tlv.data)
                     if route.next_hop == "0.0.0.0":
                         route.next_hop = dnet.ip_ntoa(self.peer)
                     route_str = route.dest + "/" + str(route.prefix) + " via " + route.next_hop
                     for i in xrange(self.parent.treestore.iter_n_children(self.iter)):
                         (test_str,) = self.parent.treestore.get(
                             self.parent.treestore.iter_nth_child(self.iter, i), self.parent.TREE_AS_ROW
                         )
                         if test_str == route_str:
                             return
                     self.parent.treestore.append(self.iter, ["INTERNAL_ROUTE", route_str])
                 if tlv.type == eigrp_tlv.EIGRP_TYPE_EXTERNAL_ROUTE:
                     route = eigrp_external_route()
                     route.parse(tlv.data)
                     if route.next_hop == "0.0.0.0":
                         route.next_hop = dnet.ip_ntoa(self.peer)
                     route_str = (
                         route.dest
                         + "/"
                         + str(route.prefix)
                         + " via "
                         + route.next_hop
                         + " on AS# "
                         + str(route.originating_as)
                         + ", type "
                         + str(route.external_proto)
                     )
                     for i in xrange(self.parent.treestore.iter_n_children(self.iter)):
                         (test_str,) = self.parent.treestore.get(
                             self.parent.treestore.iter_nth_child(self.iter, i), self.parent.TREE_AS_ROW
                         )
                         if test_str == route_str:
                             return
                     self.parent.treestore.append(self.iter, ["EXTERNAL_ROUTE", route_str])
Beispiel #18
0
 def input_udp(self, eth, ip, udp, timestamp):
     if ip.src != self.ip and ip.src != self.ip6_ll:
         if ip.src not in self.peers:
             pkg = {}
             ip_addr = ""
             prio = 0
             auth = ""
             tlv = hsrp2_tlv()
             left = str(udp.data)
             while len(left) > 0:
                 left = tlv.parse(left)
                 if tlv.type == hsrp2_tlv.TYPE_GROUP_STATE:
                     hsrp2_group_state = hsrp2_group_state_tlv()
                     left = hsrp2_group_state.parse(left)
                     pkg["hsrp2_group_state_tlv"] = hsrp2_group_state
                     ip_addr = hsrp2_group_state.ip
                     prio = hsrp2_group_state.prio
                 elif tlv.type == hsrp2_tlv.TYPE_TEXT_AUTH:
                     hsrp2_text_auth = hsrp2_text_auth_tlv()
                     left = hsrp2_text_auth.parse(left)
                     pkg["hsrp2_text_auth_tlv"] = hsrp2_text_auth
                     auth = hsrp2_text_auth.auth_data
                 elif tlv.type == hsrp2_tlv.TYPE_MD5_AUTH:
                     hsrp2_md5_auth = hsrp2_md5_auth_tlv()
                     left = hsrp2_md5_auth.parse(left)
                     pkg["hsrp2_md5_auth_tlv"] = hsrp2_md5_auth
                     auth = "MD5: %s key#%d" % (hsrp2_md5_auth.csum.encode(
                         "hex"), hsrp2_md5_auth.keyid)
                 else:
                     return
             if type(ip) == dpkt.ip6.IP6:
                 src = dnet.ip6_ntoa(ip.src)
                 ip_addr = dnet.ip6_ntoa(ip_addr)
             else:
                 src = dnet.ip_ntoa(ip.src)
                 ip_addr = dnet.ip_ntoa(ip_addr)
             if self.ui == 'gtk':
                 iter = self.liststore.append(
                     [src, ip_addr, prio, "Seen", auth])
             elif self.ui == 'urw':
                 label = "%s - %s PRIO(%d) AUTH(%s)" % (src, ip_addr, prio,
                                                        auth)
                 self.hostlist.append(
                     self.parent.menu_button(label + " - Seen",
                                             self.urw_hostlist_activated,
                                             (ip.src, label)))
                 iter = None
             self.peers[ip.src] = (iter, pkg, False, False)
             self.log("HSRP2: Got new peer %s" % (src))
Beispiel #19
0
 def input_tcp(self, eth, ip, tcp, timestamp):
     opts = dpkt.tcp.parse_opts(tcp.opts)
     for (opt, data) in opts:
         if opt == dpkt.tcp.TCP_OPT_MD5:
             src = dnet.ip_ntoa(ip.src)
             dst = dnet.ip_ntoa(ip.dst)
             ident = "%s:%i->%s:%i" % (src, tcp.sport, dst, tcp.dport)
             if ident not in self.opts:
                 if self.ui == 'gtk':
                     iter = self.liststore.append([
                         "%s:%i" % (src, tcp.sport),
                         "%s:%i" % (dst, tcp.dport), "CAPTURED"
                     ])
                 self.opts[ident] = (iter, str(eth.data), data, None)
                 self.log("TCP-MD5: Got MD5 data for connection %s" %
                          (ident))
  def build(self, bgpdump):
    '''
    Given a BGPdump, constructs a stable set from the bgpdump.

    This function also returns a parsed form of the bgpdump that contains only
    prefix and time related data which is relevant for concurrent-hijack algorithm
    '''
    ORIG_AS = None

    as_set = defaultdict(dict)
    for mrt_h, bgp_h, bgp_m in bgpdump:

      ####Parse time at which announcements were made
      TIMEstr = time.strftime('%D %T', time.localtime())
      TIME = mrt_h.ts

      #######Print the origin from the AS Path attribute

      #print ("Attributes: %s" % bgp_m.update.attributes)
      for attr in bgp_m.update.attributes:
        if attr.type == bgp.AS_PATH:
          ORIG_AS = self.path_to_str(attr.as_path)
          #print ("ORIGIN AS: %s" % type(ORIG_AS))
          break

      #### If Bgp Update has no AS_PATH attribute, skip parsing this update
      if(ORIG_AS == None):
        print ("None AS")
        continue

      #### Initialize prefixes data
      if(hasattr(as_set, ORIG_AS)):
        prefixes_data = as_set[ORIG_AS]
      else:
        prefixes_data = dict()
        as_set[ORIG_AS] = prefixes_data


      ####Parse prefixes data
      for route in bgp_m.update.announced:
        #out('Announcement %d : %s/%d\n' % (i,dnet.ip_ntoa(route.prefix), route.len))
        PREFIX = dnet.ip_ntoa(route.prefix)

        #### Initialize prefix data
        if(hasattr(prefixes_data, PREFIX)):
          prefix_data = prefixes_data[PREFIX]
        else:
          prefix_data = dict()
          prefixes_data[PREFIX] = prefix_data

        #### If already in stable set skip parsing this prefix
        if(hasattr(prefix_data, "marked") and prefix_data.marked == True):
          continue

        self.test_for_stable_set(prefix_data, ORIG_AS, PREFIX, TIME)

      #parsed_list.append(as_set)

    return as_set
Beispiel #21
0
    def build(self, bgpdump):
        '''
    Given a BGPdump, constructs a stable set from the bgpdump.

    This function also returns a parsed form of the bgpdump that contains only
    prefix and time related data which is relevant for concurrent-hijack algorithm
    '''
        ORIG_AS = None

        as_set = defaultdict(dict)
        for mrt_h, bgp_h, bgp_m in bgpdump:

            ####Parse time at which announcements were made
            TIMEstr = time.strftime('%D %T', time.localtime())
            TIME = mrt_h.ts

            #######Print the origin from the AS Path attribute

            #print ("Attributes: %s" % bgp_m.update.attributes)
            for attr in bgp_m.update.attributes:
                if attr.type == bgp.AS_PATH:
                    ORIG_AS = self.path_to_str(attr.as_path)
                    #print ("ORIGIN AS: %s" % type(ORIG_AS))
                    break

            #### If Bgp Update has no AS_PATH attribute, skip parsing this update
            if (ORIG_AS == None):
                print("None AS")
                continue

            #### Initialize prefixes data
            if (hasattr(as_set, ORIG_AS)):
                prefixes_data = as_set[ORIG_AS]
            else:
                prefixes_data = dict()
                as_set[ORIG_AS] = prefixes_data

            ####Parse prefixes data
            for route in bgp_m.update.announced:
                #out('Announcement %d : %s/%d\n' % (i,dnet.ip_ntoa(route.prefix), route.len))
                PREFIX = dnet.ip_ntoa(route.prefix)

                #### Initialize prefix data
                if (hasattr(prefixes_data, PREFIX)):
                    prefix_data = prefixes_data[PREFIX]
                else:
                    prefix_data = dict()
                    prefixes_data[PREFIX] = prefix_data

                #### If already in stable set skip parsing this prefix
                if (hasattr(prefix_data, "marked")
                        and prefix_data.marked == True):
                    continue

                self.test_for_stable_set(prefix_data, ORIG_AS, PREFIX, TIME)

            #parsed_list.append(as_set)

        return as_set
Beispiel #22
0
 def recv_pkt(self, pc, pkt):
     eth = dpkt.ethernet.Ethernet(pkt)
     if eth.src not in self.cache and eth.type == dpkt.ethernet.ETH_TYPE_CDP:
         d = dict([ (tlv.type, tlv.data) for tlv in eth.cdp.data ])
         self.cache[eth.src] = d
         print "%s [%s] - %s [%s]" % (d[1], dnet.eth_ntoa(eth.src), dnet.ip_ntoa(d[2][0].data), d[3])
         pprint.pprint(d)
         print
Beispiel #23
0
 def run(self):
     self.iter = self.parent.treestore.append(None, [dnet.ip_ntoa(self.peer), str(self.as_num)])
     self.send()
     self.parent.log("EIGRP: Peer " + socket.inet_ntoa(self.peer) + " terminated")
     if self.parent.treestore:
         if self.parent.treestore.iter_is_valid(self.iter):
             self.parent.treestore.remove(self.iter)
     del self.parent.peers[self.peer]
Beispiel #24
0
 def recv_pkt(self, pc, pkt):
     eth = dpkt.ethernet.Ethernet(pkt)
     if eth.src not in self.cache and eth.type == dpkt.ethernet.ETH_TYPE_CDP:
         d = dict([(tlv.type, tlv.data) for tlv in eth.cdp.data])
         self.cache[eth.src] = d
         print "%s [%s] - %s [%s]" % (d[1], dnet.eth_ntoa(
             eth.src), dnet.ip_ntoa(d[2][0].data), d[3])
         pprint.pprint(d)
         print
Beispiel #25
0
 def parse(self, data):
     self.next_hop = dnet.ip_ntoa(data[:4])
     self.originating_router = dnet.ip_ntoa(data[4:8])
     (
         self.originating_as,
         self.arbitrary_tag,
         self.external_metric,
         self.external_proto,
         self.flags,
         self.delay,
         self.bandwidth,
         mtu_and_hop,
         self.reliability,
         self.load,
         self.prefix,
     ) = struct.unpack("!IIIxxBBIIIBBxxB", data[8:41])
     self.mtu = mtu_and_hop >> 8
     self.hop_count = mtu_and_hop & 0x000000FF
     self.dest = dnet.ip_ntoa(data[41:] + "\0" * (45 - len(data)))
Beispiel #26
0
 def input_udp(self, eth, ip, udp, timestamp):
     if ip.src != self.ip and ip.src != self.ip6_ll:
         if ip.src not in self.peers:
             pkg = {}
             ip_addr = ""
             prio = 0
             auth = ""
             tlv = hsrp2_tlv()
             left = str(udp.data)
             while len(left) > 0:
                 left = tlv.parse(left)
                 if tlv.type == hsrp2_tlv.TYPE_GROUP_STATE:
                     hsrp2_group_state = hsrp2_group_state_tlv()
                     left = hsrp2_group_state.parse(left)
                     pkg["hsrp2_group_state_tlv"] = hsrp2_group_state
                     ip_addr = hsrp2_group_state.ip
                     prio = hsrp2_group_state.prio
                 elif tlv.type == hsrp2_tlv.TYPE_TEXT_AUTH:
                     hsrp2_text_auth = hsrp2_text_auth_tlv()
                     left = hsrp2_text_auth.parse(left)
                     pkg["hsrp2_text_auth_tlv"] = hsrp2_text_auth
                     auth = hsrp2_text_auth.auth_data
                 elif tlv.type == hsrp2_tlv.TYPE_MD5_AUTH:
                     hsrp2_md5_auth = hsrp2_md5_auth_tlv()
                     left = hsrp2_md5_auth.parse(left)
                     pkg["hsrp2_md5_auth_tlv"] = hsrp2_md5_auth
                     auth = "MD5: %s key#%d" % (hsrp2_md5_auth.csum.encode("hex"), hsrp2_md5_auth.keyid)
                 else:
                     return
             if type(ip) == dpkt.ip6.IP6:
                 src = dnet.ip6_ntoa(ip.src)
                 ip_addr = dnet.ip6_ntoa(ip_addr)
             else:
                 src = dnet.ip_ntoa(ip.src)
                 ip_addr = dnet.ip_ntoa(ip_addr)
             if self.ui == 'gtk':
                 iter = self.liststore.append([src, ip_addr, prio, "Seen", auth])
             elif self.ui == 'urw':
                 label = "%s - %s PRIO(%d) AUTH(%s)" % (src, ip_addr, prio, auth)
                 self.hostlist.append(self.parent.menu_button(label + " - Seen", self.urw_hostlist_activated, (ip.src, label)))
                 iter = None
             self.peers[ip.src] = (iter, pkg, False, False)
             self.log("HSRP2: Got new peer %s" % (src))
Beispiel #27
0
 def input_tcp(self, eth, ip, tcp, timestamp):
     if not eth.src == self.mac:
         header = tacacs_plus_header()
         data = header.parse(str(tcp.data))
         server = tcp.sport == TACACS_PLUS_PORT
         if server:
             ident = "%s -> %s" % (dnet.ip_ntoa(ip.dst), dnet.ip_ntoa(ip.src))
         else:
             ident = "%s -> %s" % (dnet.ip_ntoa(ip.src), dnet.ip_ntoa(ip.dst))
             
         if not ident in self.peers:
             encrypt = not (header.flags & tacacs_plus_header.FLAGS_UNENCRYPTED)
             #add to gui
             if self.ui == "gtk":
                 row_iter = self.treestore.append( None, [ ident, encrypt, False, "" ] )
             elif self.ui == "urw":
                 column = [ ('weight', 3, self.PopUpButton("%s - ENCRYPTED(%s)" % (ident, str(encrypt)), self, ident)) ]
                 if not header.flags & tacacs_plus_header.FLAGS_UNENCRYPTED:
                     column.append( self.parent.menu_button("Crack", self.crack_activated, ident) )
                     column.append( self.PwPopUpButton(self, ident) )
                 column = urwid.Columns(column)
                 self.peerlist.append(column)
                 row_iter = self.peerlist.index(column)
             
             self.peers[ident] = { 'encrypt' : encrypt,
                                   'secret'  : None,
                                   'iter'    : row_iter,
                                   'packets' : [],
                                   'log'     : [],
                                   'crack'   : False,
                                   'crack_pkg' : None,
                                   }
             self.log("TACACS+: Got connection %s" % ident)
         if header.flags & tacacs_plus_header.FLAGS_UNENCRYPTED:
             #cleartext
             self.peers[ident]['log'].append(self.body_to_str(header, data))
         else:
             #crypted
             if not self.peers[ident]['secret'] is None:
                 self.peers[ident]['log'].append(self.body_to_str(header, self.decrypt(header, data, self.peers[peer]['secret']), server))
             self.peers[ident]['packets'].append((header, data, server))
             if server and header._type == tacacs_plus_header.TYPE_AUTHEN:
                 self.peers[ident]['crack_pkg'] = (header, data)
Beispiel #28
0
 def test_ip_misc(self):
     n = '\x01\x02\x03\x04'
     a = '1.2.3.4'
     self.failUnless(dnet.ip_ntoa(n) == a)
     self.failUnless(dnet.ip_aton(a) == n)
     dst = '\x05\x06\x07\x08'
     hdr = dnet.ip_pack_hdr(0, dnet.IP_HDR_LEN, 666, 0, 255,
                            dnet.IP_PROTO_UDP, n, dst)
     assert hdr == 'E\x00\x00\x14\x02\x9a\x00\x00\xff\x11\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08'
     hdr = dnet.ip_checksum(hdr)
     assert hdr == 'E\x00\x00\x14\x02\x9a\x00\x00\xff\x11\xa9+\x01\x02\x03\x04\x05\x06\x07\x08'
Beispiel #29
0
 def run(self):
     self.iter = self.parent.treestore.append(
         None, [dnet.ip_ntoa(self.peer),
                str(self.as_num)])
     self.send()
     self.parent.log("EIGRP: Peer " + socket.inet_ntoa(self.peer) +
                     " terminated")
     if self.parent.treestore:
         if self.parent.treestore.iter_is_valid(self.iter):
             self.parent.treestore.remove(self.iter)
     del self.parent.peers[self.peer]
Beispiel #30
0
 def test_ip_misc(self):
     n = '\x01\x02\x03\x04'
     a = '1.2.3.4'
     self.failUnless(dnet.ip_ntoa(n) == a)
     self.failUnless(dnet.ip_aton(a) == n)
     dst = '\x05\x06\x07\x08'
     hdr = dnet.ip_pack_hdr(0, dnet.IP_HDR_LEN, 666, 0, 255,
                            dnet.IP_PROTO_UDP, n, dst)
     assert hdr == 'E\x00\x00\x14\x02\x9a\x00\x00\xff\x11\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08'
     hdr = dnet.ip_checksum(hdr)
     assert hdr == 'E\x00\x00\x14\x02\x9a\x00\x00\xff\x11\xa9+\x01\x02\x03\x04\x05\x06\x07\x08'
Beispiel #31
0
 def recv_pkt(self, pc, pkt):
     ip = dpkt.ethernet.Ethernet(pkt).ip
     msg = dpkt.dhcp.DHCP(ip.udp.data)
     opts = dict(msg.opts)
     if dpkt.dhcp.DHCP_OPT_PARAM_REQ in opts:
         l = map(ord, opts[dpkt.dhcp.DHCP_OPT_PARAM_REQ])
         fp = ','.join(map(str, l))
         print fp
         print '%s: %s (%s [%s] - %s):\n%s\n' % (
             self.types[map(ord, opts[dpkt.dhcp.DHCP_OPT_MSGTYPE])[0] - 1],
             dnet.eth_ntoa(msg.chaddr), dnet.ip_ntoa(
                 ip.src), opts.get(dpkt.dhcp.DHCP_OPT_HOSTNAME, 'unknown'),
             opts.get(dpkt.dhcp.DHCP_OPT_VENDOR_ID,
                      'unknown'), self.fpos.get(fp, 'UNKNOWN: %s' % fp))
Beispiel #32
0
 def input_udp(self, eth, ip, udp, timestamp):
     if ip.src != self.ip:
         if ip.src not in self.peers:
             pkg = hsrp_packet()
             auth = None
             data = pkg.parse(str(udp.data))
             if len(data) >= 30:
                 auth = hsrp_auth_tlv()
                 auth.parse(data)
             src = dnet.ip_ntoa(ip.src)
             if not auth is None:
                 auth_str = "MD5: %s key#%d" % (auth.csum.encode("hex"),
                                                auth.keyid)
             else:
                 auth_str = pkg.auth_data
             if self.ui == 'gtk':
                 iter = self.liststore.append([
                     src,
                     dnet.ip_ntoa(pkg.ip), pkg.prio, "Seen", auth_str
                 ])
             elif self.ui == 'urw':
                 label = "%s - %s PRIO(%d) AUTH(%s)" % (
                     src, dnet.ip_ntoa(pkg.ip), pkg.prio, auth_str)
                 self.hostlist.append(
                     self.parent.menu_button(label + " - Seen",
                                             self.urw_hostlist_activated,
                                             (ip.src, label)))
                 iter = None
             self.peers[ip.src] = {
                 "iter": iter,
                 "pkg": pkg,
                 "auth": auth,
                 "state": False,
                 "arp": False
             }
             self.log("HSRP: Got new peer %s" % (src))
def table(ip, mac, dumpall):
	global theTable
	if (dumpall == 0):
		try:
			asd = theTable[0]
		except NameError:
			theTable={}
			theTable[0] = 0
			theTable[len(theTable) + 1] = {}
			theTable[len(theTable)]['ip'] = ip
			theTable[len(theTable)]['mac'] = mac
		except KeyError:
			print "not done yet"
		else:
			theTable[len(theTable) + 1] = {}
			theTable[len(theTable)]['ip'] = ip
			theTable[len(theTable)]['mac'] = mac
	else:
		print "-------------------------------"
		for key in range(1, len(theTable)):
			print "%s at %s" % (dnet.eth_ntoa(theTable[key+1]['mac']),dnet.ip_ntoa(theTable[key+1]['ip']))
Beispiel #34
0
 def recv_pkt(self, pc, pkt):
     ip = dpkt.ethernet.Ethernet(pkt).ip
     f = ip.tcp.flags & (dpkt.tcp.TH_SYN|dpkt.tcp.TH_RST)
     if ip.src not in self.ipcache[f]:
         self.ipcache[f][ip.src] = 1
         sig = self.p0f.match(ip)
         print '%s -' % dnet.ip_ntoa(ip.src),
         if sig:
             print '%s %s' % (sig['os'], sig['desc']),
         else:
             print 'UNKNOWN %s' % sig_to_string(parse_ip(ip)),
         l = []
         if 'uptime' in sig:
             l.append('up: %d hrs' % sig['uptime'])
         if 'distance' in sig:
             l.append('distance: %d' % sig['distance'])
         if 'link' in sig:
             l.append('link: %s' % sig['link'])
         if l:
             print '(%s)' % ', '.join(l)
         else:
             print
Beispiel #35
0
 def recv_pkt(self, pc, pkt):
     ip = dpkt.ethernet.Ethernet(pkt).ip
     f = ip.tcp.flags & (dpkt.tcp.TH_SYN | dpkt.tcp.TH_RST)
     if ip.src not in self.ipcache[f]:
         self.ipcache[f][ip.src] = 1
         sig = self.p0f.match(ip)
         print '%s -' % dnet.ip_ntoa(ip.src),
         if sig:
             print '%s %s' % (sig['os'], sig['desc']),
         else:
             print 'UNKNOWN %s' % sig_to_string(parse_ip(ip)),
         l = []
         if 'uptime' in sig:
             l.append('up: %d hrs' % sig['uptime'])
         if 'distance' in sig:
             l.append('distance: %d' % sig['distance'])
         if 'link' in sig:
             l.append('link: %s' % sig['link'])
         if l:
             print '(%s)' % ', '.join(l)
         else:
             print
Beispiel #36
0
def table(ip, mac, dumpall):
    global theTable
    if (dumpall == 0):
        try:
            asd = theTable[0]
        except NameError:
            theTable = {}
            theTable[0] = 0
            theTable[len(theTable) + 1] = {}
            theTable[len(theTable)]['ip'] = ip
            theTable[len(theTable)]['mac'] = mac
        except KeyError:
            print "not done yet"
        else:
            theTable[len(theTable) + 1] = {}
            theTable[len(theTable)]['ip'] = ip
            theTable[len(theTable)]['mac'] = mac
    else:
        print "-------------------------------"
        for key in range(1, len(theTable)):
            print "%s at %s" % (dnet.eth_ntoa(theTable[key + 1]['mac']),
                                dnet.ip_ntoa(theTable[key + 1]['ip']))
Beispiel #37
0
 def input_udp(self, eth, ip, udp, timestamp):
     if ip.dst == dnet.ip_aton(RIP_MULTICAST_ADDRESS) and ip.src != self.ip:
         if ip.src not in self.hosts:
             src = dnet.ip_ntoa(ip.src)
             iter = self.host_treestore.append(None, [src])
             self.log("RIP: Got new host %s" % (src))
             self.hosts[ip.src] = (iter, src)
             msg = rip_message()
             msg.parse(udp.data)
             for i in msg.entries:
                 nh = dnet.ip_ntoa(i.nh)
                 if nh == "0.0.0.0":
                     nh = src
                 self.host_treestore.append(iter, [
                     "%s/%s via %s metric %d" % (dnet.ip_ntoa(
                         i.addr), dnet.ip_ntoa(i.mask), nh, i.metric)
                 ])
         else:
             (iter, src) = self.hosts[ip.src]
             msg = rip_message(None, [])
             msg.parse(udp.data)
             path = self.host_treestore.get_path(iter)
             expanded = self.host_treeview.row_expanded(path)
             child = self.host_treestore.iter_children(iter)
             while child:
                 self.host_treestore.remove(child)
                 child = self.host_treestore.iter_children(iter)
             for i in msg.entries:
                 nh = dnet.ip_ntoa(i.nh)
                 if nh == "0.0.0.0":
                     nh = src
                 self.host_treestore.append(iter, [
                     "%s/%s via %s metric %d" % (dnet.ip_ntoa(
                         i.addr), dnet.ip_ntoa(i.mask), nh, i.metric)
                 ])
             if expanded:
                 self.host_treeview.expand_row(path, False)
Beispiel #38
0
def clusterlist_to_str(cluster_list):
    str = ''
    for cluster in cluster_list.list:
        str += '%s ' % dnet.ip_ntoa(cluster)
    str = str[:-1]
    return str
Beispiel #39
0
 def input_udp(self, eth, ip, udp, timestamp):
     packet = bfd_control_packet()
     packet.parse(udp.data)
     src = dnet.ip_ntoa(ip.src)
     dst = dnet.ip_ntoa(ip.dst)
     id = "%s:%s" % (src, dst)
     id_rev = "%s:%s" % (dst, src)
     auth = "None"
     if packet.flags & bfd_control_packet.FLAG_AUTH:
         auth = bfd_auth.type_to_str[packet.auth.type]
     password = ""
     if packet.flags & bfd_control_packet.FLAG_AUTH and packet.auth.type == bfd_auth.TYPE_SIMPLE:
         password = packet.auth.data
     if id not in self.neighbors and id_rev not in self.neighbors:
         self.activate_filter()
         if self.ui == 'gtk':
             self.filter_checkbutton.set_active(True)
         elif self.ui == 'urw':
             self.filter_checkbox.set_state(True)
         self.log("BFD: got new session: %s -> %s" % (src, dst))
         if self.ui == 'gtk':
             iter = self.neighbor_treestore.append(None, [src, dst, bfd_control_packet.state_to_str[packet.state], bfd_control_packet.diag_to_str[packet.diag], auth, self.auto_answer, False])
         elif self.ui == 'urw':
             label = "%s - %s %s %s AUTH(%s)" % (src, dst, bfd_control_packet.state_to_str[packet.state], bfd_control_packet.diag_to_str[packet.diag], auth)
             if password != "":
                 label += " PASS(%s)" % password
             answer_c = urwid.CheckBox("Answer", self.auto_answer, on_state_change=self.urw_answer_checkbox_changed, user_data=id)
             dos_c = urwid.CheckBox("DOS", False, on_state_change=self.urw_dos_checkbox_changed, user_data=id)
             if not auth == "None":
                 button = self.parent.menu_button(label, self.crack_activated, id)
             else:
                 button = self.parent.menu_button(label)
             self.hostlist.append(urwid.Columns([('weight', 4, button), answer_c, dos_c]))
             iter = (button, answer_c, dos_c)
         self.neighbors[id] = (iter, random.randint(0x1, 0x7fffffff), self.auto_answer, False, False, udp.data, password)
     if id in self.neighbors:
         (iter, discrim, answer, dos, crack, data, password) = self.neighbors[id]
         if self.ui == 'gtk':
             if self.neighbor_treestore.iter_is_valid(iter):
                 self.neighbor_treestore.set_value(iter, self.NEIGH_STATE_ROW, bfd_control_packet.state_to_str[packet.state])
                 self.neighbor_treestore.set_value(iter, self.NEIGH_DIAG_ROW, bfd_control_packet.diag_to_str[packet.diag])
         elif self.ui == 'urw':
             (button, answer_c, dos_c) = iter
             label = "%s - %s %s %s AUTH(%s)" % (src, dst, bfd_control_packet.state_to_str[packet.state], bfd_control_packet.diag_to_str[packet.diag], auth)
             if password != "":
                 label += " PASS(%s)" % password
             button.base_widget.set_label(label)
         if answer and packet.diag == bfd_control_packet.DIAG_NO:
             if packet.state == bfd_control_packet.STATE_DOWN:
                 packet.state = bfd_control_packet.STATE_INIT
             packet.your_discrim = packet.my_discrim
             packet.my_discrim = discrim
             packet.req_min_echo = 0
             udp_hdr = dpkt.udp.UDP( dport=BFD_PORT,
                                     sport=31337,
                                     data=packet.render()
                                     )
             udp_hdr.ulen += len(udp_hdr.data)
             ip_hdr = dpkt.ip.IP(    ttl=255,
                                     tos=0xC0,
                                     p=dpkt.ip.IP_PROTO_UDP,
                                     src=ip.dst,
                                     dst=ip.src,
                                     data=str(udp_hdr)
                                     )
             ip_hdr.len += len(ip_hdr.data)
             eth_hdr = dpkt.ethernet.Ethernet(   dst=eth.src,
                                                 src=eth.dst,
                                                 type=dpkt.ethernet.ETH_TYPE_IP,
                                                 data=str(ip_hdr)
                                                 )
             self.dnet.send(str(eth_hdr))
         elif dos and packet.state > bfd_control_packet.STATE_DOWN:
             packet.state = bfd_control_packet.STATE_DOWN
             tmp = packet.your_discrim
             packet.your_discrim = packet.my_discrim
             packet.my_discrim = tmp
             udp_hdr = dpkt.udp.UDP( dport=udp.dport,
                                     sport=udp.sport,
                                     data=packet.render()
                                     )
             udp_hdr.ulen += len(udp_hdr.data)
             ip_hdr = dpkt.ip.IP(    ttl=255,
                                     tos=0xC0,
                                     p=dpkt.ip.IP_PROTO_UDP,
                                     src=ip.dst,
                                     dst=ip.src,
                                     data=str(udp_hdr)
                                     )
             ip_hdr.len += len(ip_hdr.data)
             eth_hdr = dpkt.ethernet.Ethernet(   dst=eth.src,
                                                 src=eth.dst,
                                                 type=dpkt.ethernet.ETH_TYPE_IP,
                                                 data=str(ip_hdr)
                                                 )
             self.dnet.send(str(eth_hdr))
Beispiel #40
0
def main():
    parser = OptionParser()
    parser.add_option('-i', '--input', dest='input', default='sample.dump.gz',
                      help='read input from FILE', metavar='FILE')
    parser.add_option("-m", "--machine", action="store_true", dest="machine",
                      default=False, help="output in machine-readable form")
    (options, args) = parser.parse_args()

    out = sys.stdout.write
    dump = BGPDump(options.input)

    if options.machine:
        for mrt_h, bgp_h, bgp_m in dump:
            next_hop = 'none'
            atomic_aggregate = 'NAG'
            local_pref = multi_exit_disc = '0'
            origin = as_path = communities = aggregator = ''

            for attr in bgp_m.update.attributes:
                if attr.type == bgp.AS_PATH:
                    as_path = aspath_to_str(attr.as_path)
                elif attr.type == bgp.ORIGIN:
                    origin = origin_to_str(attr.origin)
                elif attr.type == bgp.NEXT_HOP:
                    next_hop = dnet.ip_ntoa(attr.next_hop.ip)
                elif attr.type == bgp.LOCAL_PREF:
                    local_pref = '%d' % (attr.local_pref.value)
                elif attr.type == bgp.MULTI_EXIT_DISC:
                    multi_exit_disc = '%d' % (attr.multi_exit_disc.value)
                elif attr.type == bgp.COMMUNITIES:
                    communities = communities_to_str(attr.communities)
                elif attr.type == bgp.ATOMIC_AGGREGATE:
                    atomic_aggregate = 'AG'
                elif attr.type == bgp.AGGREGATOR:
                    aggregator = dnet.ip_ntoa(attr.aggregator.ip)

            time_str = '%s|%s' % ('BGP4MP', mrt_h.ts)

            attrs = '%s|%s|%s|%s|%s|%s|%s|%s|' % \
                    (as_path, origin, next_hop, local_pref, multi_exit_disc,
                     communities, atomic_aggregate, aggregator)

            for route in bgp_m.update.announced:
                out('%s|A|%s|%d|%s/%d|%s\n' % 
                    (time_str, dnet.ip_ntoa(bgp_h.src_ip), bgp_h.src_as,
                     dnet.ip_ntoa(route.prefix), route.len, attrs))

            for route in bgp_m.update.withdrawn:
                out('%s|W|%s|%d|%s/%d\n' % 
                    (time_str, dnet.ip_ntoa(bgp_h.src_ip), bgp_h.src_as,
                     dnet.ip_ntoa(route.prefix), route.len))
    else:
        for mrt_h, bgp_h, bgp_m in dump:
            origin = as_path = next_hop = multi_exit_disc = local_pref = \
            atomic_aggregate = aggregator = originator_id = cluster_list = \
            communities = None
            for attr in bgp_m.update.attributes:
                if attr.type == bgp.ORIGIN:
                    origin = origin_to_str(attr.origin)
                elif attr.type == bgp.AS_PATH:
                    as_path = aspath_to_str(attr.as_path)
                elif attr.type == bgp.NEXT_HOP:
                    next_hop = dnet.ip_ntoa(attr.next_hop.ip)
                elif attr.type == bgp.MULTI_EXIT_DISC:
                    multi_exit_disc = '%d' % (attr.multi_exit_disc.value)
                elif attr.type == bgp.LOCAL_PREF:
                    local_pref = '%d' % (attr.local_pref.value)
                elif attr.type == bgp.ATOMIC_AGGREGATE:
                    atomic_aggregate = 'AG'
                elif attr.type == bgp.AGGREGATOR:
                    aggregator = 'AS%d %s' % \
                                 (attr.aggregator.asn,
                                  dnet.ip_ntoa(attr.aggregator.ip))
                elif attr.type == bgp.ORIGINATOR_ID:
                    originator_id = dnet.ip_ntoa(attr.originator_id.value)
                elif attr.type == bgp.CLUSTER_LIST:
                    cluster_list = clusterlist_to_str(attr.cluster_list)
                elif attr.type == bgp.COMMUNITIES:
                    communities = communities_to_str(attr.communities)

            out('TIME: %s\n' %
                (time.strftime('%D %T', time.localtime(mrt_h.ts))))
            out('TYPE: BGP4MP/MESSAGE/Update\n')
            out('FROM: %s AS%d\n' % (dnet.ip_ntoa(bgp_h.src_ip), bgp_h.src_as))
            out('TO: %s AS%d\n' % (dnet.ip_ntoa(bgp_h.dst_ip), bgp_h.dst_as))
            if origin:
                out('ORIGIN: %s\n' % (origin))
            if as_path:
                out('ASPATH: %s\n' % (as_path))
            if next_hop:
                out('NEXT_HOP: %s\n' % (next_hop))
            if multi_exit_disc:
                out('MULTI_EXIT_DISC: %s\n' % (multi_exit_disc))
            if local_pref:
                out('LOCAL_PREF: %s\n' % (local_pref))
            if atomic_aggregate:
                out('ATOMIC_AGGREGATE\n')
            if aggregator:
                out('AGGREGATOR: %s\n' % (aggregator))
            if originator_id:
                out('ORIGINATOR_ID: %s\n' % (originator_id))
            if cluster_list:
                out('CLUSTER_LIST: %s\n' % (cluster_list))
            if communities:
                out('COMMUNITY: %s\n' % (communities))

            if len(bgp_m.update.announced) > 0:
                out('ANNOUNCE\n')
                for route in bgp_m.update.announced:
                    out('  %s/%d\n' % (dnet.ip_ntoa(route.prefix), route.len))

            if len(bgp_m.update.withdrawn) > 0:
                out('WITHDRAW\n')
                for route in bgp_m.update.withdrawn:
                    out('  %s/%d\n' % (dnet.ip_ntoa(route.prefix), route.len))

            out('\n')
Beispiel #41
0
 def input_udp(self, eth, ip, udp, timestamp):
     packet = bfd_control_packet()
     packet.parse(udp.data)
     src = dnet.ip_ntoa(ip.src)
     dst = dnet.ip_ntoa(ip.dst)
     id = "%s:%s" % (src, dst)
     id_rev = "%s:%s" % (dst, src)
     auth = "None"
     if packet.flags & bfd_control_packet.FLAG_AUTH:
         auth = bfd_auth.type_to_str[packet.auth.type]
     password = ""
     if packet.flags & bfd_control_packet.FLAG_AUTH and packet.auth.type == bfd_auth.TYPE_SIMPLE:
         password = packet.auth.data
     if id not in self.neighbors and id_rev not in self.neighbors:
         self.activate_filter()
         if self.ui == 'gtk':
             self.filter_checkbutton.set_active(True)
         elif self.ui == 'urw':
             self.filter_checkbox.set_state(True)
         self.log("BFD: got new session: %s -> %s" % (src, dst))
         if self.ui == 'gtk':
             iter = self.neighbor_treestore.append(None, [
                 src, dst, bfd_control_packet.state_to_str[packet.state],
                 bfd_control_packet.diag_to_str[packet.diag], auth,
                 self.auto_answer, False
             ])
         elif self.ui == 'urw':
             label = "%s - %s %s %s AUTH(%s)" % (
                 src, dst, bfd_control_packet.state_to_str[packet.state],
                 bfd_control_packet.diag_to_str[packet.diag], auth)
             if password != "":
                 label += " PASS(%s)" % password
             answer_c = urwid.CheckBox(
                 "Answer",
                 self.auto_answer,
                 on_state_change=self.urw_answer_checkbox_changed,
                 user_data=id)
             dos_c = urwid.CheckBox(
                 "DOS",
                 False,
                 on_state_change=self.urw_dos_checkbox_changed,
                 user_data=id)
             if not auth == "None":
                 button = self.parent.menu_button(label,
                                                  self.crack_activated, id)
             else:
                 button = self.parent.menu_button(label)
             self.hostlist.append(
                 urwid.Columns([('weight', 4, button), answer_c, dos_c]))
             iter = (button, answer_c, dos_c)
         self.neighbors[id] = (iter, random.randint(0x1, 0x7fffffff),
                               self.auto_answer, False, False, udp.data,
                               password)
     if id in self.neighbors:
         (iter, discrim, answer, dos, crack, data,
          password) = self.neighbors[id]
         if self.ui == 'gtk':
             if self.neighbor_treestore.iter_is_valid(iter):
                 self.neighbor_treestore.set_value(
                     iter, self.NEIGH_STATE_ROW,
                     bfd_control_packet.state_to_str[packet.state])
                 self.neighbor_treestore.set_value(
                     iter, self.NEIGH_DIAG_ROW,
                     bfd_control_packet.diag_to_str[packet.diag])
         elif self.ui == 'urw':
             (button, answer_c, dos_c) = iter
             label = "%s - %s %s %s AUTH(%s)" % (
                 src, dst, bfd_control_packet.state_to_str[packet.state],
                 bfd_control_packet.diag_to_str[packet.diag], auth)
             if password != "":
                 label += " PASS(%s)" % password
             button.base_widget.set_label(label)
         if answer and packet.diag == bfd_control_packet.DIAG_NO:
             if packet.state == bfd_control_packet.STATE_DOWN:
                 packet.state = bfd_control_packet.STATE_INIT
             packet.your_discrim = packet.my_discrim
             packet.my_discrim = discrim
             packet.req_min_echo = 0
             udp_hdr = dpkt.udp.UDP(dport=BFD_PORT,
                                    sport=31337,
                                    data=packet.render())
             udp_hdr.ulen += len(udp_hdr.data)
             ip_hdr = dpkt.ip.IP(ttl=255,
                                 tos=0xC0,
                                 p=dpkt.ip.IP_PROTO_UDP,
                                 src=ip.dst,
                                 dst=ip.src,
                                 data=str(udp_hdr))
             ip_hdr.len += len(ip_hdr.data)
             eth_hdr = dpkt.ethernet.Ethernet(
                 dst=eth.src,
                 src=eth.dst,
                 type=dpkt.ethernet.ETH_TYPE_IP,
                 data=str(ip_hdr))
             self.dnet.send(str(eth_hdr))
         elif dos and packet.state > bfd_control_packet.STATE_DOWN:
             packet.state = bfd_control_packet.STATE_DOWN
             tmp = packet.your_discrim
             packet.your_discrim = packet.my_discrim
             packet.my_discrim = tmp
             udp_hdr = dpkt.udp.UDP(dport=udp.dport,
                                    sport=udp.sport,
                                    data=packet.render())
             udp_hdr.ulen += len(udp_hdr.data)
             ip_hdr = dpkt.ip.IP(ttl=255,
                                 tos=0xC0,
                                 p=dpkt.ip.IP_PROTO_UDP,
                                 src=ip.dst,
                                 dst=ip.src,
                                 data=str(udp_hdr))
             ip_hdr.len += len(ip_hdr.data)
             eth_hdr = dpkt.ethernet.Ethernet(
                 dst=eth.src,
                 src=eth.dst,
                 type=dpkt.ethernet.ETH_TYPE_IP,
                 data=str(ip_hdr))
             self.dnet.send(str(eth_hdr))
Beispiel #42
0
    def input_udp(self, eth, ip, udp, timestamp):
        if ip.src != self.ip:
            pkg = glbp_packet()
            data = pkg.parse(str(udp.data))
            req_resp = []
            auth = None
            nonce = None
            auth_str = "Unauthenticated"
            while len(data) > 0:
                #~ print "len: %d data: %s" % (len(data), data.encode("hex"))
                tlv = glbp_tlv()
                tlv.parse(data)
                if tlv.tlv_type == glbp_tlv.TYPE_HELLO:
                    hello = glbp_tlv_hello()
                    data = hello.parse(data)
                elif tlv.tlv_type == glbp_tlv.TYPE_REQ_RESP:
                    tmp = glbp_tlv_req_resp()
                    data = tmp.parse(data)
                    if not tmp.vmac == "\x00\x00\x00\x00\x00\x00":
                        req_resp.append(tmp)
                elif tlv.tlv_type == glbp_tlv.TYPE_AUTH:
                    auth = glbp_tlv_auth()
                    data = auth.parse(data)
                    if auth.auth_type == glbp_tlv_auth.TYPE_PLAIN:
                        auth_str = "Plaintext: '%s'" % auth.secret[:-1]
                    elif auth.auth_type == glbp_tlv_auth.TYPE_MD5_STRING:
                        auth_str = "MD5 String: '%s'" % auth.secret.encode(
                            "hex")
                    elif auth.auth_type == glbp_tlv_auth.TYPE_MD5_CHAIN:
                        auth_str = "MD5 Chain: '%s'" % auth.secret.encode(
                            "hex")
                    else:
                        auth_str = "Unknown"
                else:
                    #~ print "type: %d len: %d" % (tlv.tlv_type, tlv.tlv_length)
                    data = data[tlv.tlv_length:]
            try:
                src = dnet.ip_ntoa(ip.src)
            except:
                pass

            if ip.src in self.peers:
                (iter, _, _, req_resp_old, _, _, _) = self.peers[ip.src]
                for i in req_resp:
                    if not i in req_resp_old:
                        req_resp_old.append(i)
                        self.treestore.append(
                            iter,
                            ["", "", i.weight,
                             dnet.eth_ntoa(i.vmac), ""])
            else:
                iter = self.treestore.append(None, [
                    src,
                    dnet.ip_ntoa(hello.addr), hello.prio, "Seen", auth_str
                ])
                for req in req_resp:
                    self.treestore.append(
                        iter,
                        ["", "", req.weight,
                         dnet.eth_ntoa(req.vmac), ""])
                self.peers[ip.src] = (iter, pkg, hello, req_resp, auth, False,
                                      False)
                self.log("GLBP: Got new peer %s" % (src))
Beispiel #43
0
    def main(self):
        if len(sys.argv) < 4:
            print 'Usage: %s interface target_ip target_port' % sys.argv[0]
            sys.exit(1)

        print '0trace.py by Jon Oberheide <*****@*****.**>'

        interface = sys.argv[1]
        target_ip = dnet.addr(sys.argv[2])
        target_port = sys.argv[3]
        filter = 'src host %s and src port %s and (tcp[13] & 0x17 == 0x10)' % \
                 (target_ip, target_port)

        pc = pcap.pcap(interface)
        pc.setfilter(filter)
        pc.setnonblock(True)

        print '[+] Waiting for traffic from target on %s...' % interface

        while True:
            rfd, wfd, efd = select.select([pc.fileno()], [], [])
            if rfd:
                ts, pkt = pc.next()
                break

        print '[+] Traffic acquired, waiting for a gap...'

        while True:
            rfd, wfd, efd = select.select([pc.fileno()], [], [], 3)
            if not rfd:
                break
            ts, pkt = pc.next()

        eth = dpkt.ethernet.Ethernet(pkt)
        ip = eth.data
        tcp = ip.data
        ip.src, ip.dst = ip.dst, ip.src
        tcp.seq, tcp.ack = tcp.ack, tcp.seq
        tcp.sport, tcp.dport = tcp.dport, tcp.sport

        print '[+] Target acquired: %s:%s -> %s:%s (%s/%s)' % \
              (dnet.ip_ntoa(ip.src), tcp.sport,
               dnet.ip_ntoa(ip.dst), tcp.dport, 
               tcp.seq, tcp.ack)

        print '[+] Setting up a sniffer...'

        m = Monitor('icmp or (%s)' % filter)
        m.start()
        time.sleep(1)

        print '[+] Sending probes...'

        p = AckProbe(ip, tcp)
        p.start()
        p.join()
        m.join(5)

        print
        print 'TRACE RESULTS'
        print '-------------'

        m.hops = list(sets.Set(m.hops))
        m.hops.sort()
        for id, hop in m.hops:
            print '%d %s' % (id, dnet.ip_ntoa(hop))

        if m.reached:
            print 'Target reached.'
        else:
            print 'Probe rejected by target.'
        print