Beispiel #1
0
    def __init__(self, *args, **kwargs):
        super(DPIController, self).__init__(*args, **kwargs)
        self.tbl_num = self._service_manager.get_table_num(self.APP_NAME)
        self.next_table = self._service_manager.get_next_table_num(
            self.APP_NAME)
        self.setup_type = kwargs['config']['setup_type']
        self._datapath = None
        self._dpi_enabled = kwargs['config']['dpi']['enabled']
        self._mon_port = kwargs['config']['dpi']['mon_port']
        self._mon_port_number = kwargs['config']['dpi']['mon_port_number']
        self._idle_timeout = kwargs['config']['dpi']['idle_timeout']
        self._bridge_name = kwargs['config']['bridge_name']
        self._app_set_tbl_num = self._service_manager.INTERNAL_APP_SET_TABLE_NUM
        self._imsi_set_tbl_num = \
            self._service_manager.INTERNAL_IMSI_SET_TABLE_NUM
        if self._dpi_enabled:
            self._create_monitor_port()

        tcp_pkt = packet.Packet()
        tcp_pkt.add_protocol(
            ethernet.ethernet(ethertype=ether_types.ETH_TYPE_IP))
        tcp_pkt.add_protocol(ipv4.ipv4(proto=6))
        tcp_pkt.add_protocol(tcp.tcp())
        tcp_pkt.serialize()
        self.tcp_pkt_data = tcp_pkt.data
        udp_pkt = packet.Packet()
        udp_pkt.add_protocol(
            ethernet.ethernet(ethertype=ether_types.ETH_TYPE_IP))
        udp_pkt.add_protocol(ipv4.ipv4(proto=17))
        udp_pkt.add_protocol(udp.udp())
        udp_pkt.serialize()
        self.udp_pkt_data = udp_pkt.data
Beispiel #2
0
    def test_default_args(self):
        prev = ipv4(proto=inet.IPPROTO_IGMP)
        g = igmpv3_report()
        prev.serialize(g, None)
        buf = g.serialize(bytearray(), prev)
        res = unpack_from(igmpv3_report._PACK_STR, six.binary_type(buf))
        buf = bytearray(buf)
        pack_into('!H', buf, 2, 0)

        eq_(res[0], IGMP_TYPE_REPORT_V3)
        eq_(res[1], checksum(buf))
        eq_(res[2], 0)

        # records without record_num
        prev = ipv4(proto=inet.IPPROTO_IGMP)
        record1 = igmpv3_report_group(MODE_IS_INCLUDE, 0, 0, '225.0.0.1')
        record2 = igmpv3_report_group(MODE_IS_INCLUDE, 0, 2, '225.0.0.2',
                                      ['172.16.10.10', '172.16.10.27'])
        record3 = igmpv3_report_group(MODE_IS_INCLUDE, 1, 0, '225.0.0.3', [],
                                      b'abc\x00')
        record4 = igmpv3_report_group(MODE_IS_INCLUDE, 1, 2, '225.0.0.4',
                                      ['172.16.10.10', '172.16.10.27'],
                                      b'abc\x00')
        records = [record1, record2, record3, record4]
        g = igmpv3_report(records=records)
        prev.serialize(g, None)
        buf = g.serialize(bytearray(), prev)
        res = unpack_from(igmpv3_report._PACK_STR, six.binary_type(buf))
        buf = bytearray(buf)
        pack_into('!H', buf, 2, 0)

        eq_(res[0], IGMP_TYPE_REPORT_V3)
        eq_(res[1], checksum(buf))
        eq_(res[2], len(records))
Beispiel #3
0
    def test_default_args(self):
        prev = ipv4(proto=inet.IPPROTO_IGMP)
        g = igmpv3_report()
        prev.serialize(g, None)
        buf = g.serialize(bytearray(), prev)
        res = unpack_from(igmpv3_report._PACK_STR, six.binary_type(buf))
        buf = bytearray(buf)
        pack_into("!H", buf, 2, 0)

        eq_(res[0], IGMP_TYPE_REPORT_V3)
        eq_(res[1], checksum(buf))
        eq_(res[2], 0)

        # records without record_num
        prev = ipv4(proto=inet.IPPROTO_IGMP)
        record1 = igmpv3_report_group(MODE_IS_INCLUDE, 0, 0, "225.0.0.1")
        record2 = igmpv3_report_group(MODE_IS_INCLUDE, 0, 2, "225.0.0.2", ["172.16.10.10", "172.16.10.27"])
        record3 = igmpv3_report_group(MODE_IS_INCLUDE, 1, 0, "225.0.0.3", [], b"abc\x00")
        record4 = igmpv3_report_group(MODE_IS_INCLUDE, 1, 2, "225.0.0.4", ["172.16.10.10", "172.16.10.27"], b"abc\x00")
        records = [record1, record2, record3, record4]
        g = igmpv3_report(records=records)
        prev.serialize(g, None)
        buf = g.serialize(bytearray(), prev)
        res = unpack_from(igmpv3_report._PACK_STR, six.binary_type(buf))
        buf = bytearray(buf)
        pack_into("!H", buf, 2, 0)

        eq_(res[0], IGMP_TYPE_REPORT_V3)
        eq_(res[1], checksum(buf))
        eq_(res[2], len(records))
Beispiel #4
0
def build_pkt(pkt):
    layers = []
    if 'arp_target_ip' in pkt:
        ethertype = 0x806
        layers.append(arp.arp(dst_ip=pkt['arp_target_ip']))
    elif 'ipv6_src' in pkt:
        ethertype = 0x86DD
        layers.append(ipv6.ipv6(src=pkt['ipv6_src'], dst=pkt['ipv6_src']))
    else:
        ethertype = 0x800
        if 'ipv4_src' in pkt:
            net = ipv4.ipv4(src=pkt['ipv4_src'], dst=pkt['ipv4_dst'])
        else:
            net = ipv4.ipv4()
        layers.append(net)
    if 'vid' in pkt:
        tpid = 0x8100
        layers.append(vlan.vlan(vid=pkt['vid'], ethertype=ethertype))
    else:
        tpid = ethertype
    eth = ethernet.ethernet(
        dst=pkt['eth_dst'],
        src=pkt['eth_src'],
        ethertype=tpid)
    layers.append(eth)
    result = packet.Packet()
    for layer in layers:
        result.add_protocol(layer)
    return result
Beispiel #5
0
def build_pkt(pkt):
    layers = []
    if 'arp_target_ip' in pkt:
        ethertype = 0x806
        layers.append(arp.arp(dst_ip=pkt['arp_target_ip']))
    elif 'ipv6_src' in pkt:
        ethertype = 0x86DD
        layers.append(ipv6.ipv6(src=pkt['ipv6_src'], dst=pkt['ipv6_src']))
    else:
        ethertype = 0x800
        if 'ipv4_src' in pkt:
            net = ipv4.ipv4(src=pkt['ipv4_src'], dst=pkt['ipv4_dst'])
        else:
            net = ipv4.ipv4()
        layers.append(net)
    if 'vid' in pkt:
        tpid = 0x8100
        layers.append(vlan.vlan(vid=pkt['vid'], ethertype=ethertype))
    else:
        tpid = ethertype
    eth = ethernet.ethernet(dst=pkt['eth_dst'],
                            src=pkt['eth_src'],
                            ethertype=tpid)
    layers.append(eth)
    result = packet.Packet()
    for layer in layers:
        result.add_protocol(layer)
    return result
Beispiel #6
0
    def _do_leave(self, leave, in_port, msg):
        """the process when the snooper received a LEAVE message."""
        datapath = msg.datapath
        dpid = datapath.id
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        # check whether the querier port has been specified.
        if not self._to_querier.get(dpid):
            self.logger.info("no querier exists.")
            return

        # save this LEAVE message and reset the condition of the port
        # that received this message.
        self._to_hosts.setdefault(dpid, {})
        self._to_hosts[dpid].setdefault(leave.address, {
            'replied': False,
            'leave': None,
            'ports': {}
        })
        self._to_hosts[dpid][leave.address]['leave'] = msg
        self._to_hosts[dpid][leave.address]['ports'][in_port] = {
            'out': False,
            'in': False
        }

        # create a specific query.
        timeout = igmp.LAST_MEMBER_QUERY_INTERVAL
        res_igmp = igmp.igmp(msgtype=igmp.IGMP_TYPE_QUERY,
                             maxresp=timeout * 10,
                             csum=0,
                             address=leave.address)
        res_ipv4 = ipv4.ipv4(total_length=len(ipv4.ipv4()) + len(res_igmp),
                             proto=inet.IPPROTO_IGMP,
                             ttl=1,
                             src=self._to_querier[dpid]['ip'],
                             dst=igmp.MULTICAST_IP_ALL_HOST)
        res_ether = ethernet.ethernet(dst=igmp.MULTICAST_MAC_ALL_HOST,
                                      src=self._to_querier[dpid]['mac'],
                                      ethertype=ether.ETH_TYPE_IP)
        res_pkt = packet.Packet()
        res_pkt.add_protocol(res_ether)
        res_pkt.add_protocol(res_ipv4)
        res_pkt.add_protocol(res_igmp)
        res_pkt.serialize()

        # send a specific query to the host that sent this message.
        actions = [parser.OFPActionOutput(ofproto.OFPP_IN_PORT)]
        self._do_packet_out(datapath, res_pkt.data, in_port, actions)

        # wait for REPORT messages.
        hub.spawn(self._do_timeout_for_leave, timeout, datapath, leave.address,
                  in_port)
Beispiel #7
0
    def _do_leave(self, leave, in_port, msg):
        """the process when the snooper received a LEAVE message."""
        datapath = msg.datapath
        dpid = datapath.id
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        # check whether the querier port has been specified.
        if not self._to_querier.get(dpid):
            self.logger.info("no querier exists.")
            return

        # save this LEAVE message and reset the condition of the port
        # that received this message.
        self._to_hosts.setdefault(dpid, {})
        self._to_hosts[dpid].setdefault(
            leave.address,
            {'replied': False, 'leave': None, 'ports': {}})
        self._to_hosts[dpid][leave.address]['leave'] = msg
        self._to_hosts[dpid][leave.address]['ports'][in_port] = {
            'out': False, 'in': False}

        # create a specific query.
        timeout = igmp.LAST_MEMBER_QUERY_INTERVAL
        res_igmp = igmp.igmp(
            msgtype=igmp.IGMP_TYPE_QUERY,
            maxresp=timeout * 10,
            csum=0,
            address=leave.address)
        res_ipv4 = ipv4.ipv4(
            total_length=len(ipv4.ipv4()) + len(res_igmp),
            proto=inet.IPPROTO_IGMP, ttl=1,
            src=self._to_querier[dpid]['ip'],
            dst=igmp.MULTICAST_IP_ALL_HOST)
        res_ether = ethernet.ethernet(
            dst=igmp.MULTICAST_MAC_ALL_HOST,
            src=self._to_querier[dpid]['mac'],
            ethertype=ether.ETH_TYPE_IP)
        res_pkt = packet.Packet()
        res_pkt.add_protocol(res_ether)
        res_pkt.add_protocol(res_ipv4)
        res_pkt.add_protocol(res_igmp)
        res_pkt.serialize()

        # send a specific query to the host that sent this message.
        actions = [parser.OFPActionOutput(ofproto.OFPP_IN_PORT)]
        self._do_packet_out(datapath, res_pkt.data, in_port, actions)

        # wait for REPORT messages.
        hub.spawn(self._do_timeout_for_leave, timeout, datapath,
                  leave.address, in_port)
