示例#1
0
def main():

    if len(sys.argv) < 3:
        print 'pass 3 arguments: <destination> <num>'
        exit(1)

    addr = socket.gethostbyname(sys.argv[1])
    num = int(sys.argv[2])
    iface = get_if()
    print "sending on interface %s to %s" % (iface, str(addr))

    while num > 0:
        num = num - 1
        s = "2 2 1"
        i = 0
        pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
        for p in s.split(" "):
            try:
                pkt = pkt / SourceRoute(bos=0, port=int(p))
                i = i + 1
            except ValueError:
                pass
        if pkt.haslayer(SourceRoute):
            pkt.getlayer(SourceRoute, i).bos = 1

        pkt = pkt / IP(
            dst=addr, options=IPOption_MRI(
                count=0, pathid=1, swtraces=[])) / UDP(dport=4321, sport=1234)
        pkt.show2()
        sendp(pkt, iface=iface, verbose=False)
def send():
    iface_tx = get_if()
    global wCurr, rCurr
    j = 0
    pkt = Ether(src=get_if_hwaddr(iface_tx), dst="ff:ff:ff:ff:ff:ff")
    for p in rCurr:
        try:
            pkt = pkt / SourceRoute(bos=0, port=p)
            j = j + 1
        except ValueError:
            pass
    if pkt.haslayer(SourceRoute):
        pkt.getlayer(SourceRoute, j).bos = 1

    # Check if sent enough packets
    global totalSent

    if wCurr + totalSent >= goalSent:
        wCurr = goalSent - totalSent
        print "Time Start: ", time_start  # Recorded for FCT evaluation
    totalSent = totalSent + wCurr
    print("Winodow is: ", wCurr)
    print("Route is: ", nCurr)
    t = (time.time() -
         time_start) * 1000000  # timestamp in the unit of microsecond
    pkt = pkt / IP(dst=dst_ip, proto=17) / UDP(dport=4321, sport=1234) / MRI(
        count=1, swtraces=[SwitchTrace(swid=100, egresst=t)]) / str(
            RandString(size=1000))
    sendp(pkt, iface=iface_tx, inter=0, count=wCurr, verbose=False)
示例#3
0
def main():

    if len(sys.argv)<2:
        print 'pass 2 arguments: <destination>'
        exit(1)

    addr = socket.gethostbyname(sys.argv[1])
    iface = get_if()
    print "sending on interface %s to %s" % (iface, str(addr))

    while True:
        print
        s = str(raw_input('Type space separated port nums '
                          '(example: "2 3 2 2 1") or "q" to quit: '))
        if s == "q":
            break;
        print

        i = 0
        pkt =  Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff');
        for p in s.split(" "):
            try:
                pkt = pkt / SourceRoute(bos=0, port=int(p))
                i = i+1
            except ValueError:
                pass
        if pkt.haslayer(SourceRoute):
            pkt.getlayer(SourceRoute, i).bos = 1

        pkt = pkt / IP(dst=addr) / UDP(dport=4321, sport=1234)
        pkt.show2()
        sendp(pkt, iface=iface, verbose=False)
