Exemple #1
0
 def get_sample_packet(self, pkt_type):
     if pkt_type == "tcp":
         return Ether() / IP(src=SOURCE_IP,
                             dst=DEST_IP) / TCP() / ("*" * 1500)
     elif pkt_type == "gtpu-udp":
         return (Ether() / IP(src=SOURCE_IP, dst=DEST_IP) / UDP() / GTPU() /
                 IP() / UDP() / ("*" * 1500))
     else:
         return Ether() / IP(src=SOURCE_IP,
                             dst=DEST_IP) / UDP() / ("*" * 1500)
Exemple #2
0
def main():
    oc = OSC.OSCClient()
    oc.connect(hostport)

    kbints = 0

    interface_address=options.interface_address

    if openfile:
        p = pcapy.open_offline(openfile)
    else:
        # begin listening to network traffic
        interface = options.interface
        interface_address = netifaces.ifaddresses(interface)[2][0]['addr']

        p = pcapy.open_live(interface, 1024, False, 10240)

    # create and start threads
    network_traffic = communication_thread()
    network_traffic.start()


    try:
        (header, payload) = p.next()
        while header:
            e = Ether(payload)
            t = e.getlayer(TCP)
            if t:
                i = e.getlayer(IP)
                nw_traffic_global.setdefault(t.dport,0)
                try:
                    nw_traffic_global[t.dport]+=1
                except KeyError:
                    print 'race'
                nw_traffic_inout['in' if i.dst == interface_address else 'out']+=1
                    
            if e.haslayer(ICMP):
                x = OSC.OSCMessage()
                x.setAddress('/plinker/ping')
                x.append(1)
                oc.send(x)
                print 'ICMP ping sent'

            second = header.getts()[0] # [1] = miliseconds
            
            try:
                (header, payload) = p.next()
            except Exception,e:
                pass
                #print type(e)
    except Exception,e:
        print traceback.print_exc(e)
    def start(self, args: dict) -> None:

        pkt = Ether(dst=DEST_MAC) / IP() / TCP() / ("*" * 1500)
        # Create a traffic stream
        stream = STLStream(packet=STLPktBuilder(pkt=pkt, vm=[]),
                           mode=STLTXCont())
        self.client.add_streams(stream, ports=[0])

        logging.info(
            "Starting traffic, duration: %d sec",
            args.duration,
        )

        # Start sending traffic
        self.client.start(SENDER_PORT, mult="100%", duration=args.duration)

        logging.info("Waiting until all traffic stop")
        self.client.wait_on_traffic(ports=SENDER_PORT)

        # Get statistics for TX and RX ports
        stats = self.client.get_stats()
        rx_rate_mbps = stats[1]["rx_bps"] / (10**6)
        assert (SHAPING_RATE_MBPS * 0.95 < rx_rate_mbps < SHAPING_RATE_MBPS
                ), "The measured RX rate is not close to the port shaping rate"

        readable_stats_0 = get_readable_port_stats(stats[0])
        readable_stats_1 = get_readable_port_stats(stats[1])

        print("\n Statistics for TX port: \n")
        print(readable_stats_0)

        print("\n Statistics for RX port: \n")
        print(readable_stats_1)
Exemple #4
0
def main():
    kbints = 0

    # begin listening to network traffic
    interface = options.interface
    interface_address = netifaces.ifaddresses(interface)[2][0]['addr']

    # create and start threads
    network_traffic = communication_thread("no_icmp")
    network_traffic.start()
    icmp_traffic = communication_thread("only_icmp")
    icmp_traffic.start()

    p = pcapy.open_live(interface, 1024, False, 10240)

    try:
        (header, payload) = p.next()
        while header:
            e = Ether(payload)
            t = e.getlayer(TCP)
            if t:
                i = e.getlayer(IP)
                if i.dst==interface_address:
                    nw_traffic_in_global.setdefault(t.dport,0)
                    nw_traffic_in_global[t.dport]+=1
                else:
                    nw_traffic_out_global.setdefault(t.dport,0)
                    nw_traffic_out_global[t.dport]+=1
                    
            if e.haslayer(ICMP):
                x = OSC.OSCMessage()
                x.setAddress('/plinker/ping')
                x.append(1)
                oc.send(x)
                print 'sent'

            second = header.getts()[0] # [1] = miliseconds
            (header, payload) = p.next()
    except KeyboardInterrupt:
        print 'kbint %d' % kbints
        kbints+=1
        if kbints>2:
            print 'quitting %d' % kbints
            return
    except Exception,e:
        print e