Beispiel #8
0
    def match_to_packet(self, match):
        pkt = packet.Packet()
        l2 = ethernet.ethernet(
            dst=match.setdefault('eth_dst', "00:00:00:00:00:02"),
            src=match.setdefault('eth_src', "00:00:00:00:00:01"),
            ethertype=match.setdefault('eth_type', 0x800)
            )
        pkt.add_protocol(l2)
        if 'vlan_vid' in match:
            pkt.get_protocol(ethernet.ethernet).ethertype=0x8100
            vl = vlan.vlan(
                pcp=0,
                cfi=0,
                vid=match['vlan_vid'],
                ethertype=match['eth_type']
                )
            pkt.add_protocol(vl)
        l3 = ipv4.ipv4(
            src=match.setdefault('ipv4_src', "192.168.1.1"),
            dst=match.setdefault('ipv4_dst', "192.168.1.2")
            )
        pkt.add_protocol(l3)
        l4 = tcp.tcp(
            src_port=match.setdefault('tcp_src', 12345),
            dst_port=match.setdefault('tcp_dst', 80)
            )
        pkt.add_protocol(l4)

        pkt.serialize()
        return pkt
Beispiel #9
0
      def send_ls_ack(self,ospf_pkt_ls_up):

           ### if success add 
           i=0
           ack=[]
           print ospf_pkt_ls_up.lsas
           while i < len(ospf_pkt_ls_up.lsas):
              ack.append(ospf_pkt_ls_up.lsas[i].header)
              i+=1
           msg = ospf.OSPFLSAck(router_id=self.router_id,
                             lsa_headers=ack)
           rtr = self.routers
	   datapath = rtr.datapath
	   p = packet.Packet()
           e = ethernet.ethernet(dst = '01:00:5e:00:00:05',src = '00:0c:29:d4:10:d7', ethertype = ether.ETH_TYPE_IP)
	   f = ipv4.ipv4(dst='224.0.0.5',
                     src='172.16.33.191',
                     proto=inet.IPPROTO_OSPF)
	   p.add_protocol(e)
	   p.add_protocol(f)
	   p.add_protocol(msg)
	   p.serialize()
	   actions = [datapath.ofproto_parser.OFPActionOutput(1)]
           out = datapath.ofproto_parser.OFPPacketOut(datapath=datapath,
                                  buffer_id=datapath.ofproto.OFP_NO_BUFFER,
                                  in_port=datapath.ofproto.OFPP_CONTROLLER,
                                  actions=actions,
                                  data=p.data) 
           datapath.send_msg(out)

	   dist, previous = self.shortest_path()

	   self.update_fwd_table(dist, previous)
Beispiel #10
0
def build_packet_tcp_22():
    """
    Build an SSH-like packet for use in tests.
    """
    #ethernet(dst='08:00:27:1e:98:88',ethertype=2048,src='00:00:00:00:00:02')
    #ipv4(csum=25158,dst='192.168.57.40',flags=2,header_length=5,
    # identification=58864,offset=0,option=None,proto=6,src='192.168.56.12',
    # tos=0,total_length=60,ttl=64,version=4)
    #tcp(ack=0,bits=2,csum=60347,dst_port=22,offset=10,
    # option='\x02\x04\x05\xb4\x04\x02\x08\n\x00\x08\x16\x0f\x00\x00\x00\x00\
    # x01\x03\x03\x06'
    # ,seq=533918719,src_port=52656,urgent=0,window_size=29200)

    e = ethernet.ethernet(dst='00:00:00:00:00:02',
                      src='00:00:00:00:00:01',
                      ethertype=2048)
    i = ipv4.ipv4(version=4, header_length=5, tos=0, total_length=0, 
                    identification=0, flags=0, offset=0, ttl=255, proto=0, 
                    csum=0, src='10.0.0.1', dst='10.0.0.2', option=None)
    t = tcp.tcp(src_port=52656, dst_port=22, seq=533918719, ack=0, offset=10, 
                      bits=2, window_size=29200, csum=0, urgent=0, option=None)
    p = packet.Packet()
    p.add_protocol(e)
    p.add_protocol(i)
    p.add_protocol(t)
    p.serialize()
    print repr(p.data)  # the on-wire packet
    return p
Beispiel #11
0
    def handle_socket_msg(self):
        pkt_eth = self._pkt.get_protocols(ethernet.ethernet)[0]
        pkt_ip = self._pkt.get_protocols(ipv4.ipv4)[0]
        pkt_udp = self._pkt.get_protocols(udp.udp)[0]
        pkt_dns = DNS(self._pkt[-1])
        print('----------------Sent query with ID', pkt_dns.id, pkt_dns)
        if pkt_udp.dst_port == 53 or pkt_udp.src_port == 53:
            #print 'A DNS query for controller is received'
            if pkt_dns:
                cs = self._controller.get_customers()
                d_mac = cs[0].get_next_hop_mac()
                pkt_dns.qr = 0

                new_pkt = packet.Packet()
                e = ethernet.ethernet(dst=cs[0].get_next_hop_mac(),
                                      src=pkt_eth.src)
                new_pkt.add_protocol(e)
                new_pkt.add_protocol(
                    ipv4.ipv4(src=self._controller.get_ip(),
                              dst=cs[0].get_name_server(),
                              proto=17))
                new_pkt.add_protocol(
                    udp.udp(src_port=pkt_udp.dst_port,
                            dst_port=pkt_udp.src_port))
                new_dns = DNS(rd=0,
                              id=pkt_dns.id,
                              qd=DNSQR(qname=pkt_dns.qd.qname),
                              ns=DNSRR(rrname=pkt_dns.ar.rrname,
                                       type=1,
                                       ttl=60000,
                                       rdata=cs[0].get_name_server()))
                new_pkt.add_protocol(new_dns)
                new_pkt.serialize()
                self.send_dns_packet(new_pkt, cs[0].get_datapath(),
                                     cs[0].get_ingress_port())
    def handle_ip(self, datapath, in_port, pkt):
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        ipv4_pkt = pkt.get_protocol(ipv4.ipv4)  # parse out the IPv4 pkt

        if datapath.id == 1 and ipv4_pkt.proto == inet.IPPROTO_TCP:
            tcp_pkt = pkt.get_protocol(tcp.tcp)  # parser out the TCP pkt
            eth_pkt = pkt.get_protocol(ethernet.ethernet)

            tcp_hd = tcp.tcp(ack=tcp_pkt.seq + 1,
                             src_port=tcp_pkt.dst_port,
                             dst_port=tcp_pkt.src_port,
                             bits=20)
            ip_hd = ipv4.ipv4(dst=ipv4_pkt.src,
                              src=ipv4_pkt.dst,
                              proto=ipv4_pkt.proto)
            ether_hd = ethernet.ethernet(ethertype=ether.ETH_TYPE_IP,
                                         dst=eth_pkt.src,
                                         src=eth_pkt.dst)
            tcp_rst_ack = packet.Packet()
            tcp_rst_ack.add_protocol(ether_hd)
            tcp_rst_ack.add_protocol(ip_hd)
            tcp_rst_ack.add_protocol(tcp_hd)
            tcp_rst_ack.serialize()

            actions = [parser.OFPActionOutput(in_port)]
            out = parser.OFPPacketOut(datapath, ofproto.OFP_NO_BUFFER,
                                      ofproto.OFPP_CONTROLLER, actions,
                                      tcp_rst_ack.data)
            datapath.send_msg(out)
Beispiel #13
0
    def packet_in_handler(self, ev):
        pkt = packet.Packet()

        pkt.add_protocol(ethernet.ethernet(ethertype=0x0800, dst='00:00:00:00:00:02', src='00:00:00:00:00:01'))

        pkt.add_protocol(ipv4.ipv4(dst='10.0.0.2', src='10.0.0.1', proto=17))
        pkt.add_protocol(udp.udp(src_port=1000, dst_port=8000))

        payload = b'Hellooooooooo~~~~~~~~~'
        pkt.add_protocol(payload)

        # Packet serializing
        pkt.serialize()

        data = pkt.data

        msg = ev.msg
        dp = msg.datapath
        ofproto = dp.ofproto
        actions = [dp.ofproto_parser.OFPActionOutput(2)]

        out = dp.ofproto_parser.OFPPacketOut(
            datapath=dp, buffer_id=ofproto.OFP_NO_BUFFER, in_port=msg.match['in_port'],
            actions=actions, data=data)

        dp.send_msg(out)
Beispiel #14
0
    def test_serialize(self):
        src_ip = netaddr.IPAddress('192.168.0.1').value
        dst_ip = vrrp.VRRP_IPV4_DST_ADDRESS
        prev = ipv4.ipv4(4, 5, 0, 0, 0, 0, 0, vrrp.VRRP_IPV4_TTL,
                         inet.IPPROTO_VRRP, 0, src_ip, dst_ip)

        type_ = vrrp.VRRP_TYPE_ADVERTISEMENT
        vrid = 5
        priority = 10
        max_adver_int = 30
        ip_address = netaddr.IPAddress('192.168.0.2').value
        ip_addresses = [ip_address]

        vrrp_ = vrrp.vrrpv2.create(type_, vrid, priority, max_adver_int,
                                   ip_addresses)

        buf = vrrp_.serialize(bytearray(), prev)
        pack_str = vrrp.vrrpv2._PACK_STR + 'III'
        pack_len = struct.calcsize(pack_str)
        res = struct.unpack(pack_str, str(buf))
        eq_(res[0], vrrp.vrrp_to_version_type(vrrp.VRRP_VERSION_V2, type_))
        eq_(res[1], vrid)
        eq_(res[2], priority)
        eq_(res[3], len(ip_addresses))
        eq_(res[4], vrrp.VRRP_AUTH_NO_AUTH)
        eq_(res[5], max_adver_int)
        # res[6] is checksum
        eq_(res[7], ip_address)
        eq_(res[8], 0)
        eq_(res[9], 0)
        eq_(len(buf), pack_len)

        # checksum
        s = packet_utils.checksum(buf)
        eq_(0, s)