示例#4
0
    def get_packet(pkt):

       if not pkt.getlayer(NBNSQueryRequest):
           return

       if pkt.FLAGS & 0x8000:
           query = False
           addr = unpack_ip(str(pkt.getlayer(Raw))[8:])
       else:
           query = True

       if verbose:
           print str(pkt.NAME_TRN_ID) + ":",
           if query:
               print "Q",
           else:
               print "R",
           print "SRC:" + pkt.getlayer(IP).src + " DST:" + pkt.getlayer(IP).dst,
           if query:
               print 'NAME:"' + pkt.QUESTION_NAME + '"'
           else:
               print 'NAME:"' + pkt.QUESTION_NAME + '"',
               print 'IP:' + addr

       if query and regexp.match(pkt.QUESTION_NAME.rstrip(),1):
            response  = Ether(dst=pkt.src,src=mac_addr)
            response /= IP(dst=pkt.getlayer(IP).src,src=ip)
            response /= UDP(sport=137,dport=137)
            response /= NBNSQueryRequest(
                NAME_TRN_ID=pkt.getlayer(NBNSQueryRequest).NAME_TRN_ID,\
                FLAGS=0x8500,\
                QDCOUNT=0,\
                ANCOUNT=1,\
                NSCOUNT=0,\
                ARCOUNT=0,\
                QUESTION_NAME=pkt.getlayer(NBNSQueryRequest).QUESTION_NAME,\
                SUFFIX=pkt.getlayer(NBNSQueryRequest).SUFFIX,\
                NULL=0,\
                QUESTION_TYPE=pkt.getlayer(NBNSQueryRequest).QUESTION_TYPE,\
                QUESTION_CLASS=pkt.getlayer(NBNSQueryRequest).QUESTION_CLASS)
            response /= Raw()
            # Time to live: 3 days, 11 hours, 20 minutes
            response.getlayer(Raw).load += '\x00\x04\x93\xe0'
            # Data length: 6
            response.getlayer(Raw).load += '\x00\x06'
            # Flags: (B-node, unique)
            response.getlayer(Raw).load += '\x00\x00'
            # The IP we're giving them:
            response.getlayer(Raw).load += pack_ip(ip)
            sendp(response,iface=interface,verbose=0)
            if verbose:
                print 'Sent spoofed reply to #' + str(response.getlayer(NBNSQueryRequest).NAME_TRN_ID)
示例#5
0
    def handle_read(self):
        # | 4 bytes | 4 bytes |   18 bytes   |     1500 bytes    |
        #     Tap       VLAN    Ether Header          Frame
        buf = self.read(1526)
        eth_rcvd_frame = Ether(buf[4:])

        #if DEBUG:
        #    os.write(1,"Received from %s\n" % ifname)
        #    if VERB:
        #        os.write(1,"%s\n" % eth_rcvd_frame.summary())

        # Prepare Dot11 frame for injection
        dot11_sent_frame = self.radiotap()

        dot11_sent_frame /= Dot11(
            type = "Data",
            FCfield = "from-DS",
            addr1 = eth_rcvd_frame.getlayer(Ether).dst,
            addr2 = self._tap.bssid)

        # It doesn't seem possible to set tuntap interface MAC address
        # when we create it, so we set source MAC here
        if self._tap.smac == '':
            dot11_sent_frame.addr3 = eth_rcvd_frame.getlayer(Ether).src
        else:
            dot11_sent_frame.addr3 = self._tap.smac

        if self._tap.has_wep:
            dot11_sent_frame.FCfield |= 0x40
            dot11_sent_frame /= Dot11WEP(
                iv = "111",
                keyid = self._tap.key_id)

        dot11_sent_frame /= LLC(ctrl = 3)/SNAP(code=eth_rcvd_frame.getlayer(Ether).type)/eth_rcvd_frame.getlayer(Ether).payload

        #if DEBUG:
        #    os.write(1,"Sending from-DS to %s\n" % OUT_IFACE)
        #    if VERB:
        #        os.write(1,"%s\n" % dot11_sent_frame.summary())

        # Frame injection :
        sendp(dot11_sent_frame,verbose=0) # Send from-DS frame
示例#6
0
    def handle_read(self):
        # | 4 bytes | 4 bytes |   18 bytes   |     1500 bytes    |
        #     Tap       VLAN    Ether Header          Frame
        buf = self.read(1526)
        eth_rcvd_frame = Ether(buf[4:])

        #if DEBUG:
        #    os.write(1,"Received from %s\n" % ifname)
        #    if VERB:
        #        os.write(1,"%s\n" % eth_rcvd_frame.summary())

        # Prepare Dot11 frame for injection
        dot11_sent_frame = self.radiotap()

        dot11_sent_frame /= Dot11(type="Data",
                                  FCfield="from-DS",
                                  addr1=eth_rcvd_frame.getlayer(Ether).dst,
                                  addr2=self._tap.bssid)

        # It doesn't seem possible to set tuntap interface MAC address
        # when we create it, so we set source MAC here
        if self._tap.smac == '':
            dot11_sent_frame.addr3 = eth_rcvd_frame.getlayer(Ether).src
        else:
            dot11_sent_frame.addr3 = self._tap.smac

        if self._tap.has_wep:
            dot11_sent_frame.FCfield |= 0x40
            dot11_sent_frame /= Dot11WEP(iv="111", keyid=self._tap.key_id)

        dot11_sent_frame /= LLC(ctrl=3) / SNAP(code=eth_rcvd_frame.getlayer(
            Ether).type) / eth_rcvd_frame.getlayer(Ether).payload

        #if DEBUG:
        #    os.write(1,"Sending from-DS to %s\n" % OUT_IFACE)
        #    if VERB:
        #        os.write(1,"%s\n" % dot11_sent_frame.summary())

        # Frame injection :
        sendp(dot11_sent_frame, verbose=0)  # Send from-DS frame