Exemple #5
0
 def run_ping_checks_scapy(target, ret, checks, interval, timeout, source,
                           timestamp, group, alert, **kwargs):
     check_result = {
         "success": 0,
         "checks": checks,
         "rtt": [],
         "comment": "",
         "target": target,
         "check_type": "PING",
         "source": source,  # add minion id
         "@timestamp": timestamp,
         "group": group,
     }
     # try to resolve target name to IP:
     try:
         target_address = socket.gethostbyname(target)
     except socket.gaierror:
         check_result[
             "comment"] += "ERROR, PING connection check, DNS resolution failed for target - {}".format(
                 target)
         ret["out"].append(check_result)
         return
     # do ICMP checks
     for i in range(checks):
         try:
             packet = Ether() / IP(dst=target_address) / ICMP()
             ans, unans = srp(packet,
                              filter="icmp",
                              verbose=0,
                              timeout=timeout)
             if len(ans) != 0:
                 rx = ans[0][1]
                 tx = ans[0][0]
                 check_result["rtt"].append(abs(rx.time - tx.sent_time))
                 check_result["success"] += 1
             elif len(unans) != 0:
                 check_result[
                     "comment"] += "Check {}, ERROR, no ICMP reply, timeout - {}s, target - {}, address - {}\n".format(
                         i, timeout, target, target_address)
         except:
             exc_type, exc_value, exc_traceback = sys.exc_info()
             check_result[
                 "comment"] += "Check {}, ERROR: Unhandled scapy error, target - {}, target_address - {}\n\n{}\n".format(
                     i,
                     target,
                     target_address,
                     "".join(
                         traceback.format_exception(exc_type, exc_value,
                                                    exc_traceback)),
                 )
         time.sleep(interval)
     # add check stats
     check_result = _calculate_stats(check_result)
     # sent alert on failure if requested to do so
     if check_result["success"] == 0 and alert is True:
         _send_alert(check_type="PING", target=target, data=check_result)
     # save thread run results
     ret["out"].append(check_result)
Exemple #6
0
def encrypt_pkt(key, pkt):
    key_ary = [0, 0, 0, 0]
    for i in range(4):
        key_ary[i] = (key >> (24 - i * 8)) & 0xff

    # Identify the packet type and break up the packet as appropriate
    str_pkt = str(pkt)
    str_hdr = str_pkt[:START_POS]
    load = str_pkt[START_POS:]
    str_load = ''
    for i in range(len(str_pkt) - START_POS):
        str_load += chr(ord(load[i]) ^ key_ary[(i + START_POS) % 4])
    ret_pkt = Ether(str_hdr + str_load)
    return ret_pkt
Exemple #7
0
def process(pkt):
    global records,sampling_rate,buffer_count,records_in_buffer,packet_count_for_sampling,current_iface, total_packets_captured
    ifIn = 100
    ifOut = 200
    pkt=Ether(pkt)
    if pkt.haslayer(DNSQR) and UDP in pkt and pkt[UDP].sport == 53:
        for i in range(0, pkt[DNS].ancount):
            name = pkt[DNS].an[i].rrname
            solved = pkt[DNS].an[i].rdata
            tpe = pkt[DNS].an[i].type
            now = datetime.now()
            data = {'Domain': name, 'IP': solved, 'Type': tpe, 'occurrence': 1, 'Last_seen': datetime.now()}
    packet_count_for_sampling+=1
    if packet_count_for_sampling==sampling_rate:
        if TCP in pkt:
            flgs=pkt[TCP].flags
        else:
            flgs=''
        if pkt[IP].src!=current_iface[0].address:
            ifIn=200
            ifOut=100
        records.append(
            rbnf.NetflowRecordV5( \
                src=pkt[IP].src, dst=pkt[IP].dst, nexthop="192.168.1.1", \
                input=ifIn, output=ifOut, dpkts=1, dOctets=pkt[IP].len, \
                first=1, last=2, srcport=pkt[IP].sport, \
                dstport=pkt[IP].dport, pad1=0, tcpFlags=flgs, \
                prot=pkt[IP].proto , tos=0x00, src_as=0, dst_as=0, \
                src_mask=0, dst_mask=0, pad2=0),
        )
        records_in_buffer+=1
        if records_in_buffer==int(buffer_count):
            send_to_collector(records)
            records_in_buffer=0
            records=[]
        packet_count_for_sampling=0
    total_packets_captured += 1