Beispiel #15
0
    def generateFINpkt(self):
        ipv4_p = self.payload_pkt.get_protocol(ipv4.ipv4)
        tcp_P = self.payload_pkt.get_protocol(tcp.tcp)
        eth_p = self.payload_pkt.get_protocol(ethernet.ethernet)

        e = ethernet.ethernet(dst=eth_p.dst, src=eth_p.src)

        #ip = ipv4.ipv4(4, 5, ipv4_p.tos, 0, 0, 0, 0, 255, 6, 0, src=ipv4_p.dst, dst=ipv4_p.src, option=None)
        #ip = ipv4.ipv4(4, 5, ipv4_p.tos, 0, ipv4_p.identification, ipv4_p.flags, 0, ipv4_p.ttl, ipv4_p.proto, 0, src=ipv4_p.src, dst=ipv4_p.dst, option=None)
        ip = ipv4.ipv4(4,
                       5,
                       ipv4_p.tos,
                       0,
                       ipv4_p.identification,
                       ipv4_p.flags,
                       0,
                       ipv4_p.ttl,
                       ipv4_p.proto,
                       0,
                       src=ipv4_p.dst,
                       dst=ipv4_p.src,
                       option=None)

        bits = 1 | 1 << 4
        #tcpd = tcp.tcp(tcp_P.src_port, tcp_P.dst_port, tcp_P.seq, tcp_P.ack, 0, bits, tcp_P.window_size, 0, tcp_P.urgent, tcp_P.option)
        tcpd = tcp.tcp(tcp_P.dst_port, tcp_P.src_port, tcp_P.seq, tcp_P.ack, 0,
                       bits, tcp_P.window_size, 0, tcp_P.urgent, tcp_P.option)

        fin_pkt = packet.Packet()
        fin_pkt.add_protocol(e)
        fin_pkt.add_protocol(ip)
        fin_pkt.add_protocol(tcpd)
        fin_pkt.serialize()
        print "FIN packet is generated."
        return fin_pkt
    def _set_redundancy(self, dpid, redundancy):
        self.logger.info("Setting redundancy to: {}".format(redundancy))
        datapath = get_datapath(self, dpid)
        ofp = datapath.ofproto
        ofp_parser = datapath.ofproto_parser

        self.logger.info("Create OAM packet")
        # pkt = copy.deepcopy(self.config_pkt)
        pkt = packet.Packet()
        pkt.add_protocol(
            ethernet.ethernet(ethertype=ether_types.ETH_TYPE_IP,
                              dst='ff:ff:ff:ff:ff:ff',
                              src='00:00:00:00:00:0c'))
        pkt.add_protocol(
            ipv4.ipv4(dst="255.255.255.255",
                      src="0.0.0.0",
                      proto=in_proto.IPPROTO_UDP))
        pkt.add_protocol(udp.udp(dst_port=common.UDP_PORT_OAM))
        payload = struct.pack(">i", int(redundancy))
        pkt.add_protocol(payload)
        pkt.serialize()
        data = pkt.data
        in_port = ofp.OFPP_CONTROLLER
        actions = [ofp_parser.OFPActionOutput(1)]
        req = ofp_parser.OFPPacketOut(datapath, ofp.OFP_NO_BUFFER, in_port,
                                      actions, data)
        self.logger.info("Send OAM packet to encoder")
        datapath.send_msg(req)
Beispiel #17
0
    def flood(self, msg, seq, except_port=None):
        size = len(msg)
        buf_size = 1200
        offset = 0
        count = size / buf_size + 1
        while size > 0:
            frag = msg[offset:offset + buf_size]
            offset = offset + buf_size
            size = size - buf_size
            pkt_data = json.dumps({'seq': seq, 'count': count, 'data': frag})
            p = packet.Packet()
            eth_header = ethernet.ethernet()
            ip_header = ipv4.ipv4(proto=MULTIJET_IP_PROTO)
            ip_header.serialize(pkt_data, eth_header)
            p.add_protocol(eth_header)
            p.add_protocol(ip_header)
            p.add_protocol(pkt_data)

            ofp = self.dp.ofproto
            parser = self.dp.ofproto_parser
            p.serialize()
            data = p.data
            actions = [parser.OFPActionOutput(ofp.OFPP_FLOOD)]
            if except_port is None:
                except_port = ofp.OFPP_CONTROLLER
            out = parser.OFPPacketOut(datapath=self.dp,
                                      buffer_id=ofp.OFP_NO_BUFFER,
                                      in_port=except_port,
                                      actions=actions,
                                      data=data)
            self.dp.send_msg(out)
        log('flood finished')
Beispiel #18
0
def build_carp_ad_packet(src_mac):
    # 16 bit for ip layer identification length
    # getrandbits return long int 
    identification = int(random.getrandbits(16))
    #total 3 bit in flags
    #position 0    : reserved
    #position 1 : don't fragment
    #position 2 : more fragment
    flags = 0b010
    eth_pkt = ethernet.ethernet(dst=vrrp.VRRP_IPV4_DST_MAC_ADDRESS,
                                #src=vrrp_ipv4_src_mac_address(CONF.CARP.VRID),
                                src=src_mac,
                                ethertype=ether_types.ETH_TYPE_IP)
    ip_pkt = ipv4.ipv4( identification=identification,
                        flags=flags,
                        ttl=vrrp.VRRP_IPV4_TTL,
                        proto=in_proto.IPPROTO_VRRP,
                        dst=vrrp.VRRP_IPV4_DST_ADDRESS)
    carp_pkt = vrrp.vrrpv2.create(type_=vrrp.VRRP_TYPE_ADVERTISEMENT,vrid=CONF.CARP.VRID,
                                    priority=0,max_adver_int=1,ip_addresses=[CONF.PARAMETER.LOGICAL_IP])
    p = packet.Packet()
    p.add_protocol(eth_pkt)
    p.add_protocol(ip_pkt)
    p.add_protocol(carp_pkt)
    return p
Beispiel #19
0
    def test_serialize_option(self):
        # prepare test data
        offset = 0
        csum = 0
        option = [
            tcp.TCPOptionMaximumSegmentSize(max_seg_size=1460),
            tcp.TCPOptionSACKPermitted(),
            tcp.TCPOptionTimestamps(ts_val=287454020, ts_ecr=1432778632),
            tcp.TCPOptionNoOperation(),
            tcp.TCPOptionWindowScale(shift_cnt=9),
        ]
        option_buf = b"\x02\x04\x05\xb4" b"\x04\x02" b"\x08\x0a\x11\x22\x33\x44\x55\x66\x77\x88" b"\x01" b"\x03\x03\x09"
        prev = ipv4(4, 5, 0, 0, 0, 0, 0, 64, inet.IPPROTO_TCP, 0, "192.168.10.1", "192.168.100.1")

        # test serializer
        t = tcp.tcp(
            self.src_port,
            self.dst_port,
            self.seq,
            self.ack,
            offset,
            self.bits,
            self.window_size,
            csum,
            self.urgent,
            option,
        )
        buf = t.serialize(bytearray(), prev)
        r_option_buf = buf[tcp.tcp._MIN_LEN : tcp.tcp._MIN_LEN + len(option_buf)]
        eq_(option_buf, r_option_buf)

        # test parser
        (r_tcp, _, _) = tcp.tcp.parser(buf)
        eq_(str(option), str(r_tcp.option))
Beispiel #20
0
 def _handle_icmp(self, datapath, port, pkt_ethernet, pkt_ipv4, pkt_icmp):
     """
     依据传入的 eth, ip, icmp 生成 packet包
     :param datapath:
     :param port:
     :param pkt_ethernet:
     :param pkt_ipv4:
     :param pkt_icmp:
     :return:
     """
     if pkt_icmp.type != icmp.ICMP_ECHO_REQUEST:
         return
     pkt = packet.Packet()
     pkt.add_protocol(
         ethernet.ethernet(ethertype=pkt_ethernet.ethertype,
                           dst=pkt_ethernet.src,
                           src=self.hw_addr))
     pkt.add_protocol(
         ipv4.ipv4(dst=pkt_ipv4.src, src=self.ip_addr,
                   proto=pkt_ipv4.proto))
     pkt.add_protocol(
         icmp.icmp(type_=icmp.ICMP_ECHO_REPLY,
                   code=icmp.ICMP_ECHO_REPLY_CODE,
                   csum=0,
                   data=pkt_icmp.data))
     self._send_packet(datapath, port, pkt)
    def _handle_icmp(self, ev, subname):
        msg = ev.msg
        datapath = msg.datapath
        pkt = packet.Packet(data=msg.data)
        pkt_ethernet = pkt.get_protocol(ethernet.ethernet)
        pkt_ipv4 = pkt.get_protocol(ipv4.ipv4)
        pkt_icmp = pkt.get_protocol(icmp.icmp)
        in_port = msg.match['in_port']
         
        # ignore icmp of other than icmp_echo_request
        if pkt_icmp.type != icmp.ICMP_ECHO_REQUEST:
            return
        # make packet object to return
        this_subnet=self.subnet[datapath.id][subname]
        pkt = packet.Packet()
        pkt.add_protocol(ethernet.ethernet(ethertype=pkt_ethernet.ethertype,
            dst=pkt_ethernet.src,
            src=this_subnet['mac']))
#             if vid != None:
#             pkt.add_protocol(vlan.vlan(vid=vid, ethertype = 0x0800))
        pkt.add_protocol(ipv4.ipv4(dst=pkt_ipv4.src,
            src=this_subnet['ip'],
            proto=pkt_ipv4.proto))
        pkt.add_protocol(icmp.icmp(type_=icmp.ICMP_ECHO_REPLY,
            code=icmp.ICMP_ECHO_REPLY_CODE,
            csum=0,
            data=pkt_icmp.data))
        self._send_packet(datapath, in_port, pkt)
        self.logger.info("icmp reply is sent: %s-%s via port=%s" % (pkt_ethernet.src, pkt_ipv4.src, in_port) )      