示例#7
0
    def encapsulate(cls, packet_or_frame, src_mac, dst_mac):
        if dst_mac == None:
            dst_mac = Ethernet.DefaultDst
        if src_mac == None:
            src_mac = Ethernet.DefaultSrc

        try:
            if not packet_or_frame.haslayer(Ether):
                packet_or_frame = Ether() / packet_or_frame

            packet_or_frame.getlayer(Ether).src = src_mac
            packet_or_frame.getlayer(Ether).dst = dst_mac
        except AttributeError:
            pass

        return packet_or_frame
示例#8
0
    def encapsulate(cls, packet_or_frame, src_mac, dst_mac):
        if dst_mac == None:
            dst_mac = Ethernet.DefaultDst
        if src_mac == None:
            src_mac = Ethernet.DefaultSrc

        try:
            if not packet_or_frame.haslayer(Ether):
                packet_or_frame = Ether()/packet_or_frame

            packet_or_frame.getlayer(Ether).src = src_mac
            packet_or_frame.getlayer(Ether).dst = dst_mac
        except AttributeError:
            pass

        return packet_or_frame
示例#9
0
def main():

    if len(sys.argv) < 2:
        print 'pass 2 arguments: <destination>'
        exit(1)

    #addr = socket.gethostbyname(sys.argv[1])
    iface = get_if()
    print "sending on interface %s to %s" % (iface, sys.argv[1])

    print
    s = str(
        raw_input('Type space separated port nums '
                  '(example: "4 3 1 2 2 ") or "q" to quit: '))
    if s == "q":
        exit(1)
    print

    i = 0
    pkt = Ether(src=get_if_hwaddr(iface), dst='00:00:00:00:02:02')

    for p in s.split(" "):
        try:
            pkt = pkt / SourceRoute(bos=0, port=int(p))
            i = i + 1
        except ValueError:
            pass
    if pkt.haslayer(SourceRoute):
        pkt.getlayer(SourceRoute, i).bos = 1

    #pkt = pkt / IPv6(dst=sys.argv[1], nh=150) / Bitmap(bit_label=228, bit_reserve=0) / MRI1(count=0, swtraces=[])
    pkt = pkt / IPv6(dst=sys.argv[1], nh=150)

    while True:
        with open('flag.txt', 'r') as f:
            t = float(f.readline())
        if (t != MAX_t):
            p = pkt / Bitmap(bit_label=255, bit_reserve=0) / MRI1(count=0,
                                                                  swtraces=[])
        else:
            p = pkt / Bitmap(bit_label=228, bit_reserve=0) / MRI2(count=0,
                                                                  swtraces=[])
        #p = pkt / Bitmap(bit_label=255, bit_reserve=0) / MRI1(count=0, swtraces=[])
        p.show2()
        sendp(p, iface=iface, verbose=False)
        sleep(t)