Exemple #8
0
    def resolve_mac(self, timeout=None, retries=None):
        if timeout is None:
            timeout = self.arp_timeout
        if retries is None:
            retries = self.arp_retries

        # TODO: randomize source
        resp = srp1(
            Ether() / ARP(pdst=str(self.ip)),
            retry=retries,
            timeout=timeout,
            iface=conf.iface,
        )
        if resp is None:
            raise AddressNotResolvedError(
                'failed to resolve {}'.format(self.ip)
            )
        else:
            self.mac = MAC(resp[ARP].hwsrc)
    def start(self, args) -> None:
        pkt = (
            Ether(src=SOURCE_MAC, dst=DEST_MAC)
            / IP(src=SOURCE_IP, dst=DEST_IP)
            / UDP()
            / ("*" * 1500)
        )

        stream = STLStream(packet=STLPktBuilder(pkt=pkt, vm=[]), mode=STLTXCont())

        logging.info("Setting up ports")
        self.client.add_streams(stream, ports=SENDER_PORTS)

        pkt_capture_limit = args.duration * 3
        logging.info(
            "Start capturing first %s RX packet from INT collector", pkt_capture_limit
        )
        self.client.set_service_mode(ports=INT_COLLECTPR_PORTS, enabled=True)
        capture = self.client.start_capture(
            rx_ports=INT_COLLECTPR_PORTS,
            limit=pkt_capture_limit,
            bpf_filter="udp and dst port 32766",
        )

        logging.info(
            "Starting traffic, duration: %ds, throughput: 100%%", args.duration
        )
        self.client.start(ports=SENDER_PORTS, mult="100%", duration=args.duration)
        logging.info("Waiting until all traffic stop")
        self.client.wait_on_traffic(ports=SENDER_PORTS)

        logging.info("Stop capturing packet from INT collector port")
        output = "/tmp/congestion-report-{}.pcap".format(
            datetime.now().strftime("%Y%m%d-%H%M%S")
        )
        self.client.stop_capture(capture["id"], output)
        analysis_report_pcap(output)
        list_port_status(self.client.get_stats())