Beispiel #22
0
 def _handle_icmp(self, datapath, port, pkt_ethernet, pkt_ipv4, pkt_icmp,
                  SrcGroup):
     # パケットがICMP ECHOリクエストでなかった場合はすぐに返す
     # 自分のゲートウェイIPアドレスをもっているグループでなかったら終了
     print('ICMP : ', pkt_ipv4.src, ' > ', pkt_ipv4.dst)
     if pkt_icmp.type != icmp.ICMP_ECHO_REQUEST or pkt_ipv4.dst != self.group_mac[
             SrcGroup][0][0]:
         return
     # ICMPを作成して返す
     pkt = packet.Packet()
     pkt.add_protocol(
         ethernet.ethernet(ethertype=pkt_ethernet.ethertype,
                           dst=pkt_ethernet.src,
                           src=self.gateway_mac))  # ゲートウェイのmac
     pkt.add_protocol(
         ipv4.ipv4(
             dst=pkt_ipv4.src,
             src=self.group_mac[SrcGroup][0][0],  # ゲートウェイのIP
             proto=pkt_ipv4.proto))
     pkt.add_protocol(
         icmp.icmp(type_=icmp.ICMP_ECHO_REPLY,
                   code=icmp.ICMP_ECHO_REPLY_CODE,
                   csum=0,
                   data=pkt_icmp.data))
     self._send_packet(datapath, port, pkt)
Beispiel #23
0
Datei: a.py Projekt: jsjhan/test
def build_new_packet(switch):
    src_eth = switch['src_eth']
    dst_eth = switch['dst_eth']
    src_ip = switch['src_ip']
    dst_ip = switch['dst_ip']
    ip_id = switch['ip_id']
    seq = switch['seq']
    ack = switch['ack']
    src_port = switch['src_port']
    dst_port = switch['dst_port']

    #eth proto
    eth_pkt = ethernet.ethernet(src_eth,dst_eth,ethertype=ether_types.ETH_TYPE_IP)
    #ip proto
    ip_pkt = ipv4.ipv4(version=4, header_length=5,
                    tos=0, total_length=0,
                        identification=ip_id+1, flags=2,
                        offset=0, ttl=64,
                        proto=in_proto.IPPROTO_TCP, csum=0,
                        src=dst_ip, dst=src_ip)
    #tcp proto
    #psh ack bit
    bits = 0b011000
    tcp_pkt = tcp.tcp(src_port=dst_port, dst_port=src_port,
                    seq=ack, ack=seq, offset=0,
                    bits=bits, window_size=2048,
                    csum=0, urgent=0, option=None)
    p = packet.Packet()
    p.add_protocol(eth_pkt)
    p.add_protocol(ip_pkt)
    p.add_protocol(tcp_pkt)
    return p
Beispiel #24
0
    def assemble_ack(self, pkt):
        req_eth = pkt.get_protocol(ethernet.ethernet)
        req_ipv4 = pkt.get_protocol(ipv4.ipv4)
        req_udp = pkt.get_protocol(udp.udp)
        req = pkt.get_protocol(dhcp.dhcp)
        req.options.option_list.remove(
            next(opt for opt in req.options.option_list if opt.tag == 53))
        req.options.option_list.insert(
            0, dhcp.option(tag=51, value=bytes.fromhex('8640'.encode().hex())))
        req.options.option_list.insert(0, dhcp.option(tag=53,
                                                      value=bytes([5])))

        ack_pkt = packet.Packet()
        ack_pkt.add_protocol(
            ethernet.ethernet(ethertype=req_eth.ethertype,
                              dst=req_eth.src,
                              src=self.hw_addr))
        ack_pkt.add_protocol(
            ipv4.ipv4(dst=req_ipv4.dst,
                      src=self.dhcp_server,
                      proto=req_ipv4.proto))
        ack_pkt.add_protocol(udp.udp(src_port=67, dst_port=68))
        ack_pkt.add_protocol(
            dhcp.dhcp(op=2,
                      chaddr=req_eth.src,
                      siaddr=self.dhcp_server,
                      boot_file=req.boot_file,
                      yiaddr=self._cal_vm_ip(req),
                      xid=req.xid,
                      options=req.options))
        self.logger.info("ASSEMBLED ACK: %s" % ack_pkt)
        return ack_pkt
Beispiel #25
0
    def sendReply(self, sdonID, origMsg, action, reply):
        datapath = origMsg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser
        in_port = origMsg.match['in_port']
        if (action == "hello,"):
            # save this SdonManager in the dictionary so we can contact that switch when we want
            print "Saving " + str(sdonID) + "'s OF details."
            self.sdonID_to_OF[sdonID] = [datapath, parser, in_port]

            # Initialize the dictionary of Apps available for an SdonNode
            # self.sdonID_to_apps[pubIp] = []

        # Reply to the action message
        pkt = packet.Packet()
        e = ethernet.ethernet()
        i = ipv4.ipv4(src="10.0.0.1", dst = "1.2.3.4")
        # u = udp.udp()
        pkt= e/i/(str(action) + str(reply))
        pkt.serialize()

        data = pkt.data
        actions=[parser.OFPActionOutput(in_port)]
        out = parser.OFPPacketOut(datapath=datapath,
                                  buffer_id=ofproto.OFP_NO_BUFFER,
                                  in_port=ofproto.OFPP_CONTROLLER,
                                  actions=actions,
                                  data=data)
        datapath.send_msg(out)
Beispiel #26
0
 def handle_packet(self):
     pkt_ip = self._pkt.get_protocols(ipv4.ipv4)[0]
     pkt_udp = self._pkt.get_protocols(udp.udp)[0]
     cs = self._controller.get_customers()
     index1 = self._controller.get_current_customer_id()
     dns = DNS(self._pkt[-1])
     print('------UDP---------', index1, cs[int(index1)].get_next_hop_mac(),
           self._controller.get_transaction_id())
     if self._controller.get_destination_nat(
     ) is not None and self._controller.get_transaction_id() is not None:
         new_pkt = packet.Packet()
         new_pkt.add_protocol(
             ethernet.ethernet(src='10:00:00:00:10:ff',
                               dst=cs[int(index1)].get_next_hop_mac()))
         new_pkt.add_protocol(
             ipv4.ipv4(src=pkt_ip.src,
                       dst=cs[int(index1)].get_name_server(),
                       proto=17))
         new_pkt.add_protocol(
             udp.udp(src_port=pkt_udp.src_port, dst_port=pkt_udp.dst_port))
         new_pkt.add_protocol(self._pkt[-1])
         print('---------okt--------', new_pkt)
         new_pkt.serialize()
         print(
             '----------------The Number of Exchanged PACKETS between Controllers-----',
             self._controller.get_packet_counter())
         self.send_dns_packet(new_pkt, cs[int(index1)].get_datapath(),
                              cs[int(index1)].get_ingress_port())
     elif self._controller.get_destination_nat() is None:
         self.send_dns_response_to_controller(self._pkt)
Beispiel #27
0
    def test_serialize_with_auth_simple(self):
        pkt = packet.Packet()

        eth_pkt = ethernet.ethernet('08:00:27:d1:95:7c', '08:00:27:ed:54:41')
        pkt.add_protocol(eth_pkt)

        ip_pkt = ipv4.ipv4(src='192.168.57.2', dst='192.168.57.1', tos=192,
                           identification=3216, proto=inet.IPPROTO_UDP)
        pkt.add_protocol(ip_pkt)

        udp_pkt = udp.udp(49152, 3784)
        pkt.add_protocol(udp_pkt)

        auth_cls = bfd.SimplePassword(auth_key_id=2,
                                      password=self.auth_keys[2])

        bfd_pkt = bfd.bfd(ver=1, diag=bfd.BFD_DIAG_NO_DIAG,
                          flags=bfd.BFD_FLAG_AUTH_PRESENT,
                          state=bfd.BFD_STATE_DOWN, detect_mult=3, my_discr=1,
                          your_discr=0, desired_min_tx_interval=1000000,
                          required_min_rx_interval=1000000,
                          required_min_echo_rx_interval=0,
                          auth_cls=auth_cls)

        pkt.add_protocol(bfd_pkt)

        eq_(len(pkt.protocols), 4)

        pkt.serialize()
        eq_(pkt.data, self.data_auth_simple)
Beispiel #28
0
    def _build_vlan(self):
        src_mac = mac.haddr_to_bin('00:07:0d:af:f4:54')
        dst_mac = mac.haddr_to_bin('00:00:00:00:00:00')
        ethertype = ether.ETH_TYPE_8021Q
        e = ethernet(dst_mac, src_mac, ethertype)

        version = 4
        header_length = 20
        tos = 0
        total_length = 24
        identification = 0x8a5d
        flags = 0
        offset = 1480
        ttl = 64
        proto = inet.IPPROTO_ICMP
        csum = 0xa7f2
        src = int(netaddr.IPAddress('131.151.32.21'))
        dst = int(netaddr.IPAddress('131.151.32.129'))
        option = 'TEST'
        ip = ipv4(version, header_length, tos, total_length, identification,
                  flags, offset, ttl, proto, csum, src, dst, option)

        p = Packet()

        p.add_protocol(e)
        p.add_protocol(self.v)
        p.add_protocol(ip)
        p.serialize()

        return p
Beispiel #29
0
    def assemble_ack(self, pkt):
        req_eth = pkt.get_protocol(ethernet.ethernet)
        req_ipv4 = pkt.get_protocol(ipv4.ipv4)
        req_udp = pkt.get_protocol(udp.udp)
        req = dhcp.dhcp.parser(pkt[3])
        req[0].options.option_list.remove(
            next(opt for opt in req[0].options.option_list if opt.tag == 53))
        req[0].options.option_list.insert(0, dhcp.option(tag=51, value='8640'))
        req[0].options.option_list.insert(
            0, dhcp.option(tag=53, value='05'.decode('hex')))

        ack_pkt = packet.Packet()
        ack_pkt.add_protocol(
            ethernet.ethernet(ethertype=req_eth.ethertype,
                              dst=req_eth.src,
                              src=self.hw_addr))
        ack_pkt.add_protocol(
            ipv4.ipv4(dst=req_ipv4.dst,
                      src=self.dhcp_server,
                      proto=req_ipv4.proto))
        ack_pkt.add_protocol(udp.udp(src_port=67, dst_port=68))
        ack_pkt.add_protocol(
            dhcp.dhcp(op=2,
                      chaddr=req_eth.src,
                      siaddr=self.dhcp_server,
                      boot_file=req[0].boot_file,
                      yiaddr=self.ip_addr,
                      xid=req[0].xid,
                      options=req[0].options))
        self.logger.info("ASSEMBLED ACK: %s" % ack_pkt)
        return ack_pkt