示例#10
0
    def parse_dhcp_offer_or_ack(self, pkt, xid):
        '''Use Scapy to parse and obtain the interesting fields from a DHCPACK
        or DHCPOFFER packet received from the network.'''

        parse_result = dict()

        e = Ether(pkt)

        parse_result['ether_src_address'] = e.src

        # Some conditions ought to be true by the time we get here; assert that they are.
        assert e.type == 0x0800
        i = e.getlayer('IP')

        parse_result['ip_src_address'] = i.src
        parse_result['ip_dst_address'] = i.dst

        assert i.proto == 17
        u = i.getlayer('UDP')

        assert u.sport == 67
        assert u.dport == 68
        b = u.getlayer('BOOTP')

        assert b.op == 2
        assert b.xid == xid

        parse_result['siaddr'] = b.siaddr
        parse_result['yiaddr'] = b.yiaddr

        d = b.getlayer('DHCP')

        for option in d.options:
            if isinstance(option, str):
                assert option == 'end'
                break
            assert isinstance(option, tuple)
            assert isinstance(option[0], str)
            parse_result[option[0]] = option[1]

        for key in parse_result:
            logging.debug('Packet parse result: "{}" => "{}"'.format(
                key, parse_result[key]))

        return parse_result
示例#11
0
def send_ack(pkt):
    iface = get_if()

    options = getOptions(sys.argv[1:])
    list_switches, dict_host_ip, dict_link_weight, dict_link_port = get_network(
        options.topo)
    global dict_mri

    flag = 0
    for i in range(0, len(pkt[MRI].swtraces)):
        dict_mri[pkt[MRI].swtraces[i].swid] = pkt[MRI].swtraces[i].qdepth
        if pkt[MRI].swtraces[i].qdepth > 5:
            flag = 1

    src_ip = pkt[IP].src
    dst_ip = pkt[IP].dst

    src_host = dict_host_ip.keys()[dict_host_ip.values().index(src_ip)]
    dst_host = dict_host_ip.keys()[dict_host_ip.values().index(dst_ip)]

    sp_nodes, sp_ports = update_shorest_path(dict_mri,
                                             dict_link_weight,
                                             dict_link_port,
                                             src=dst_host,
                                             dst=src_host)

    ack = Ether(src=get_if_hwaddr(iface), dst="ff:ff:ff:ff:ff:ff")
    j = 0
    for p in sp_ports:
        try:
            ack = ack / SourceRoute(bos=0, port=p)
            j = j + 1
        except ValueError:
            pass
    if ack.haslayer(SourceRoute):
        ack.getlayer(SourceRoute, j).bos = 1

    ack = ack / IP(dst=pkt[IP].src, proto=17) / UDP(
        dport=4322, sport=1235) / MRI(count=pkt[MRI].count,
                                      swtraces=pkt[MRI].swtraces)
    # ack.show2()
    sendp(ack, iface=iface, verbose=False)
    print("ACK sent at time: ", time.time())
示例#12
0
def main():

    if len(sys.argv) < 2:
        print 'pass 2 arguments: <destination>'
        exit(1)

    #addr = socket.gethostbyname(sys.argv[1])
    iface = get_if()
    print "sending on interface %s to %s" % (iface, sys.argv[1])

    while True:
        print
        s = str(
            raw_input('Type space separated port nums '
                      '(example: "4 3 1 2 2 ") or "q" to quit: '))
        if s == "q":
            break
        print

        i = 0
        #pkt =  Ether(src=get_if_hwaddr(iface), dst='00:aa:00:00:00:01');
        pkt = Ether()
        for p in s.split(" "):
            try:
                pkt = pkt / SourceRoute(bos=0, port=int(p))
                i = i + 1
            except ValueError:
                pass
        if pkt.haslayer(SourceRoute):
            pkt.getlayer(SourceRoute, i).bos = 1

        pkt = pkt / IPv6(dst=sys.argv[1], nh=150) / MRI(count=0, swtraces=[])
        #pkt = pkt / SwitchTrace(swid=0, in_port=0, out_port=0, qdepth=0, in_time=0, out_time=0, bos=0)
        #pkt = pkt / SwitchTrace(swid=0, in_port=0, out_port=0, qdepth=0, in_time=0, out_time=0, bos=0)
        #pkt = pkt / UDP(dport=4321, sport=1234) / "P4 is cool"
        pkt.show2()

        for i in range(int(sys.argv[2])):
            sendp(pkt, iface=iface, verbose=False)
            sleep(1)
示例#13
0
        if f in r:

            # tuntap frame max. size is 1522 (ethernet, see RFC3580) + 4
            buf = os.read(f, 1526)
            eth_rcvd_frame = Ether(buf[4:])

            if DEBUG:
                os.write(1, "Received from %s\n" % ifname)
                if VERB:
                    os.write(1, "%s\n" % eth_rcvd_frame.summary())