Exemple #10
0
    def start(self, args: dict) -> None:

        # create packets
        pkt1 = Ether(dst=DEST_MAC) / IP(src="16.0.0.1", dst="48.0.0.1") / UDP(
            dport=12, sport=1025) / ("*" * 1500)
        pkt2 = Ether(dst=DEST_MAC) / IP(src="16.0.0.2", dst="48.0.0.2") / UDP(
            dport=12, sport=1025) / ("*" * 1500)
        pkt3 = Ether(dst=DEST_MAC) / IP(src="16.0.0.3", dst="48.0.0.3") / UDP(
            dport=12, sport=1025) / ("*" * 1500)

        #stream list
        streams = []

        # Create a traffic stream
        # assume s1 is a delay critical stream with QoS
        s1 = STLStream(packet=STLPktBuilder(pkt=pkt1),
                       mode=STLTXCont(percentage=1),
                       flow_stats=STLFlowLatencyStats(pg_id=1))
        # assume s2 is a delay critical stream without QoS
        s2 = STLStream(packet=STLPktBuilder(pkt=pkt2),
                       mode=STLTXCont(percentage=1),
                       flow_stats=STLFlowLatencyStats(pg_id=2))
        # assume s3 is a lower priority stream
        s3 = STLStream(packet=STLPktBuilder(pkt=pkt3),
                       mode=STLTXCont(percentage=98),
                       flow_stats=STLFlowLatencyStats(pg_id=3))

        # prepare ports
        self.client.reset(ports=[0, 1])

        # add sterams
        streams.append(s1)
        streams.append(s2)
        streams.append(s3)
        self.client.add_streams(streams, ports=[0])

        logging.info(
            "Starting traffic, duration: %d sec",
            args.duration,
        )

        # Start sending traffic
        self.client.start(SENDER_PORT, mult="100%", duration=args.duration)
        pgids = self.client.get_active_pgids()

        logging.info("Waiting until all traffic stop")
        self.client.wait_on_traffic(ports=SENDER_PORT)

        # stats for pg_id 1 and 2
        stats = self.client.get_pgid_stats(pgids['latency'])
        flow_stats_1 = stats['flow_stats'].get(1)
        flow_stats_2 = stats['flow_stats'].get(2)
        global_lat_stats = stats['latency']
        lat_stats_1 = global_lat_stats.get(1)
        lat_stats_2 = global_lat_stats.get(2)

        tx_pkts_1 = flow_stats_1['tx_pkts'].get(0, 0)
        rx_pkts_1 = flow_stats_1['rx_pkts'].get(1, 0)
        drops_1 = lat_stats_1['err_cntrs']['dropped']

        tx_pkts_2 = flow_stats_2['tx_pkts'].get(0, 0)
        rx_pkts_2 = flow_stats_2['rx_pkts'].get(1, 0)
        drops_2 = lat_stats_2['err_cntrs']['dropped']

        print(
            " \n TX and RX flow stats and packets dropped for s1 (i.e., delay critical): "
        )
        print("  tx packets: {0}".format(tx_pkts_1))
        print("  tx bytes : {0}".format(tx_pps_1))
        print("  rx packets : {0}".format(rx_pkts_1))
        print("  drops: {0}".format(drops_1))

        print(
            " \n TX and RX flow stats and packets dropped for s2 (i.e., delay critical): "
        )
        print("  tx packets: {0}".format(tx_pkts_2))
        print("  tx bytes : {0}".format(tx_pps_2))
        print("  rx packets : {0}".format(rx_pkts_2))
        print("  drops: {0}".format(drops_2))

        # latency info for s1
        lat_1 = lat_stats_1['latency']
        avg_1 = lat_1['average']
        tot_max_1 = lat_1['total_max']
        tot_min_1 = lat_1['total_min']

        # latency info for s2
        lat_2 = lat_stats_2['latency']
        avg_2 = lat_2['average']
        tot_max_2 = lat_2['total_max']
        tot_min_2 = lat_2['total_min']

        print('\n Latency info for s1 (ie., delay critical with QoS):')
        print("  Maximum latency(usec): {0}".format(tot_max_1))
        print("  Minimum latency(usec): {0}".format(tot_min_1))
        print("  Average latency(usec): {0}".format(avg_1))

        print('\n Latency info for s2 (ie., delay critical without QoS):')
        print("  Maximum latency(usec): {0}".format(tot_max_2))
        print("  Minimum latency(usec): {0}".format(tot_min_2))
        print("  Average latency(usec): {0}".format(avg_2))

        # max latency difference between delay critcal streams s1 and s2
        dc_max_lat_diff = tot_max_2 - tot_max_1

        assert ((LATENCY_LP_MAX_USEC - LATENCY_DC_MAX_USEC) <= dc_max_lat_diff), \
        "Priority scheduling test failed."

        # Get statistics for TX and RX ports
        stats = self.client.get_stats()
        readable_stats_0 = get_readable_port_stats(stats[0])
        readable_stats_1 = get_readable_port_stats(stats[1])

        logging.info("Priority scheduling test successfully executed.")
        print("\n Overall Statistics for TX port: \n")
        print(readable_stats_0)
        print("\n Overall Statistics for RX port: \n")
        print(readable_stats_1)
Exemple #11
0
import OSC            # pyOSC

interface = 'wlan0'
interface_address = netifaces.ifaddresses(interface)[2][0]['addr']
print interface_address

p = pcapy.open_live(interface, 1024, False, 10240)
#p = pcapy.open_offline('test.tcpdump')

summary_in = {}
summary_out = {}

try:
    (header, payload) = p.next()
    while header:
        e = Ether(payload)
        t = e.getlayer(TCP)
        if t:
            i = e.getlayer(IP)
            if i.dst==interface_address:
                summary_in.setdefault(t.dport,0)
                summary_in[t.dport]+=1
            else:
                summary_out.setdefault(t.dport,0)
                summary_out[t.dport]+=1

        if e.haslayer(ICMP):
            print 'ping'

        second = header.getts()[0] # [1] = miliseconds
        (header, payload) = p.next()