Beispiel #30
0
    def test_serialize_with_auth_sha1(self):
        pkt = packet.Packet()

        eth_pkt = ethernet.ethernet("08:00:27:d1:95:7c", "08:00:27:ed:54:41")
        pkt.add_protocol(eth_pkt)

        ip_pkt = ipv4.ipv4(src="192.168.57.2", dst="192.168.57.1", tos=192, identification=2960, proto=inet.IPPROTO_UDP)
        pkt.add_protocol(ip_pkt)

        udp_pkt = udp.udp(49152, 3784)
        pkt.add_protocol(udp_pkt)

        auth_cls = bfd.KeyedSHA1(auth_key_id=2, seq=16817, auth_key=self.auth_keys[2])

        bfd_pkt = bfd.bfd(
            ver=1,
            diag=bfd.BFD_DIAG_NO_DIAG,
            flags=bfd.BFD_FLAG_AUTH_PRESENT,
            state=bfd.BFD_STATE_DOWN,
            detect_mult=3,
            my_discr=1,
            your_discr=0,
            desired_min_tx_interval=1000000,
            required_min_rx_interval=1000000,
            required_min_echo_rx_interval=0,
            auth_cls=auth_cls,
        )

        pkt.add_protocol(bfd_pkt)

        eq_(len(pkt.protocols), 4)

        pkt.serialize()
        eq_(pkt.data, self.data_auth_sha1)
Beispiel #31
0
    def assemble_ack(self, pkt):
        response_eth = pkt.get_protocol(ethernet.ethernet)
        response_ipv4 = pkt.get_protocol(ipv4.ipv4)
        response = pkt.get_protocol(dhcp.dhcp)
        response.options.option_list.remove(
            next(opt for opt in response.options.option_list if opt.tag == 53))
        response.options.option_list.insert(0, dhcp.option(tag=51, value=''))
        response.options.option_list.insert(0, dhcp.option(tag=53, value=""))

        ack_pkt = packet.Packet()
        ack_pkt.add_protocol(
            ethernet.ethernet(ethertype=response_eth.ethertype,
                              dst=response_eth.src,
                              src=""))
        ack_pkt.add_protocol(
            ipv4.ipv4(dst=response_ipv4.dst,
                      src=self.dhcp_server,
                      proto=response_ipv4.proto))
        ack_pkt.add_protocol(udp.udp(src_port=67, dst_port=68))
        ack_pkt.add_protocol(
            dhcp.dhcp(op=2,
                      chaddr=response_eth.src,
                      siaddr="dhcp_server",
                      boot_file=response.boot_file,
                      yiaddr="ip_addr",
                      xid=response.xid,
                      options=response.options))
        return ack_pkt
Beispiel #32
0
    def send_ipv4_packet (self, datapath, port_no, hw_addr):
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        pkt = packet.Packet()
        pkt.add_protocol(ethernet.ethernet(ethertype=self.ipv4_type, src=hw_addr))
        pkt.add_protocol(ipv4.ipv4(version=4, 
                                   header_length=5, 
                                   tos=0, 
                                   total_length=0, 
                                   identification=0, 
                                   flags=0, 
                                   offset=0, 
                                   ttl=0, 
                                   proto=0, 
                                   csum=0, 
                                   src='10.0.0.1', 
                                   dst='10.0.0.2', 
                                   option=None))
 
        actions = [parser.OFPActionOutput(ofproto.OFPP_FLOOD)]
        out = parser.OFPPacketOut(datapath=datapath,
                                  buffer_id=ofproto.OFP_NO_BUFFER,
                                  in_port=ofproto.OFPP_CONTROLLER,
                                  actions=actions,
                                  data=data)
        datapath.send_msg(out)
Beispiel #33
0
    def assemble_ack(self, pkt, chaddr):
        chaddr_yiaddr = self.get_ip(chaddr)
        req_eth = pkt.get_protocol(ethernet.ethernet)
        req_ipv4 = pkt.get_protocol(ipv4.ipv4)
        req_udp = pkt.get_protocol(udp.udp)
        req = pkt.get_protocol(dhcp.dhcp)
        req.options.option_list.remove(
            next(opt for opt in req.options.option_list if opt.tag == 53))
        req.options.option_list.insert(
            0, dhcp.option(tag=51, value=str.encode('8640')))
        req.options.option_list.insert(
            0, dhcp.option(tag=53, value=str.encode('\x05')))

        ack_pkt = packet.Packet()
        ack_pkt.add_protocol(
            ethernet.ethernet(ethertype=req_eth.ethertype,
                              dst=req_eth.src,
                              src=self.hw_addr))
        ack_pkt.add_protocol(
            ipv4.ipv4(dst=req_ipv4.dst,
                      src=self.dhcp_server,
                      proto=req_ipv4.proto))
        ack_pkt.add_protocol(udp.udp(src_port=67, dst_port=68))
        ack_pkt.add_protocol(
            dhcp.dhcp(op=2,
                      chaddr=req_eth.src,
                      siaddr=self.dhcp_server,
                      boot_file=req.boot_file,
                      yiaddr=chaddr_yiaddr,
                      xid=req.xid,
                      options=req.options))
        self.logger.debug("ASSEMBLED ACK")
        return ack_pkt
Beispiel #34
0
    def assemble_offer(self, pkt):
        disc_eth = pkt.get_protocol(ethernet.ethernet)
        disc_ipv4 = pkt.get_protocol(ipv4.ipv4)
        disc_udp = pkt.get_protocol(udp.udp)
        disc = dhcp.dhcp.parser(pkt[3])
        disc[0].options.option_list.remove(next(opt for opt in disc[0].options.option_list if opt.tag == 55))
        disc[0].options.option_list.remove(next(opt for opt in disc[0].options.option_list if opt.tag == 53))
        disc[0].options.option_list.remove(next(opt for opt in disc[0].options.option_list if opt.tag == 12))
        disc[0].options.option_list.insert(0, dhcp.option(tag=1, value=self.bin_netmask))
        disc[0].options.option_list.insert(0, dhcp.option(tag=3, value=self.bin_server))
        disc[0].options.option_list.insert(0, dhcp.option(tag=6, value=self.bin_dns))
        disc[0].options.option_list.insert(0, dhcp.option(tag=12, value=self.hostname))
        disc[0].options.option_list.insert(0, dhcp.option(tag=53, value='02'.decode('hex')))
        disc[0].options.option_list.insert(0, dhcp.option(tag=54, value=self.bin_server))

        offer_pkt = packet.Packet()
        offer_pkt.add_protocol(ethernet.ethernet(ethertype=disc_eth.ethertype, dst=disc_eth.src, src=self.hw_addr))
        offer_pkt.add_protocol(ipv4.ipv4(dst=disc_ipv4.dst, src=self.dhcp_server, proto=disc_ipv4.proto))
        offer_pkt.add_protocol(udp.udp(src_port=67,dst_port=68))
        offer_pkt.add_protocol(dhcp.dhcp(op=2, chaddr=disc_eth.src,
                                         siaddr=self.dhcp_server,
                                         boot_file=disc[0].boot_file,
                                         yiaddr=self.ip_addr,
                                         xid=disc[0].xid,
                                         options=disc[0].options))
        self.logger.info("ASSEMBLED OFFER: %s" % offer_pkt)
        return offer_pkt
Beispiel #35
0
    def test_serialize(self):
        pkt = packet.Packet()

        eth_pkt = ethernet.ethernet('b0:a8:6e:18:b8:08', '64:87:88:e9:cb:c8')
        pkt.add_protocol(eth_pkt)

        ip_pkt = ipv4.ipv4(src='172.28.3.1',
                           dst='172.28.3.2',
                           tos=192,
                           identification=26697,
                           proto=inet.IPPROTO_UDP)
        pkt.add_protocol(ip_pkt)

        udp_pkt = udp.udp(49152, 3784)
        pkt.add_protocol(udp_pkt)

        bfd_pkt = bfd.bfd(ver=1,
                          diag=bfd.BFD_DIAG_CTRL_DETECT_TIME_EXPIRED,
                          state=bfd.BFD_STATE_UP,
                          detect_mult=3,
                          my_discr=6,
                          your_discr=7,
                          desired_min_tx_interval=60000,
                          required_min_rx_interval=60000,
                          required_min_echo_rx_interval=0)
        pkt.add_protocol(bfd_pkt)

        eq_(len(pkt.protocols), 4)

        pkt.serialize()
        eq_(pkt.data, self.data)
Beispiel #36
0
def new_udp_pkt(eth_dst, eth_src, ip_dst, ip_src, src_port, dst_port, size=0):
    # pcap_pen = pcaplib.Writer(open('pkt.pcap', 'wb'))
    # Creat an empty Packet instance
    pkt = packet.Packet()

    pkt.add_protocol(ethernet.ethernet(ethertype=0x0800, dst=eth_dst,
                                       src=eth_src))

    pkt.add_protocol(ipv4.ipv4(dst=ip_dst, src=ip_src, proto=17))
    pkt.add_protocol(udp.udp(src_port=src_port, dst_port=dst_port))

    # Check how many byte be used under layer 3
    _pkt = copy.deepcopy(pkt)
    _pkt.serialize()
    _d = _pkt.data

    # the max. packet size is 1500 byte
    limited_size = 1500 - len(_d)

    # if size larger than 1500 byte set limit size
    if size >= limited_size:
        size = limited_size

    if size != 0:
        payload = os.urandom(size)
        # Add payload
        pkt.add_protocol(payload)

    # Packet serializing
    pkt.serialize()
    data = pkt.data
    # pcap_pen.write_pkt(data)
    return data
Beispiel #37
0
    def test_serialize(self):
        src_port = 6431
        dst_port = 8080
        total_length = 0
        csum = 0

        src_ip = '192.168.10.1'
        dst_ip = '192.168.100.1'
        prev = ipv4(4, 5, 0, 0, 0, 0, 0, 64,
                    inet.IPPROTO_UDP, 0, src_ip, dst_ip)

        u = udp(src_port, dst_port, total_length, csum)
        buf = u.serialize(bytearray(), prev)
        res = struct.unpack(udp._PACK_STR, buf)

        eq_(res[0], src_port)
        eq_(res[1], dst_port)
        eq_(res[2], struct.calcsize(udp._PACK_STR))

        # checksum
        ph = struct.pack('!4s4sBBH',
                         addrconv.ipv4.text_to_bin(src_ip),
                         addrconv.ipv4.text_to_bin(dst_ip), 0, 17, res[2])
        d = ph + buf + bytearray()
        s = packet_utils.checksum(d)
        eq_(0, s)