# Prepare Dot11 frame for injection
            dot11_sent_frame = RadioTap() / Dot11(
                type="Data",
                FCfield="from-DS",
                addr1=eth_rcvd_frame.getlayer(Ether).dst,
                addr2=BSSID)
            # It doesn't seem possible to set tuntap interface MAC address
            # when we create it, so we set source MAC here
            if not HAS_SMAC:
                dot11_sent_frame.addr3 = eth_rcvd_frame.getlayer(Ether).src
            else:
                dot11_sent_frame.addr3 = SMAC
            if WEP:
                dot11_sent_frame.FCfield |= 0x40
                dot11_sent_frame /= Dot11WEP(iv="111", keyid=KEYID)
            dot11_sent_frame /= LLC(ctrl=3) / SNAP(
                code=eth_rcvd_frame.getlayer(
                    Ether).type) / eth_rcvd_frame.getlayer(Ether).payload

            if DEBUG:
示例#14
0
	if f in r:

	    # tuntap frame max. size is 1522 (ethernet, see RFC3580) + 4
	    buf = os.read(f,1526)
            eth_rcvd_frame=Ether(buf[4:])

	    if DEBUG:
	        os.write(1,"Received from %s\n" % ifname)
		if VERB:
		    os.write(1,"%s\n" % eth_rcvd_frame.summary())
	    
	# Prepare Dot11 frame for injection
	    dot11_sent_frame = RadioTap()/Dot11(
		type = "Data",
		FCfield = "from-DS",
		addr1 = eth_rcvd_frame.getlayer(Ether).dst,
		addr2 = BSSID)
	# It doesn't seem possible to set tuntap interface MAC address
	# when we create it, so we set source MAC here
	    if not HAS_SMAC:
	        dot11_sent_frame.addr3 = eth_rcvd_frame.getlayer(Ether).src
	    else:
		dot11_sent_frame.addr3 = SMAC
	    if WEP:
		dot11_sent_frame.FCfield |= 0x40
		dot11_sent_frame /= Dot11WEP(
		    iv = "111",
		    keyid = KEYID)
	    dot11_sent_frame /= LLC(ctrl = 3)/SNAP(code=eth_rcvd_frame.getlayer(Ether).type)/eth_rcvd_frame.getlayer(Ether).payload

	    if DEBUG:
示例#15
0
def collector(pkt):
    global COUNT, COUNT_SERVER, COUNT_CLIENT, NEW_BIND_PORTS

    COUNT += 1

    if savepcap:
        pcap_dump.write(pkt)

    print(f'[*] running... {put_color(next(roll), "green")}', end='\r')

    tcp_layer = pkt.getlayer('TCP')
    if tcp_layer is None:
        return

    IP_layer = pkt.getlayer("IP") or pkt.getlayer("IPv6")

    src_ip = IP_layer.src
    src_port = pkt.getlayer("TCP").sport

    dst_ip = IP_layer.dst
    dst_port = pkt.getlayer("TCP").dport

    layer = get_attr(tcp_layer[0], 'msg')
    if not layer:
        # 有两种情况会导致为空
        # 1. 可能不为 TLS/SSL
        # 2. 也可能是 Scapy 认为这个端口不会传输 TLS/SSL,
        #    见 github.com/secdev/scapy/issues/2806
        if pkt.lastlayer().name != 'Raw':
            # 如果最后一层不是 Raw,
            # 那么就可以排除第二种情况
            # 直接舍弃
            return

        if src_port in NEW_BIND_PORTS[0] and dst_port in NEW_BIND_PORTS[1]:
            # 如果之前已经加过这两个端口
            # 依旧没有识别出来,就可以排除第二种情况
            return

        # 新增端口,
        # 告诉 scapy 遇到这对端口也要尝试解析 TLS/SSL
        # _注意这里的端口并非成对的,而是可以随意组合的_
        bind_layers(TCP, TLS, sport=src_port)  # noqa: F821
        bind_layers(TCP, TLS, dport=dst_port)  # noqa: F821

        NEW_BIND_PORTS[0].add(src_port)
        NEW_BIND_PORTS[1].add(dst_port)

        # 新增端口之后还需要重新解析数据包
        pkt = Ether(pkt.do_build())
        tcp_layer = pkt.getlayer('TCP')
        layer = get_attr(tcp_layer[0], 'msg')
        if not layer:
            # 一顿操作之后还是为空的话就舍弃
            return

    layer = layer[0]
    name = layer.name

    if not name.endswith('Hello'):
        return

    from_type = 0
    from_name = 'Server'
    fp_name = 'ja3s'

    if name.startswith('TLS') or name.startswith('SSL'):
        if 'Client' in name:
            from_type = 1
            from_name = 'Client'
            fp_name = 'ja3'
    else:
        return

    server_name = 'unknown'

    Version = layer.version
    Cipher = get_attr(layer, 'ciphers' if from_type else 'cipher')

    exts = get_attr(layer, 'ext')
    if exts:
        Extensions_Type = list(map(lambda c: c.type, exts))

        # 下面几个字段可能是出现在固定的位置
        # 但是这样写保险一点
        if from_type:
            # 版本(TLS ClientHello Version)、可接受的加密算法(Ciphers)、扩展列表各个段的长度(Extensions Length)
            # 椭圆曲线密码(TLS_Ext_SupportedGroups)、椭圆曲线密码格式(ec_point_formats)
            # 使用 `,` 来分隔各个字段,并通过 `-` 来分隔每个字段中的各个值
            # 最后变成一个字符串

            try:
                loc = Extensions_Type.index(0)
            except ValueError:
                server_name = 'unknown'
            else:
                server_names = get_attr(exts[loc], 'servernames')

                if server_names:
                    server_name = get_attr(server_names[0], 'servername',
                                           'unknown').decode('utf8')

            try:
                loc = Extensions_Type.index(11)
            except IndexError:
                EC_Point_Formats = []
            else:
                EC_Point_Formats = get_attr(exts[loc], 'ecpl')

            try:
                loc = Extensions_Type.index(10)
            except IndexError:
                Elliptic_Curves = []
            else:
                Elliptic_Curves = get_attr(exts[loc], 'groups')

            raw_fp = concat([
                Version, Cipher, Extensions_Type, Elliptic_Curves,
                EC_Point_Formats
            ])

    else:
        Extensions_Type = Elliptic_Curves = EC_Point_Formats = []

    if from_type:
        COUNT_CLIENT += 1
        raw_fp = concat([
            Version, Cipher, Extensions_Type, Elliptic_Curves, EC_Point_Formats
        ])
    else:
        COUNT_SERVER += 1
        raw_fp = concat([Version, Cipher, Extensions_Type])

    md5_fp = hashlib.md5(raw_fp.encode('utf8')).hexdigest()

    handshake_type = name.split(' ')[0]
    if need_json:
        json_data = {
            'from': from_name,
            'type': handshake_type,
            'src': {
                'ip': src_ip,
                'port': src_port,
            },
            'dst': {
                'ip': dst_ip,
                'port': dst_port,
            },
            fp_name: {
                'str': raw_fp,
                'md5': md5_fp
            }
        }

        if from_type:
            json_data['dst']['server_name'] = server_name

        Print(json_data)
    else:
        color_data = '\n'.join([
            f'[+] Hello from {put_color(from_name, "cyan", bold=False)}',
            f'  [-] type: {put_color(handshake_type, "green")}',
            f'  [-] src ip: {put_color(src_ip, "cyan")}',
            f'  [-] src port: {put_color(src_port, "white")}',
            f'  [-] dst ip: {put_color(dst_ip, "blue")}' +
            (f' ({put_color(server_name, "white")})' if from_type else ''),
            f'  [-] dst port: {put_color(dst_port, "white")}',
            f'  [-] {fp_name}: {raw_fp}',
            f'  [-] md5: {put_color(md5_fp, "yellow")}'
        ])
        Print(color_data)