Exemple #12
0
def axis_load(f, period):
    """
    Loads packets from an AXI Stream-grammar formatted text file as a list of
    Scapy packet instances.  The following extra attributes are added to each
    instance:
        .tuser          raw contents of TUSER, stored as array of 128-bit ints
        .tuser_len      packet length (from TUSER)
        .tuser_sport    source port (one-hot, from TUSER)
        .tuser_dport    dest port (one-hot, from TUSER)
    """
    def as_bytes(x):
        """
        Splits hex string X into list of bytes.
        """
        return [int(x[i:i + 2], 16) for i in range(0, len(x), 2)]

    bus_width = None
    time = 0
    pkt_data = []
    tuser = []
    pkts = []
    for lno, line in enumerate(f):
        lno += 1
        try:
            # Look to see if a comment is present.  If not, index() will throw
            # an exception, and we skip this section.
            hash_index = line.index('#')
        except ValueError:
            pass
        else:
            line = line[:hash_index]
        line = line.strip()
        if not line:
            continue

        # Handle delay specs
        if line[0] == '@':
            time = int(line[1:]) / 1e9
        elif line[0] == '+':
            time += int(line[1:]) / 1e9
        elif line[0] == '*':
            time += period * int(line[1:])
        else:  # treat as data
            terminal = line[-1]
            line = line[:-1]
            if terminal not in [',', '.']:
                raise BadAXIDataException(f.name, lno,
                                          'unknown terminal %s' % terminal)
            line = [x.strip() for x in line.split(',')]
            if len(line) != 3:
                raise BadAXIDataException(
                    f.name, lno,
                    'invalid data (expected 3 fields, got %d)' % len(line))

            # handle start of packet
            if not pkt_data:
                SoP_time = time
            if bus_width is None:
                bus_width = len(line[0]) * 4
                if math.log(bus_width, 2) - int(math.log(bus_width, 2)) != 0:
                    print '%s: data bus not a power of two in width' % f.name
            # accumulate packet and TUSER data
            pkt_data += reversed(as_bytes(line[0].zfill(bus_width / 4)))
            tuser.append(int(line[2], 16))
            # handle end of packet
            if terminal == '.':
                valid_bytes = int(math.log(int(line[1], 16) + 1, 2))
                if valid_bytes < bus_width / 8:  # trim off any padding
                    del pkt_data[valid_bytes - bus_width / 8:]
                pkts.append(Ether(''.join([chr(x) for x in pkt_data])))
                pkts[-1].time = SoP_time
                pkts[-1].tuser = tuser
                pkts[-1].tuser_len = tuser[0] & 0xffff
                pkts[-1].tuser_sport = (tuser[0] >> 16) & 0xff
                pkts[-1].tuser_dport = (tuser[0] >> 24) & 0xff
                pkt_data = []
                tuser = []
                if len(pkts[-1]) != pkts[-1].tuser_len:
                    print '%s: %d: #%d: warning: meta length (%d) disagrees with actual length (%d)' % (
                        f.name, lno, len(pkts), meta_len, len(pkts[-1]))
            time += period
    return pkts
Exemple #13
0
nftest_init(sim_loop=['nf0', 'nf1'], hw_config=[phy0loop4])
nftest_start()

# set parameters
DA = "11:11:11:11:11:11"
SA = "22:22:22:22:22:22"
TTL = 64
DST_IP = "192.168.1.1"
SRC_IP = "192.168.0.1"
nextHopMAC = "dd:55:dd:66:dd:77"
NUM_PKTS = 1
pkt = [[], [], [], [], [], [], [], [], [], []]

pkt[0] = (
    Ether(src='dd:bb:cc:dd:ee:ff', dst='00:ca:fe:00:dd:01') /
    "000000000000000000000000000000000000D8CAECE0BDF40A12540D0A4296A472C2412199493F11CF353EACA4D302F4311E"
    .decode("hex"))
pkt[1] = (
    Ether(src='dd:bb:cc:dd:ee:ff', dst='00:ca:fe:00:dd:01') /
    "000000000000000000000000000000000000bd8cc040d202c864782b698f271acfa357d652f18793422411ac8704c93b9ebd"
    .decode("hex"))