Beispiel #38
0
def generate_trace_pkt(entries, color, r_id):
    '''
        Receives the REST/PUT to generate a PacketOut
        data needs to be serialized
        template_trace.json is an example
    '''
    trace = {}
    switch = {}
    eth = {}
    ip = {}
    tp = {}

    # TODO Validate for dl_vlan. If empty, return error.

    dpid, in_port = 0, 65532
    dl_src, dl_dst = "ca:fe:ca:fe:00:00", "ca:fe:ca:fe:ca:fe"
    dl_vlan, dl_type = 100, 2048
    nw_src, nw_dst, nw_tos = '127.0.0.1', '127.0.0.1', 0
    tp_src, tp_dst = 1, 1

    try:
        trace = entries['trace']
        switch = trace['switch']
        eth = trace['eth']
        ip = trace['ip']
        tp = trace['tp']
    except:
        pass


    if len(switch) > 0:
        dpid, in_port = prepare_switch(switch, dpid, in_port)

    if len(eth) > 0:
        dl_src, dl_dst, dl_vlan, dl_type = prepare_ethernet(eth, dl_src, dl_dst,
                                                            dl_vlan, dl_type)
    if len(ip) > 0:
        nw_src, nw_dst, nw_tos = prepare_ip(ip, nw_src, nw_dst, nw_tos)

    if len(tp) > 0:
        tp_src, tp_dst = prepare_tp(tp, tp_src, tp_dst)

    pkt = packet.Packet()

    eth_pkt = ethernet.ethernet(dst=dl_dst, src=dl_src, ethertype=33024)
    vlan_pkt = vlan.vlan(vid=dl_vlan, ethertype=dl_type, pcp=int(color, 2))
    pkt.add_protocol(eth_pkt)
    pkt.add_protocol(vlan_pkt)

    if dl_type == 2048:
        ip_pkt = ipv4.ipv4(dst=str(nw_dst), src=str(nw_src), tos=nw_tos,
                           proto=6)
        pkt.add_protocol(ip_pkt)
        tp_pkt = tcp.tcp(dst_port=tp_dst, src_port=tp_src)
        pkt.add_protocol(tp_pkt)
        data = str(r_id)   # this will be the ID
        pkt.add_protocol(data)

    pkt.serialize()
    return in_port, pkt
    def test_serialize(self):
        offset = 5
        csum = 0

        src_ip = '192.168.10.1'
        dst_ip = '192.168.100.1'
        prev = ipv4(4, 5, 0, 0, 0, 0, 0, 64, inet.IPPROTO_TCP, 0, src_ip,
                    dst_ip)

        t = tcp(self.src_port, self.dst_port, self.seq, self.ack, offset,
                self.bits, self.window_size, csum, self.urgent)
        buf = t.serialize(bytearray(), prev)
        res = struct.unpack(tcp._PACK_STR, str(buf))

        eq_(res[0], self.src_port)
        eq_(res[1], self.dst_port)
        eq_(res[2], self.seq)
        eq_(res[3], self.ack)
        eq_(res[4], offset << 4)
        eq_(res[5], self.bits)
        eq_(res[6], self.window_size)
        eq_(res[8], self.urgent)

        # checksum
        ph = struct.pack('!4s4sBBH', addrconv.ipv4.text_to_bin(src_ip),
                         addrconv.ipv4.text_to_bin(dst_ip), 0, 6, offset * 4)
        d = ph + buf + bytearray()
        s = packet_utils.checksum(d)
        eq_(0, s)
Beispiel #40
0
    def test_serialize(self):
        pkt = packet.Packet()

        eth_pkt = ethernet.ethernet("b0:a8:6e:18:b8:08", "64:87:88:e9:cb:c8")
        pkt.add_protocol(eth_pkt)

        ip_pkt = ipv4.ipv4(src="172.28.3.1", dst="172.28.3.2", tos=192, identification=26697, proto=inet.IPPROTO_UDP)
        pkt.add_protocol(ip_pkt)

        udp_pkt = udp.udp(49152, 3784)
        pkt.add_protocol(udp_pkt)

        bfd_pkt = bfd.bfd(
            ver=1,
            diag=bfd.BFD_DIAG_CTRL_DETECT_TIME_EXPIRED,
            state=bfd.BFD_STATE_UP,
            detect_mult=3,
            my_discr=6,
            your_discr=7,
            desired_min_tx_interval=60000,
            required_min_rx_interval=60000,
            required_min_echo_rx_interval=0,
        )
        pkt.add_protocol(bfd_pkt)

        eq_(len(pkt.protocols), 4)

        pkt.serialize()
        eq_(pkt.data, self.data)
Beispiel #41
0
    def _ping(self, dp, port_out):
        ofp = dp.ofproto
        parser = dp.ofproto_parser
        pkt = packet.Packet()
        pkt.add_protocol(
            ethernet.ethernet(ethertype=0x0800,
                              dst='ff:ff:ff:ff:ff:ff',
                              src='aa:aa:aa:aa:aa:aa'))

        pkt.add_protocol(ipv4.ipv4(dst='0.0.0.2', src='0.0.0.1', proto=1))

        pkt.add_protocol(
            icmp.icmp(type_=8,
                      code=0,
                      csum=0,
                      data=icmp.echo(
                          1, 1, "{'dpid' : " + str(dp.id) + ",'port_out' : " +
                          str(port_out) + "}")))
        pkt.serialize()
        data = pkt.data
        actions = [parser.OFPActionOutput(port_out, 0)]
        out = parser.OFPPacketOut(datapath=dp,
                                  buffer_id=ofp.OFP_NO_BUFFER,
                                  in_port=ofp.OFPP_CONTROLLER,
                                  actions=actions,
                                  data=data)
        dp.send_msg(out)
Beispiel #42
0
    def test_serialize_with_auth_sha1(self):
        pkt = packet.Packet()

        eth_pkt = ethernet.ethernet('08:00:27:d1:95:7c', '08:00:27:ed:54:41')
        pkt.add_protocol(eth_pkt)

        ip_pkt = ipv4.ipv4(src='192.168.57.2', dst='192.168.57.1', tos=192,
                           identification=2960, proto=inet.IPPROTO_UDP)
        pkt.add_protocol(ip_pkt)

        udp_pkt = udp.udp(49152, 3784)
        pkt.add_protocol(udp_pkt)

        auth_cls = bfd.KeyedSHA1(auth_key_id=2, seq=16817,
                                 auth_key=self.auth_keys[2])

        bfd_pkt = bfd.bfd(ver=1, diag=bfd.BFD_DIAG_NO_DIAG,
                          flags=bfd.BFD_FLAG_AUTH_PRESENT,
                          state=bfd.BFD_STATE_DOWN, detect_mult=3, my_discr=1,
                          your_discr=0, desired_min_tx_interval=1000000,
                          required_min_rx_interval=1000000,
                          required_min_echo_rx_interval=0,
                          auth_cls=auth_cls)

        pkt.add_protocol(bfd_pkt)

        eq_(len(pkt.protocols), 4)

        pkt.serialize()
        eq_(pkt.data, self.data_auth_sha1)
    def handle_ip(self, datapath, in_port, pkt):
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        ipv4_pkt = pkt.get_protocol(ipv4.ipv4) # parse out the IPv4 pkt

        if datapath.id == 1 and ipv4_pkt.proto == inet.IPPROTO_TCP:
            tcp_pkt = pkt.get_protocol(tcp.tcp) # parser out the TCP pkt
            eth_pkt = pkt.get_protocol(ethernet.ethernet)
            #if (tcp_pkt.bits) % 4 == 2:


            tcp_hd = tcp.tcp(ack=tcp_pkt.seq+1, src_port = tcp_pkt.dst_port, dst_port = tcp_pkt.src_port, bits=20)
            ip_hd = ipv4.ipv4(dst= ipv4_pkt.src, src= ipv4_pkt.dst, proto=ipv4_pkt.proto)
            ether_hd = ethernet.ethernet(ethertype = ether.ETH_TYPE_IP, dst = eth_pkt.src, src = eth_pkt.dst)
            tcp_rst_ack = packet.Packet()
            tcp_rst_ack.add_protocol(ether_hd)
            tcp_rst_ack.add_protocol(ip_hd)
            tcp_rst_ack.add_protocol(tcp_hd)
            tcp_rst_ack.serialize()


            # generate the TCP packet with the RST flag set to 1
            # packet generation is similar to ARP,
            # but need to generate ethernet->ip->tcp and serialize it
            
        # send the Packet Out mst to back to the host who is initilaizing the ARP
            actions = [parser.OFPActionOutput(in_port)];
            out = parser.OFPPacketOut(datapath, ofproto.OFP_NO_BUFFER, 
                                      ofproto.OFPP_CONTROLLER, actions,
                                      tcp_rst_ack.data)
            datapath.send_msg(out)
Beispiel #44
0
    def test_serialize(self):
        src_ip = netaddr.IPAddress('192.168.0.1').value
        dst_ip = vrrp.VRRP_IPV4_DST_ADDRESS
        prev = ipv4.ipv4(4, 5, 0, 0, 0, 0, 0, vrrp.VRRP_IPV4_TTL,
                         inet.IPPROTO_VRRP, 0, src_ip, dst_ip)

        type_ = vrrp.VRRP_TYPE_ADVERTISEMENT
        vrid = 5
        priority = 10
        max_adver_int = 30
        ip_address = netaddr.IPAddress('192.168.0.2').value
        ip_addresses = [ip_address]

        vrrp_ = vrrp.vrrpv2.create(
            type_, vrid, priority, max_adver_int, ip_addresses)

        buf = vrrp_.serialize(bytearray(), prev)
        pack_str = vrrp.vrrpv2._PACK_STR + 'III'
        pack_len = struct.calcsize(pack_str)
        res = struct.unpack(pack_str, str(buf))
        eq_(res[0], vrrp.vrrp_to_version_type(vrrp.VRRP_VERSION_V2, type_))
        eq_(res[1], vrid)
        eq_(res[2], priority)
        eq_(res[3], len(ip_addresses))
        eq_(res[4], vrrp.VRRP_AUTH_NO_AUTH)
        eq_(res[5], max_adver_int)
        # res[6] is checksum
        eq_(res[7], ip_address)
        eq_(res[8], 0)
        eq_(res[9], 0)
        eq_(len(buf), pack_len)

        # checksum
        s = packet_utils.checksum(buf)
        eq_(0, s)
    def handle_ip(self, datapath, in_port, pkt):
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        ipv4_pkt = pkt.get_protocol(ipv4.ipv4)  # parse out the IPv4 pkt

        if (datapath.id == 2
                or datapath.id == 4) and ipv4_pkt.proto == inet.IPPROTO_TCP:
            tcp_pkt = ipv4_pkt.get_protocol(tcp.tcp)  # parser out the TCP pkt

            ### generate the TCP packet with the RST flag set to 1
            ### packet generation is similar to ARP,
            ### but you need to generate ethernet->ip->tcp and serialize it
            eth_pkt = ipv4_dst.get_protocol(ethernet, ethernet)
            tcp_hd = tcp.tcp(ack=tcp_pkt.seq + 1,
                             src_port=tcp_pkt.dst_port,
                             dst_port=tcp_pkt.src_port,
                             bits=20)
            ip_hd = ipv4.ipv4(dst=ipv4_pkt.src,
                              src=ipv4_pkt.dst,
                              proto=ipv4_pkt.proto)
            ether_hd = ethernet.ethernet(ethertype=ether.ETH_TYPE_IP,
                                         dst=eth_pkt.src,
                                         src=eth_pkt.dst)
            tcp_rst_ack = packet.Packet()
            tcp_rst_ack.add_protocol(ether_hd)
            tcp_rst_ack.add_protocol(ip_hd)
            tcp_rst_ack.add_protocol(tcp_hd)
            tcp_rst_ack.serialize()
            # send the Packet Out mst to back to the host who is initilaizing the ARP
            actions = [parser.OFPActionOutput(in_port)]
            out = parser.OFPPacketOut(datapath, ofproto.OFP_NO_BUFFER,
                                      ofproto.OFPP_CONTROLLER, actions,
                                      tcp_rst_ack.data)
            datapath.send_msg(out)