示例#16
0
def main():
    pathIDs = []
    portpaths = []
    info = psutil.net_if_addrs()
    for cname in info.keys():
        if cname!='lo':
            hostname = cname.split('-')[0]
    print hostname
    #if len(sys.argv)<5:
    #    print 'pass 5 arguments: <destination> <num> <pathID> <path>'
    #    exit(1)
    f = open("pinglist16-1.txt", "r")
    line = f.readline()
    while line:
        line = line[0:-1]
        paras = line.split(" ")
        if hostname==paras[1].split(",")[0]:
            #pathID = int(paras[0])
            pathIDs.append(int(paras[0]))
            #s = paras[2]
            portpaths.append(paras[2])
        line = f.readline()
    addr = socket.gethostbyname("10.0.0.2")
    num = 0
    #pathID = int(sys.argv[3])
    #s=sys.argv[4]
    iface = get_if()
    #print "sending on interface %s to %s" % (iface, str(addr))
    pathnum = len(pathIDs)
    begin_time = datetime.datetime.now()
    

    probepkts = []
    for j in range(pathnum):
        pathID = pathIDs[j]
        s = portpaths[j]
        i=0
        pkt =  Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
        for p in s.split(","):
            try:
                pkt = pkt / SourceRoute(bos=0, port=int(p))
                i = i+1
            except ValueError:
                pass
        if pkt.haslayer(SourceRoute):
            pkt.getlayer(SourceRoute, i).bos = 1
        pkt = pkt / IP(dst=addr, options = IPOption_MRI(count=0, pathid=pathID, swtraces=[])) / UDP(dport=4321, sport=1234)
        probepkts.append(pkt)

    #write_cap(probepkts)
    packet_size = len(probepkts[0])


    while num<pathnum*200:
        #pathID = pathIDs[num%pathnum]
        #s=portpaths[num%pathnum]  
        '''
        i = 0
        pkt =  Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
        for p in s.split(","):
            try:
                pkt = pkt / SourceRoute(bos=0, port=int(p))
                i = i+1
            except ValueError:
                pass
        if pkt.haslayer(SourceRoute):
            pkt.getlayer(SourceRoute, i).bos = 1

        pkt = pkt / IP(dst=addr, options = IPOption_MRI(count=0, pathid=pathID, swtraces=[])) / UDP(dport=4321, sport=1234)
        #print len(pkt)
        #pkt.show2()
        '''
        #pkt.show2()
        sendp(probepkts[num%pathnum], iface=iface, verbose=False)
        print(str(num)+"/"+str(pathnum*200)) 
        num = num + 1  
        '''
示例#17
0
    def analyze(self):
        pcap = RawPcapReader(self.file_name).read_all()
        if not pcap:
            self.fail('Empty pcap {0}'.format(self.file_name))

        l4_type = None
        for index, (raw_pkt, _) in enumerate(pcap):
            scapy_pkt = Ether(raw_pkt)

            # l3
            ipv4 = scapy_pkt.getlayer('IP')
            ipv6 = scapy_pkt.getlayer('IPv6')
            if ipv4 and ipv6:
                scapy_pkt.show2()
                self.fail('Packet #%s in pcap has both IPv4 and IPv6!' % index)

            if ipv4:
                l3 = ipv4
            elif ipv6:
                l3 = ipv6
            else:
                scapy_pkt.show2()
                self.fail('Packet #%s in pcap is not IPv4/6.' % index)

            # first packet
            if self.c_ip is None:
                self.c_ip = l3.src
                self.s_ip = l3.dst
                direction = "c"
            else:
                if self.c_ip == l3.src and self.s_ip == l3.dst:
                    direction = "c"
                elif self.s_ip == l3.src and self.c_ip == l3.dst:
                    direction = "s"
                else:
                    self.fail(
                        'Only one session is allowed in a file. Packet {0} is from different session'
                        .format(index))

            # l4
            tcp = scapy_pkt.getlayer('TCP')
            udp = scapy_pkt.getlayer('UDP')
            if tcp and udp:
                scapy_pkt.show2()
                self.fail('Packet #%s in pcap has both TCP and UDP' % index)

            elif tcp:
                l4 = tcp
                # SYN
                if l4.flags & 0x02:
                    # SYN + ACK
                    if l4.flags & 0x10:
                        self.s_tcp_win = tcp.window
                        if self.state == _CPcapReader_help.states["init"]:
                            self.fail(
                                'Packet #%s is SYN+ACK, but there was no SYN yet, or '
                                % index)
                        else:
                            if self.state != _CPcapReader_help.states["syn"]:
                                self.fail(
                                    'Packet #%s is SYN+ACK, but there was already SYN+ACK in cap file'
                                    % index)
                        self.state = _CPcapReader_help.states["syn+ack"]
                    # SYN - no ACK. Should be first packet client->server
                    else:
                        self.c_tcp_win = tcp.window
                        # allowing syn retransmission because cap2/https.pcap contains this
                        if self.state > _CPcapReader_help.states["syn"]:
                            self.fail(
                                'Packet #%s is TCP SYN, but there was already TCP SYN in cap file'
                                % index)
                        else:
                            self.state = _CPcapReader_help.states["syn"]
                else:
                    if self.state != _CPcapReader_help.states["syn+ack"]:
                        self.fail(
                            'Cap file must start with syn, syn+ack sequence')
                if l4_type not in (None, 'TCP'):
                    self.fail(
                        'PCAP contains both TCP and %s. This is not supported currently.'
                        % l4_type)
                l4_type = 'TCP'
            elif udp:
                self.fail(
                    'CAP file contains UDP packets. This is not supported yet')
                #l4 = udp
                #if l4_type not in (None, 'UDP'):
                #    self.fail('PCAP contains both UDP and %s. This is not supported currently.' % l4_type)
                #l4_type = 'UDP'
            else:
                scapy_pkt.show2()
                self.fail('Packet #%s in pcap is not TCP or UDP.' % index)

            if self.s_port == -1:
                self.s_port = l4.sport
                self.d_port = l4.dport

            padding = scapy_pkt.getlayer('Padding')
            if padding is not None:
                pad_len = len(padding)
            else:
                pad_len = 0
            l4_payload_len = len(l4.payload) - pad_len
            self.total_payload_len += l4_payload_len
            self._pkts.append(
                CPacketData(direction,
                            bytes(l4.payload)[0:l4_payload_len]))
示例#18
0
def bpf_handler():
    global current_connection

    #arguments
    interface = "eth0"

    if len(argv) == 2:
        if str(argv[1]) == '-h':
            help()
        else:
            usage()

    if len(argv) == 3:
        if str(argv[1]) == '-i':
            interface = argv[2]
        else:
            usage()

    if len(argv) > 3:
        usage()

    success_text = open("./success", "rb").read()

    print("binding socket to '%s'" % interface)

    # initialize BPF - load source code from parse.c
    bpf = BPF(src_file="parse.c", debug=0)

    #load eBPF program filter of type SOCKET_FILTER into the kernel eBPF vm
    #more info about eBPF program types
    #http://man7.org/linux/man-pages/man2/bpf.2.html
    logging.info('JIT eBPF Code')
    function_filter = bpf.load_func("filter", BPF.SOCKET_FILTER)

    #create raw socket, bind it to interface
    #attach bpf program to socket created
    logging.info('Creating Raw Socket')
    BPF.attach_raw_socket(function_filter, interface)

    #get file descriptor of the socket previously created inside BPF.attach_raw_socket
    socket_fd = function_filter.sock

    #create python socket object, from the file descriptor
    sock = socket.fromfd(socket_fd, socket.PF_PACKET, socket.SOCK_RAW,
                         socket.IPPROTO_IP)
    #set it as blocking socket
    sock.setblocking(True)

    while True:
        #retrieve raw packet from socket
        packet_str = os.read(socket_fd, 2048)
        packet_bytearray = bytearray(packet_str)

        # Parse RAW data using scapy.. super general and easy
        c = Ether(packet_bytearray)
        if c.haslayer(IP):
            layer_ip = c.getlayer(IP)
            logging.info('IP: {} said the magic word ;-)'.format(layer_ip.src))
            if len(current_connection) > 0:
                for con, addr in current_connection:
                    if (layer_ip.src, layer_ip.sport) == addr:
                        con.send(success_text)
                logging.info('Sending success text now to: {}'.format(
                    layer_ip.src))