pkt[2] = (
    Ether(src='dd:bb:cc:dd:ee:ff', dst='00:ca:fe:00:dd:01') /
    "000000000000000000000000000000000000a9dbeeb9c28e60bb3fee809b9187522976e74969209f5bb87e7e76d60272baca"
    .decode("hex"))
pkt[3] = (
    Ether(src='dd:bb:cc:dd:ee:ff', dst='00:ca:fe:00:dd:01') /
    "0000000000000000000000000000000000000508b1780821fe4dd8e9ab281d4853c5969f6de07d7aaa56bbff1a2b5f173131"
    .decode("hex"))
pkt[4] = (
Exemple #14
0
#

import sys
sys.path.append('../../../../../../tools/scripts')

# NB: axitools import must preceed any scapy imports
import axitools

from scapy.layers.all import Ether, IP, TCP

pkts = []
f0 = open("stream_data_in_0.axi", "w")
f1 = open("stream_data_in_1.axi", "w")
f2 = open("stream_data_in_2.axi", "w")
f3 = open("stream_data_in_3.axi", "w")
f4 = open("stream_data_in_4.axi", "w")

# A simple TCP/IP packet embedded in an Ethernet II frame
for i in range(0, 10):
    pkt = (Ether(src='f0:0d:f0:0d:f0:0d', dst='ba:be:ba:be:ba:be') /
           IP(src='204.204.204.204', dst='221.221.221.221') /
           TCP(sport=51996, dport=80) / "GET /newyorker.com.abdcldkj")
    pkt.time = i * (1e-8)
    pkts.append(pkt)

# Write out to console
axitools.axis_dump(pkts, f0, 64, 1e-9)
axitools.axis_dump(pkts, f1, 64, 1e-9)
axitools.axis_dump(pkts, f2, 64, 1e-9)
axitools.axis_dump(pkts, f3, 64, 1e-9)
axitools.axis_dump(pkts, f4, 64, 1e-9)
Exemple #15
0
if isHW():
    mres.append(nftest_regread_expect(SUME_ARP_CRYPTO_0_DATA0(), size))
else:
    nftest_regread_expect(SUME_ARP_CRYPTO_0_DATA0(), size) 

#nftest_barrier()

num_broadcast = 0


## send transperent arp packets
pkts = []
expected_pkts = []
for i in range(size / (1500 - 64) + 1):
    DA = "ff:ff:ff:ff:ff:ff"
    pkt = Ether(src = SA, dst = DA) / ARP(op = 'who-has', psrc = SIP, pdst = DIP, hwsrc = SA, hwdst = HWDST)
    #pkt = Ether(src = SA, dst = DA) 

    if not isHW():
        pkt.tuser_sport = 32
    pkts.append(pkt)
    expected_pkts.append(pkt)

    for i in range(size / (1500 - 64) + 1):
        for pkt in pkts:
            pkt.time = i*(1e-8) + (1e-6)

if isHW():
    for i in xrange(len(pkts)):
        nftest_send_phy('nf0', pkts[i], False)
        nftest_expect_phy('nf0', expected_pkts[i], '\x00' * 42)
Exemple #16
0
        	nftest_send_dma('nf' + str(port), pkt)
        	nftest_expect_dma('nf' + str(port), pkt)

	print ""

	nftest_finish()
else:
	no_pkts = 8
	pkts=[]
	# A simple TCP/IP packet embedded in an Ethernet II frame	
	for i in range(no_pkts):
    	    g = 10 # min payload length
	    payload = ''
	    for x in range(g):
		payload = payload + 'A'
    	    	pkt = (Ether(src='aa:bb:cc:dd:ee:ff', dst='77:88:99:aa:bb:cc')/
           	      IP(src='192.168.0.1', dst='192.168.1.1')/
           	      TCP()/
		      payload)    	    
	    pkt.time = i*(1e-8)
       	    # Set source network interface for DMA stream
    	    pkt.tuser_sport = 1 << (i%4*2 + 1) # PCI ports are odd-numbered
    	    pkts.append(pkt)

	# PCI interface
	with open( os.path.join( script_dir, 'dma_0_stim.axi' ), 'w' ) as f:
    	    axitools.axis_dump( pkts, f, 256, 1e-9 )
	with open( os.path.join( script_dir, 'dma_0_expected.axi' ), 'w' ) as f:
    	    axitools.axis_dump( pkts*4, f, 256, 1e-9 )

	# 10g interfaces
Exemple #17
0
    fix_checksum_sum = sum(bytearray(fix_checksum_string)) % 256
    str_fix = str(fix_checksum_sum)

    bcd_fix_checksum = ''

    if fix_checksum_sum >= 100:
        bcd_fix_checksum = str_fix[0] + str_fix[1] + str_fix[2]
    elif fix_checksum_sum < 100 and fix_checksum_sum >= 10:
        bcd_fix_checksum = '0' + str_fix[0] + str_fix[1]
    elif fix_checksum_sum < 10:
        bcd_fix_checksum = '0' + '0' + str_fix[0]

    bcd_fix_checksum = '10=' + bcd_fix_checksum + '\x01'

    pkt = (Ether(src=src_mac_addr, dst=dst_mac_addr) /
           IP(src=src_ip_addr, dst=dst_ip_addr) /
           TCP(sport=ip_sport_no,
               dport=ip_dport_no,
               flags="PA",
               options=[('NOP', None), ('NOP', None),
                        ('Timestamp', (34498433, 3150184448))]) /
           fix_header_data / fix_body_length_final / fix_Msg_Type /
           fix_seq_num / fix_sendCom_ID / fix_sending_time_data /
           fix_Target_ID / fix_ClOrd_ID / fix_order_ID / fix_account /
           fix_symbol / fix_Ord_Type / fix_order_Qty / fix_order_side /
           fix_order_price / fix_timeInForce / fix_transactTime /
           fix_TwseIvacnoFlag / fix_TwseOrdType / fix_TwseExCode /
           fix_TwseRejStaleOrd / bcd_fix_checksum)
    pkts_tcp.append(pkt)
Exemple #18
0
magic = pack('<L', 0xa5a5a5a5)

for i in xrange(4):
    nftest_regwrite(addrs[i](), data[i])
    if isHW():
        mres.append(nftest_regread_expect(addrs[i](), data[i]))
    else:
        nftest_regread_expect(addrs[i](), data[i]) 

nftest_barrier()

pkts = []
expected_pkts = []
pkta = []
for i in range(num_broadcast):
    pkt = Ether(src = SA, dst = DA) / ARP(op = 'who-has', psrc = SIP, pdst = DIP, hwsrc = SA, hwdst = HWDST)

    pkt.tuser_sport = 1
    pkts.append(pkt)
    expected_pkts.append(pkt / Raw(load = magic + key))

    for i in range(num_broadcast):
        for pkt in pkts:
            pkt.time = i*(1e-8) + (1e-6)

    if isHW():
        nftest_expect_phy('nf1', pkt / Raw(load = magic + key))
        nftest_send_phy('nf0', pkt)
    
if not isHW():
    nftest_send_phy('nf0', pkts)
Exemple #19
0
def extract_ip_from_gse_data(raw_data,
                             high_reliability=True,
                             tcp_hijack=False,
                             tcp_hijack_ips=[None, None]):
    ip_packet = None
    simple_packet = None
    try:
        ip_packet = Ipv4Packet.from_bytes(raw_data)
    except EOFError:
        # if there's just not enough bytes, we can try adding a small number of padding bytes to see if it makes for a mostly recovered packet
        # we'll try to recover up to 3x the length of the original packet
        try:
            raw_data = raw_data + (3 * len(raw_data)) * b"\x00"
            ip_packet = Ipv4Packet.from_bytes(raw_data)
        except:
            counters['non_ip_or_corrupt_gse'] += 1
    except ValueError:
        # we can try and force a typical first two bytes of an IPV4 header to bully GSExtract into making a packet
        # this runs the risk of invalid IP headers but catches some packets when there are undocument proprietary GSE extensions
        if not high_reliability:
            try:
                raw_data = b"\x45" + raw_data + (3 * len(raw_data)) * b"\x00"
                ip_packet = Ipv4Packet.from_bytes(raw_data)
            except:
                try:
                    raw_data = b"\x45\x00" + raw_data[1:] + (
                        3 * len(raw_data)) * b"\x00"
                    ip_packet = Ipv4Packet.from_bytes(raw_data)
                except:
                    pass
        counters['non_ip_or_corrupt_gse'] += 1
    except:
        pass
    if ip_packet is not None:
        seconds_time = time.time()
        dt = datetime.now()
        simple_packet = (int(seconds_time), dt.microsecond, len(raw_data),
                         len(raw_data), raw_data)

        # This is a very simple example of TCP hijacking
        # You would need to pass both a target and destination IP address through to the parent function
        # This is not implemented in the command-line tool but the modifications should be straightforward
        if tcp_hijack and (ip_packet.src_ip_addr == tcp_hijack_ips[0]
                           or ip_packet.dst_ip_addr == tcp_hijack_ips[0]) and (
                               ip_packet.src_ip_addr == tcp_hijack_ips[1]
                               or ip_packet.dst_ip_addr == tcp_hijack_ips[1]):
            html = "<b>Hijacked TCP Session</b>"
            p = IP(raw_data)
            if "TCP" in p:
                F = p[TCP].flags
                forgery_ip = IP(src=p[IP].dst, dst=p[IP].src)
                response = "HTTP/1.1 200 OK\n"
                response += "Server: MyServer\n"
                response += "Content-Type: text/html\n"
                response += "Content-Length: " + str(len(html)) + "\n"
                response += "Connection: close"
                response += "\n\n"
                response += html
                if F & SYN and not F & ACK:
                    forgery_tcp = TCP(sport=p[TCP].dport,
                                      dport=p[TCP].sport,
                                      seq=123,
                                      ack=p[TCP].seq + 1,
                                      flags="AS")
                    forgery = Ether() / forgery_ip / forgery_tcp / response
                    sendp(forgery)
                elif F & ACK and F & PSH:
                    forgery_tcp = TCP(sport=p[TCP].dport,
                                      dport=p[TCP].sport,
                                      seq=p[TCP].ack + 1,
                                      ack=p[TCP].seq,
                                      flags="PA",
                                      options=p[TCP].options)
                    forgery = Ether() / forgery_ip / forgery_tcp / response
                    sendp(forgery)
                    forgery.show()
        counters['ip_recovered'] += 1
    return simple_packet
Exemple #20
0
import crypto_axitools

from scapy.layers.all import Ether, IP, TCP

parser=OptionParser()

parser.add_option("-k","--key",dest="key",help="Encryption key")
(options,args)=parser.parse_args()


key=int(options.key,16)

pkts=[]
# A simple TCP/IP packet embedded in an Ethernet II frame
for i in range(1):
    pkt = (Ether(src='11:22:33:44:55:66', dst='77:88:99:aa:bb:cc')/
           IP(src='192.168.1.1', dst='192.168.1.2')/
#           TCP()/  #TCP is not used in this design
           'Hello, NetFPGA-10G!')
    pkt.time        = 2e-6+i*(1e-8) #give enough time for register configuration
    # Set source network interface for DMA stream
    pkt.tuser_sport = 1 << (i%4*2 + 1) # PCI ports are odd-numbered
    pkts.append(pkt)

save_payload=pkts[0].payload.payload
# PCI interface
with open( os.path.join( script_dir, 'dma_0_stim.axi' ), 'w' ) as f:
    axitools.axis_dump( pkts, f, 256, 1e-9 )
with open( os.path.join( script_dir, 'dma_0_expected.axi' ), 'w' ) as f:
    for i in range(1):
       for pkt in pkts:
Exemple #21
0
magic = pack('<L', 0xa5a5a5a5)

for i in xrange(4):
    nftest_regwrite(addrs[i](), data[i])
    if isHW():
        mres.append(nftest_regread_expect(addrs[i](), data[i]))
    else:
        nftest_regread_expect(addrs[i](), data[i])

nftest_barrier()

pkts = []
expected_pkts = []
pkta = []
for i in range(num_broadcast):
    pkt = Ether(src=SA, dst=DA) / ARP(
        op='who-has', psrc=SIP, pdst=DIP, hwsrc=SA, hwdst=HWDST)

    pkt.tuser_sport = 1
    pkts.append(pkt)
    expected_pkts.append(pkt / Raw(load=magic + key))

    for i in range(num_broadcast):
        for pkt in pkts:
            pkt.time = i * (1e-8) + (1e-6)

    if isHW():
        nftest_expect_phy('nf1', pkt / Raw(load=magic + key))
        nftest_send_phy('nf0', pkt)

if not isHW():