Beispiel #46
0
 def _handle_icmp(self, msg, port, data):
     # パケットがICMP ECHOリクエストでなかった場合はすぐに返す
     # 自分のゲートウェイIPアドレスをもっているグループでなかったら終了
     pkt = packet.Packet(data)
     pkt_icmp = pkt.get_protocol(icmp.icmp)
     pkt_ethernet = pkt.get_protocol(ethernet.ethernet)
     pkt_ipv4 = pkt.get_protocol(ipv4.ipv4)
     if pkt_ipv4:
         pass
     else:
         return
     if pkt_icmp.type != icmp.ICMP_ECHO_REQUEST or pkt_ipv4.dst != self.gateway_ip:
         return
     src_mac = self.gateway_mac
     src_ip = self.gateway_ip
     dst_mac = pkt_ethernet.src
     dst_ip = pkt_ipv4.src
     print('ICMP : ', src_ip, ' >> ', dst_ip)
     # ICMPを作成して返す
     pkt = packet.Packet()
     pkt.add_protocol(
         ethernet.ethernet(ethertype=pkt_ethernet.ethertype,
                           dst=dst_mac,
                           src=src_mac))  # ゲートウェイのmac
     pkt.add_protocol(
         ipv4.ipv4(
             dst=dst_ip,
             src=src_ip,  # ゲートウェイのIP
             proto=pkt_ipv4.proto))
     pkt.add_protocol(
         icmp.icmp(type_=icmp.ICMP_ECHO_REPLY,
                   code=icmp.ICMP_ECHO_REPLY_CODE,
                   csum=0,
                   data=pkt_icmp.data))
     self._send_packet(port, pkt, self.datapath.ofproto.OFP_NO_BUFFER)
Beispiel #47
0
    def send_ping_packet(self, s1, s2):
        '''
            Send a ping/ICMP packet between two switches.
            Uses ryu's packet library.
            Uses a fake MAC and IP address only known to controller.
        '''
        datapath = self.datapath_list[int(s1.dpid)]
        dst_mac = self.ping_mac
        dst_ip = self.ping_ip
        out_port = s1.port_no
        actions = [datapath.ofproto_parser.OFPActionOutput(out_port)]

        pkt = packet.Packet()
        pkt.add_protocol(
            ethernet.ethernet(ethertype=ether_types.ETH_TYPE_IP,
                              src=self.controller_mac,
                              dst=dst_mac))
        pkt.add_protocol(
            ipv4.ipv4(proto=in_proto.IPPROTO_ICMP,
                      src=self.controller_ip,
                      dst=dst_ip))
        echo_payload = '%s;%s;%f' % (s1.dpid, s2.dpid, time.time())
        payload = icmp.echo(data=echo_payload)
        pkt.add_protocol(icmp.icmp(data=payload))
        pkt.serialize()

        out = datapath.ofproto_parser.OFPPacketOut(
            datapath=datapath,
            buffer_id=datapath.ofproto.OFP_NO_BUFFER,
            data=pkt.data,
            in_port=datapath.ofproto.OFPP_CONTROLLER,
            actions=actions)

        datapath.send_msg(out)
Beispiel #48
0
    def send_ping_packet(self, switch, ip):
        datapath = switch.dp
        dpid = datapath.id
        mac_dst = self.arp_table[ip]
        out_port = self.mac_to_port[dpid][mac_dst]
        actions = [datapath.ofproto_parser.OFPActionOutput(out_port)]

        pkt = packet.Packet()
        pkt.add_protocol(
            ethernet.ethernet(ethertype=ether_types.ETH_TYPE_IP,
                              src=self.controller_mac,
                              dst=self.arp_table[ip]))
        pkt.add_protocol(
            ipv4.ipv4(proto=in_proto.IPPROTO_ICMP,
                      src=self.controller_ip,
                      dst=ip))
        echo_payload = '%d;%s;%f' % (dpid, ip, time.time())
        payload = icmp.echo(data=echo_payload)
        pkt.add_protocol(icmp.icmp(data=payload))
        pkt.serialize()

        out = datapath.ofproto_parser.OFPPacketOut(
            datapath=datapath,
            buffer_id=datapath.ofproto.OFP_NO_BUFFER,
            data=pkt.data,
            in_port=datapath.ofproto.OFPP_CONTROLLER,
            actions=actions)

        datapath.send_msg(out)
Beispiel #49
0
      def send_ospf_hello(self,signum, frame):
	ospf_hello = ospf.OSPFHello(router_id = self.router_id ,neighbors = self.neighbors)
	rtr = self.routers
	datapath = rtr.datapath	
        hello = ospf_hello.serialize()
	p = packet.Packet()
        e = ethernet.ethernet(dst = '00:0c:29:9c:a6:82',src = '00:0c:29:52:9b:c4', ethertype = ether.ETH_TYPE_IP)
	f = ipv4.ipv4(dst='192.168.66.195',
                     src='192.168.66.135',
                     proto=inet.IPPROTO_OSPF)
	p.add_protocol(e)
	p.add_protocol(f)
	p.add_protocol(hello)
	p.serialize()
	print " ================= P.DATA =========== "
	print p.data
	print " ================= P.DATA =========== "
	actions = [datapath.ofproto_parser.OFPActionOutput(6)]
        out = datapath.ofproto_parser.OFPPacketOut(datapath=datapath,
                                  buffer_id=datapath.ofproto.OFP_NO_BUFFER,
                                  in_port=datapath.ofproto.OFPP_CONTROLLER,
                                  actions=actions,
                                  data=p.data) 

	datapath.send_msg(out)
	self.call()
Beispiel #50
0
    def test_serialize(self):
        offset = 5
        csum = 0

        src_ip = '192.168.10.1'
        dst_ip = '192.168.100.1'
        prev = ipv4(4, 5, 0, 0, 0, 0, 0, 64,
                    inet.IPPROTO_TCP, 0, src_ip, dst_ip)

        t = tcp(self.src_port, self.dst_port, self.seq, self.ack,
                offset, self.bits, self.window_size, csum, self.urgent)
        buf = t.serialize(bytearray(), prev)
        res = struct.unpack(tcp._PACK_STR, str(buf))

        eq_(res[0], self.src_port)
        eq_(res[1], self.dst_port)
        eq_(res[2], self.seq)
        eq_(res[3], self.ack)
        eq_(res[4], offset << 4)
        eq_(res[5], self.bits)
        eq_(res[6], self.window_size)
        eq_(res[8], self.urgent)

        # checksum
        ph = struct.pack('!4s4sBBH',
                         addrconv.ipv4.text_to_bin(src_ip),
                         addrconv.ipv4.text_to_bin(dst_ip), 0, 6, offset * 4)
        d = ph + buf + bytearray()
        s = packet_utils.checksum(d)
        eq_(0, s)
Beispiel #51
0
    def _ping(self,
              dp,
              port_out,
              ip_src=DISCOVERY_IP_SRC,
              ip_dst=DISCOVERY_IP_DST,
              eth_src='02:b0:00:00:00:b5',
              eth_dst='02:bb:bb:bb:bb:bb',
              icmp_type=8,
              icmp_code=0):
        ofp = dp.ofproto
        parser = dp.ofproto_parser
        pkt = packet.Packet()
        pkt.add_protocol(
            ethernet.ethernet(ethertype=0x0800, dst=eth_dst, src=eth_src))

        pkt.add_protocol(ipv4.ipv4(dst=ip_dst, src=ip_src, proto=1))

        pkt.add_protocol(
            icmp.icmp(type_=icmp_type,
                      code=icmp_code,
                      csum=0,
                      data=icmp.echo(
                          1, 1, "{'dpid' : " + str(dp.id) + ",'port_out' : " +
                          str(port_out) + "}")))
        pkt.serialize()
        data = pkt.data
        actions = [parser.OFPActionOutput(port_out, 0)]
        out = parser.OFPPacketOut(datapath=dp,
                                  buffer_id=ofp.OFP_NO_BUFFER,
                                  in_port=ofp.OFPP_CONTROLLER,
                                  actions=actions,
                                  data=data)
        dp.send_msg(out)
Beispiel #52
0
    def _build_vlan(self):
        src_mac = mac.haddr_to_bin('00:07:0d:af:f4:54')
        dst_mac = mac.haddr_to_bin('00:00:00:00:00:00')
        ethertype = ether.ETH_TYPE_8021Q
        e = ethernet(dst_mac, src_mac, ethertype)

        version = 4
        header_length = 20
        tos = 0
        total_length = 24
        identification = 0x8a5d
        flags = 0
        offset = 1480
        ttl = 64
        proto = inet.IPPROTO_ICMP
        csum = 0xa7f2
        src = int(netaddr.IPAddress('131.151.32.21'))
        dst = int(netaddr.IPAddress('131.151.32.129'))
        option = 'TEST'
        ip = ipv4(version, header_length, tos, total_length, identification,
                  flags, offset, ttl, proto, csum, src, dst, option)

        p = Packet()

        p.add_protocol(e)
        p.add_protocol(self.v)
        p.add_protocol(ip)
        p.serialize()

        return p
Beispiel #53
0
    def _build_itag(self):
        b_src_mac = '00:07:0d:af:f4:54'
        b_dst_mac = '00:00:00:00:00:00'
        b_ethertype = ether.ETH_TYPE_8021AD
        e1 = ethernet.ethernet(b_dst_mac, b_src_mac, b_ethertype)

        b_pcp = 0
        b_cfi = 0
        b_vid = 32
        b_ethertype = ether.ETH_TYPE_8021Q
        bt = vlan.svlan(b_pcp, b_cfi, b_vid, b_ethertype)

        c_src_mac = '11:11:11:11:11:11'
        c_dst_mac = 'aa:aa:aa:aa:aa:aa'
        c_ethertype = ether.ETH_TYPE_8021AD
        e2 = ethernet.ethernet(c_dst_mac, c_src_mac, c_ethertype)

        s_pcp = 0
        s_cfi = 0
        s_vid = 32
        s_ethertype = ether.ETH_TYPE_8021Q
        st = vlan.svlan(s_pcp, s_cfi, s_vid, s_ethertype)

        c_pcp = 0
        c_cfi = 0
        c_vid = 32
        c_ethertype = ether.ETH_TYPE_IP
        ct = vlan.vlan(c_pcp, c_cfi, c_vid, c_ethertype)

        version = 4
        header_length = 20
        tos = 0
        total_length = 24
        identification = 0x8a5d
        flags = 0
        offset = 1480
        ttl = 64
        proto = inet.IPPROTO_ICMP
        csum = 0xa7f2
        src = '131.151.32.21'
        dst = '131.151.32.129'
        option = 'TEST'
        ip = ipv4.ipv4(version, header_length, tos, total_length,
                       identification, flags, offset, ttl, proto, csum,
                       src, dst, option)

        p = packet.Packet()

        p.add_protocol(e1)
        p.add_protocol(bt)
        p.add_protocol(self.it)
        p.add_protocol(e2)
        p.add_protocol(st)
        p.add_protocol(ct)
        p.add_protocol(ip)
        p.serialize()

        return p
 def ICMPPacket(self, datapath, in_port, pkt_ethernet, pkt_ipv4, pkt_icmp):
     if pkt_icmp.type == icmp.ICMP_ECHO_REQUEST:
         eer=ethernet.ethernet(ethertype=pkt_ethernet.ethertype,
                     dst=pkt_ethernet.src,
                     src=self.interfaces_virtuales[self.tabla_vlan[in_port]][0])
                     
         iper=ipv4.ipv4(dst=pkt_ipv4.src,
                 src=self.interfaces_virtuales[self.tabla_vlan[in_port]][2],
                 proto=pkt_ipv4.proto)
Beispiel #55
0
    def test_default_args(self):
        prev = ipv4(proto=inet.IPPROTO_UDP)
        u = udp()
        buf = u.serialize(bytearray(), prev)
        res = struct.unpack(udp._PACK_STR, buf)

        eq_(res[0], 1)
        eq_(res[1], 1)
        eq_(res[2], udp._MIN_LEN)
    def _handle_icmp(self, msg, pkt, icmp_pkt):
        """
            reply to ICMP_ECHO_REQUEST(i.e. ping);
            may handle other types of ICMP msg in the future;
            return True if send a response
        """
        LOG.debug('Handling ICMP packet %s', icmp_pkt)

        if icmp_pkt.type != icmp.ICMP_ECHO_REQUEST:
            return False

        in_port_no = msg.in_port
        switch = self.dpid_to_switch[msg.datapath.id]
        ipv4_layer = self.find_packet(pkt, 'ipv4')
        ip_src = netaddr.IPAddress(ipv4_layer.src)
        ip_dst = netaddr.IPAddress(ipv4_layer.dst)

        if ip_dst == netaddr.IPAddress(util.bgper_config['local_ipv4']):
            self.write_to_tap(pkt.data, modifyMacAddress=True)
            LOG.debug('Forward ICMP packet to tap port.')
            return True

        need_reply = False
        for _k, p in switch.ports.iteritems():
            if p.gateway and p.gateway.gw_ip == ip_dst:
                need_reply = True
                break
        if not need_reply:
            return False

        echo_id = icmp_pkt.data.id
        echo_seq = icmp_pkt.data.seq
        echo_data = bytearray(icmp_pkt.data.data)

        icmp_data = icmp.echo(id_=echo_id, seq=echo_seq, data=echo_data)

        #send a echo reply packet
        ether_layer = self.find_packet(pkt, 'ethernet')
        ether_dst = ether_layer.src
        ether_src = str(switch.ports[in_port_no].hw_addr)
        e = ethernet.ethernet(ether_dst, ether_src, ether.ETH_TYPE_IP)
        #csum calculation should be paid attention to
        i = ipv4.ipv4(version=4, header_length=5, tos=0, total_length=0,
            identification=0, flags=0x000, offset=0, ttl=64, proto=1, csum=0,
            src=str(ip_dst), dst=str(ip_src), option=None)
        ic = icmp.icmp(type_=0, code=0, csum=0, data=icmp_data)
        p = packet.Packet()
        p.add_protocol(e)
        p.add_protocol(i)
        p.add_protocol(ic)
        p.serialize()
        datapath = msg.datapath
        datapath.send_packet_out(in_port=ofproto_v1_0.OFPP_NONE,
                actions=[datapath.ofproto_parser.OFPActionOutput(in_port_no)],
                data=p.data)
        LOG.debug('Ping replied %s -> %s', ip_dst, ip_src)
        return True
Beispiel #57
0
    def packet_in_handler(self, event):
        message = event.msg
        datapath = message.datapath
        protocol = datapath.ofproto
        parser = datapath.ofproto_parser
        in_port = message.match['in_port']

        pkt = packet.Packet(message.data)
        eth = pkt.get_protocols(ethernet.ethernet)[0]
        ip4 = pkt.get_protocol(ipv4.ipv4)

        dst = eth.dst
        src = eth.src

        dpid = datapath.id
        self.mac_to_port.setdefault(dpid, {})


        self.mac_to_port[dpid][src] = in_port

        if dst in self.mac_to_port[dpid]:
            out_port = self.mac_to_port[dpid][dst]
        else:
            out_port = protocol.OFPP_FLOOD

        if ip4 is not None:
            self.logger.info("PacketIn(%s):[%s:(%s)]>>[%s:(%s)])", dpid, ip4.src, in_port, ip4.dst, out_port)

        """
        todo: if ipv4.dst == 202.45.128.181: output port
        """
        controlleraddress = ipv4.ipv4(dst="202.45.128.181")
        if ip4 is not None:
            if ip4.dst == controlleraddress.dst:
                out_port = 9
                # self.logger.info("202.45.128.181 address caught!")

        actions = [parser.OFPActionOutput(out_port)]

        if out_port != protocol.OFPP_FLOOD:
            match = parser.OFPMatch(in_port=in_port, eth_dst=dst)
            self.matchlist.append(match)
            self.insertflow(datapath, self.table_id, 2, match, actions)
            # self.logger.info("matches: %s", match)

        for m in self.matchlist:
            self.logger.info("matches: %s", m)
            self.send_flow_stats_request(datapath, m)

        data = None
        if message.buffer_id == protocol.OFP_NO_BUFFER:
            data = message.data

        packetout = parser.OFPPacketOut(datapath=datapath,
            buffer_id=message.buffer_id, in_port=in_port, actions=actions, data=data)
        datapath.send_msg(packetout)
Beispiel #58
0
    def assemble_ack(cls, pkt, datapath, port):
        req_eth = pkt.get_protocol(ethernet.ethernet)
        req_ipv4 = pkt.get_protocol(ipv4.ipv4)
        req_udp = pkt.get_protocol(udp.udp)
        req = pkt.get_protocol(dhcp.dhcp)

        wanted_ip = cls.get_option_value(req, 50)
        src = req_eth.src
        got_ip = None
        if src in cls.wan_leases[datapath]:
            if wanted_ip != cls.wan_leases[datapath][src]:
                cls.wan_pool.append(cls.wan_leases[datapath][src])
                del cls.wan_leases[datapath][src]
            else:
                got_ip = cls.wan_leases[datapath][src]
        if got_ip is None:
            if src in cls.wan_offers[datapath]:
                if wanted_ip != cls.wan_offers[datapath][src]:
                    cls.wan_pool.append(cls.wan_offers[datapath][src])
                    del cls.wan_offers[datapath][src]
                else:
                    got_ip = cls.wan_offers[datapath][src]
        if got_ip is None:
            if wanted_ip in cls.wan_pool[datapath]:
                cls.wan_pool[datapath].remove(wanted_ip)
                got_ip = wanted_ip
        if got_ip is None:
            # cls.log.warn("%s asked for un-offered %s", src, wanted_ip)
            # cls.nak(event) # nak 
            return

        req.options.option_list.remove(next(opt for opt in req.options.option_list if opt.tag == 53))
        req.options.option_list.insert(0, dhcp.option(tag=1, value=cls.bin_netmask))
        req.options.option_list.insert(0, dhcp.option(tag=3, value=addrconv.ipv4.text_to_bin(cls.dhcp_server[datapath])))
        req.options.option_list.insert(0, dhcp.option(tag=6, value=cls.bin_dns))
        req.options.option_list.insert(0, dhcp.option(tag=51, value='8640'))
        req.options.option_list.insert(0, dhcp.option(tag=53, value='05'.decode('hex')))
        req.options.option_list.insert(0, dhcp.option(tag=54, value=addrconv.ipv4.text_to_bin(cls.dhcp_server[datapath])))

        ack_pkt = packet.Packet()
        ack_pkt.add_protocol(ethernet.ethernet(ethertype=req_eth.ethertype, dst=src, src=cls.hw_addr))
        ack_pkt.add_protocol(ipv4.ipv4(dst=req_ipv4.dst, src=cls.dhcp_server[datapath], proto=req_ipv4.proto))
        ack_pkt.add_protocol(udp.udp(src_port=67,dst_port=68))
        ack_pkt.add_protocol(dhcp.dhcp(op=2, chaddr=src,
                                       hlen=6, # salah di len
                                       siaddr=cls.dhcp_server[datapath],
                                       boot_file=req.boot_file,
                                       yiaddr=wanted_ip,
                                       xid=req.xid,
                                       options=req.options))
        # cls.logger.info("ASSEMBLED ACK: %s" % ack_pkt)


        # print(wanted_ip, src, datapath, port)
        cls.add_arp(wanted_ip, src, datapath, port)
        return ack_pkt
 def _handle_icmp(self, datapath, port, pkt_ethernet, pkt_ipv4, pkt_icmp):
     if pkt_icmp.type != icmp.ICMP_ECHO_REQUEST:
         return
     pkt = packet.Packet()
     pkt.add_protocol(ethernet.ethernet(ethertype=pkt_ethernet.ethertype, dst=pkt_ethernet.src, src=self.hw_addr))
     pkt.add_protocol(ipv4.ipv4(dst=pkt_ipv4.src, src=self.ip_addr, proto=pkt_ipv4.proto))
     pkt.add_protocol(
         icmp.icmp(type_=icmp.ICMP_ECHO_REPLY, code=icmp.ICMP_ECHO_REPLY_CODE, csum=0, data=pkt_icmp.data)
     )
     self._send_packet(datapath, port, pkt)