Beispiel #1
0
 def f_nat_forward_packet(self,vid,packet_in,new_dst_ip,new_dst_mac,forward_port,new_src_ip=None):    
     msg = of.ofp_packet_out(in_port=packet_in.in_port)               
     msg.data = packet_in
     '''set new src IP'''
     if new_src_ip:
         msg.actions.append(of.ofp_action_nw_addr.set_src(IPAddr(new_src_ip)))
     '''set new dst IP'''
     if new_dst_ip:
         msg.actions.append(of.ofp_action_nw_addr.set_dst(IPAddr(new_dst_ip)))
     if new_dst_mac:
         msg.actions.append(of.ofp_action_dl_addr.set_dst(EthAddr(new_dst_mac)))
     '''add VLAN ID'''
     if vid:
         msg.actions.append(of.ofp_action_set_vlan_vid(vlan_vid=vid))    
       
     msg.actions.append(of.ofp_action_output(port = forward_port))
     #msg.buffer_id = <some buffer id, if any>
     msg.cookie = 100
     self.connection.send(msg)
Beispiel #2
0
def Arp_Flood(arp_packet):
    #construct arp request packet
    arp_request = arp()
    arp_request.hwsrc = arp_packet.hwsrc  #Special_MAC
    arp_request.hwdst = arp_packet.hwdst  #EthAddr(b"\xff\xff\xff\xff\xff\xff")
    arp_request.opcode = arp.REQUEST
    arp_request.protosrc = arp_packet.protosrc
    arp_request.protodst = arp_packet.protodst
    ether = ethernet()
    ether.type = ethernet.ARP_TYPE
    ether.dst = EthAddr(b"\xff\xff\xff\xff\xff\xff")
    ether.src = Special_MAC
    ether.payload = arp_request

    msg = of.ofp_packet_out()
    msg.data = ether.pack()
    msg.actions.append(of.ofp_action_output(port=of.OFPP_FLOOD))
    for connection in core.openflow.connections:
        connection.send(msg)
Beispiel #3
0
    def __init__(self, t, r, mode):
        self.switches = {}  # Switches seen: [dpid] -> Switch
        self.t = t  # Master Topo object, passed in and never modified.
        self.r = r  # Master Routing object, passed in and reused.
        self.mode = mode  # One in MODES.
        self.macTable = {}  # [mac] -> (dpid, port)
        # If you want to send to dst, then send down self.macTable[dst] dpid, port
        graph = self.t._graph

        for sw in self._raw_dpids(t.layer_nodes(t.LAYER_EDGE)):
            sw_name = t.id_gen(dpid=sw).name_str()
            for host in t.down_nodes(sw_name):
                host_mac = EthAddr(t.id_gen(name=host).mac_str())
                sw_port, _ = t.port(sw_name, host)
                self.macTable[host_mac] = (sw, sw_port)

        # TODO: generalize all_switches_up to a more general state machine.
        self.all_switches_up = False  # Sequences event handling.
        core.openflow.addListeners(self, priority=0)
Beispiel #4
0
 def test_from_json(self):
     # Arrange
     hw_addr_str = "11:22:33:44:55:66"
     hw_addr = EthAddr(hw_addr_str)
     ip_str = "127.0.0.1"
     ip = IPAddr(ip_str)
     name = "eth0"
     input_json = {
         '__type__': 'sts.entities.hosts.HostInterface',
         'name': name,
         'ips': [ip],
         'hw_addr': hw_addr_str
     }
     # Act
     interface = HostInterface.from_json(input_json)
     # Assert
     self.assertEquals(interface.hw_addr, hw_addr)
     self.assertEquals(interface.ips, [ip])
     self.assertEquals(interface.name, name)
 def _send_ping (self, src_dpid, src_port, dst_mac, dst_ip):
   """
   Builds an ETH/IP any-to-any ARP packet (an "ARP ping")
   """
   if src_port < 0:
     return
   r = arp()
   r.opcode = arp.REQUEST
   r.hwdst = EthAddr(dst_mac)
   r.hwsrc = core.host_tracker.ping_src_mac
   r.protodst = IPAddr(dst_ip)
   # src is IP_ANY
   e = ethernet(type=ethernet.ARP_TYPE, src=r.hwsrc, dst=r.hwdst)
   e.payload = r
   log.debug("%i %i sending ARP REQ to %s %s",
             src_dpid, src_port, str(r.hwdst), str(r.protodst))
   msg = of.ofp_packet_out(data = e.pack(),
                           action = of.ofp_action_output(port=src_port))
   core.openflow.sendToDPID(src_dpid, msg.pack())
Beispiel #6
0
def send_arp_request(connection,
                     ip,
                     port=of.OFPP_FLOOD,
                     src_mac=None,
                     src_ip=None):
    """
  Send an ARP request

  src_mac can be None to use the "DPID MAC" or True to use the port Mac.
    (or it can be an EthAddr)
  """
    if src_mac is None:
        src_mac = connection.eth_addr
    elif src_mac is True:
        if port in (of.OFPP_FLOOD, of.OFPP_ALL):
            for p in connection.ports.values():
                if p.config & OFPPC_NO_FLOOD:
                    if port == of.ofPP_FLOOD:
                        continue
                if p.port_no < 0: continue
                if p.port_no > of.OFPP_MAX: continue  # Off by one?
                send_arp_request(connection,
                                 ip,
                                 p.port_no,
                                 src_mac=p.hw_addr,
                                 src_ip=src_ip)
            return
        src_mac = connection.ports[port].hw_addr
    else:
        src_mac = EthAddr(src_mac)
    r = arp()
    r.opcode = r.REQUEST
    r.hwdst = ETHER_BROADCAST
    r.protodst = IPAddr(ip)
    r.hwsrc = src_mac
    r.protosrc = IPAddr("0.0.0.0") if src_ip is None else IPAddr(src_ip)
    e = ethernet(type=ethernet.ARP_TYPE, src=src_mac, dst=r.hwdst)
    e.payload = r
    msg = of.ofp_packet_out()
    msg.data = e.pack()
    msg.actions.append(of.ofp_action_output(port=port))
    msg.in_port = of.OFPP_NONE
    connection.send(msg)
Beispiel #7
0
    def _handle_ConnectionUp(self, event):
        log.debug("Connection %s %s" %
                  (event.connection, dpidToStr(event.dpid)))

        self.dpid = event.dpid
        self.ports = {}

        for p in event.ofp.ports:
            if p.port_no != of.OFPP_CONTROLLER and p.port_no != of.OFPP_LOCAL:
                self.ports[p.port_no] = {'hw_addr': p.hw_addr, 'name': p.name}

        msg = of.ofp_flow_mod()
        msg.match = of.ofp_match()
        msg.match.in_port = 1
        msg.idle_timeout = 0
        msg.hard_timeout = 0
        msg.buffer_id = of.NO_BUFFER

        case = 2

        if case == 1:
            msg.actions.append(vof.viro_action_pop_fd())
            msg.actions.append(
                of.ofp_action_dl_addr.set_dst(
                    dl_addr=EthAddr("01:01:01:01:01:01")))
            # msg.actions.append(of.ofp_action_nw_addr.set_dst(nw_addr = IPAddr("10.0.0.1")))
        elif case == 2:
            msg.actions.append(
                vof.viro_action_push_fd(fd=vof.viro_addr(0x01, 0x02)))

            msg.actions.append(vof.viro_action_vid_sw.set_fd(0x0a0b0c0d))
            msg.actions.append(vof.viro_action_vid_host.set_fd(0x0e0f))

            msg.actions.append(vof.viro_action_vid_sw.set_dst(0x01020304))
            msg.actions.append(vof.viro_action_vid_host.set_dst(0x1122))

            msg.actions.append(vof.viro_action_vid_sw.set_src(0x05060708))
            msg.actions.append(vof.viro_action_vid_host.set_src(0x3344))

        msg.actions.append(of.ofp_action_output(port=2))

        event.connection.send(msg)
Beispiel #8
0
    def test_from_json(self):
        # Arrange
        json_dict = {
            '__type__':
            'sts.entities.hosts.NamespaceHost',
            'cmd':
            '/bin/bash sleep',
            'name':
            'h1',
            'hid':
            1,
            'interfaces': [{
                '__type__': 'sts.entities.hosts.HostInterface',
                'hw_addr': '0e:32:a4:91:e7:30',
                'ips': ['192.168.56.2'],
                'name': 'test-host'
            }]
        }

        io_master = mock.Mock()
        hw_addr_str = "0e:32:a4:91:e7:30"
        ip_str = "192.168.56.2"
        hw_addr = EthAddr(hw_addr_str)
        ip = IPAddr(ip_str)
        ifname = "test-host"
        interface = HostInterface(hw_addr, ip, name=ifname)
        hname = "h1"
        hid = 1
        cmd = '/bin/bash sleep'
        # Mocking external dependencies
        import sts.util.network_namespace as ns
        ns.launch_namespace = mock.Mock(return_value=(None, hw_addr_str, None))
        ns.bind_raw_socket = mock.Mock(return_value=None)
        # Act
        host = NamespaceHost.from_json(json_dict,
                                       io_master.create_worker_for_socket)
        # Assert
        self.assertEquals(host.name, hname)
        self.assertEquals(host.hid, hid)
        self.assertEquals(host.cmd, cmd)
        self.assertEquals(len(host.interfaces), 1)
        self.assertEquals(host.interfaces[0].to_json(), interface.to_json())
Beispiel #9
0
    def _handle_PacketIn(self, event):
        """
    Packets not handled by the router rules will be
    forwarded to this method to be handled by the controller
    """

        packet = event.parsed  # This is the parsed packet data.
        if not packet.parsed:
            log.warning("Ignoring incomplete packet")
            return

        packet_in = event.ofp  # The actual ofp_packet_in message.
        print("Unhandled packet from " + str(self.connection.dpid) + ":" +
              packet.dump())

        # save the port number
        port_in = event.port
        # set an arbitrary ethaddr for cores21
        cores21_Addr = EthAddr("01:02:03:04:05:06")

        if packet.type == packet.ARP_TYPE and packet.payload.opcode == arp.REQUEST:
            # create reply message
            arp_reply = arp()
            arp_reply.hwsrc = cores21_Addr
            arp_reply.hwdst = packet.src
            arp_reply.opcode = arp.REPLY
            arp_reply.protosrc = packet.next.protodst
            arp_reply.protodst = packet.next.protosrc

            # wrap in ethernet wrapper
            ether = ethernet()
            ether.type = ethernet.ARP_TYPE
            ether.dst = packet.src
            ether.src = cores21_Addr
            msg = of.ofp_flow_mod()
            msg.match.dl_type = 0x0800
            msg.match.nw_dst = packet.next.protosrc
            msg.actions.append(of.ofp_action_dl_addr.set_dst(packet.src))
            msg.actions.append(of.ofp_action_output(port=port_in))
            self.connection.send(msg)
            ether.set_payload(arp_reply)
            self.resend_packet(ether, port_in)
Beispiel #10
0
 def test_init(self, SwitchCls):
     # Arrange
     sw1 = SwitchCls()
     sw1.dpid = 1
     # It's really hard to mock this, because of using assert_type
     p1 = ofp_phy_port(port_no=1)
     hw_addr_str = "11:22:33:44:55:66"
     hw_addr = EthAddr(hw_addr_str)
     ip_str = "127.0.0.1"
     ip = IPAddr(ip_str)
     ifname = "eth0"
     interface = HostInterface(hw_addr, ip, name=ifname)
     hname = "h1"
     hid = 1
     host = Host(interface, name=hname, hid=hid)
     # Act
     link = AccessLink(host, interface, sw1, p1)
     # Assert
     self.assertEquals(link.host, host)
     self.assertEquals(link.interface, interface)
Beispiel #11
0
def _handle_PacketIn(event):
    dpid = event.dpid
    inport = event.port
    packet = event.parsed
    log.info('Pacote de ' + str(dpid_to_mac(dpid)))

    net = packet.next  # Camada de rede
    transp = packet.next.next  # Camada de transporte

    if not packet.parsed:
        log.info("Pacote not Parsed")
        return
    #if packet.type == ethernet.LLDPTYPE:
    #.info("Pacote LLDPTYPE")
    #return
    if isinstance(net, ipv4):
        log.info("Pacote IPv4")
        #log.info("Estou aqui!!")
        if str(dpid_to_mac(dpid)) == '00:00:00:00:00:01':
            msg = of.ofp_flow_mod()
            msg.match.dl_src = EthAddr('00:00:00:00:01:01')
            msg.match.dl_dst = EthAddr('00:00:00:00:03:11')
            msg.actions.append(of.ofp_action_output(port=13))
            event.connection.send(msg)

            msg2 = of.ofp_flow_mod()
            msg2.match.dl_dst = EthAddr('00:00:00:00:01:01')
            msg2.actions.append(of.ofp_action_output(port=1))
            event.connection.send(msg2)
            #log.info(msg)
        elif str(dpid_to_mac(dpid)) == '00:00:00:00:00:03':
            msg = of.ofp_flow_mod()
            msg.match.dl_src = EthAddr('00:00:00:00:03:11')
            msg.match.dl_dst = EthAddr('00:00:00:00:01:01')
            msg.actions.append(of.ofp_action_output(port=11))
            event.connection.send(msg)

            msg2 = of.ofp_flow_mod()
            msg2.match.dl_dst = EthAddr('00:00:00:00:03:11')
            msg2.actions.append(of.ofp_action_output(port=1))
            event.connection.send(msg2)
            #log.info(msg)

    elif isinstance(net, arp):
        log.info("Pacote ARP")
        return
    else:
        #log.info("Aconteceu nada!!")
        return
Beispiel #12
0
        def forward (message = None):
            this_dpid = dpid_to_str(event.dpid)

            if packet.dst.is_multicast:
                flood()
                return
            else:
                log.debug("Got unicast packet for %s at %s (input port %d):",
                          packet.dst, dpid_to_str(event.dpid), event.port)

                try:
                    if event.parsed.find('arp') or event.parsed.find('icmp'):
                        #log.debug("ARP packet type has no transport ports, flooding.")
                        install_fwdrule(event,packet,of.OFPP_FLOOD)
                    elif event.parsed.find('tcp'):
                        if tcpp.dstport == 80:
                            outport = self.portmap[(this_dpid, EthAddr(packet.src),EthAddr(packet.dst), tcpp.dstport)]
                            install_fwdrule(event, packet, outport)
                        elif tcpp.srcport == 80:
                            outport = self.portmap[(this_dpid, EthAddr(packet.src),EthAddr(packet.dst), tcpp.srcport)]
                            install_fwdrule(event, packet, outport)
                        elif tcpp.dstport == 22:
                            outport = self.portmap[(this_dpid, EthAddr(packet.src),EthAddr(packet.dst), tcpp.dstport)]
                            install_fwdrule(event, packet, outport)                            
                        elif tcpp.srcport == 22:
                            outport = self.portmap[(this_dpid, EthAddr(packet.src),EthAddr(packet.dst), tcpp.srcport)]
                            install_fwdrule(event, packet, outport)                            
                            
                            
                        log.debug("Sw: %s adding rule Src: %s Dst: %s Dport: %s out port: %d", this_dpid, packet.src, packet.dst, tcpp.dstport, outport)
                
                except KeyError:
                    log.debug("TCP packet type has no transport ports, flooding.")
                    install_fwdrule(event,packet,of.OFPP_FLOOD)
                except AttributeError:
                    log.debug("Generic packet type has no transport ports, flooding.")

                    # flood and install the flow table entry for the flood
                    install_fwdrule(event,packet,of.OFPP_FLOOD)
Beispiel #13
0
    def __init__(self, ping_src_mac=None, install_flow=True, eat_packets=True):

        if ping_src_mac is None:
            ping_src_mac = DEFAULT_ARP_PING_SRC_MAC

        self.ping_src_mac = EthAddr(ping_src_mac)
        self.install_flow = install_flow
        self.eat_packets = eat_packets

        # The following tables should go to Topology later
        self.entryByMAC = {}
        self._t = Timer(timeoutSec['timerInterval'],
                        self._check_timeouts,
                        recurring=True)

        # Listen to openflow with high priority if we want to eat our ARP replies
        listen_args = {}
        if eat_packets:
            listen_args = {'openflow': {'priority': 0}}
        core.listen_to_dependencies(self, listen_args=listen_args)
Beispiel #14
0
    def _handle_ConnectionUp(self, event):
        switch = 's' + str(event.dpid)
        ports = self._getPortMapping(switch)

        for host, (ip, mac) in hostMappings.iteritems():
            port = ports[host]
            print switch, host, ip, mac, port

            msg_mac = of.ofp_flow_mod()
            msg_mac.match.dl_dst = EthAddr(mac)
            msg_mac.actions.append(of.ofp_action_output(port=port))
            event.connection.send(msg_mac)

            msg_ip = of.ofp_flow_mod()
            msg_ip.match.nw_dst = IPAddr(ip)
            msg_ip.match.dl_type = 2054
            msg_ip.actions.append(of.ofp_action_output(port=port))
            event.connection.send(msg_ip)

        log.debug("Dijkstra installed on %s", dpidToStr(event.dpid))
Beispiel #15
0
 def _handle_ConnectionUp(self, event):
     log.debug("dpid %d: connection is up" % event.dpid)
     dpid = event.dpid
     ip = IPAddr('10.0.%d.1' % dpid)
     mac = EthAddr("%012x" %
                   (event.dpid & 0xffffffffffff | 0x0000000000f0, ))
     self.routerIP[dpid] = ip
     if dpid not in self.connections:
         self.connections[dpid] = event.connection
     if dpid not in self.arpTable:
         self.arpTable[dpid] = {}
     if dpid not in self.routingTable:
         self.routingTable[dpid] = {}
     if dpid not in self.arpWait:
         self.arpWait[dpid] = {}
     self.arpTable[dpid][ip] = mac
     log.debug("dpid %d: adding mac %s IP %s as router" % (dpid, mac, ip))
     if len(self.routerIP) == 2:
         self.handleArpRequest(ip, IPAddr('10.0.%d.1' % (3 - event.dpid)),
                               mac, of.OFPP_FLOOD, dpid)
    def _handle_PacketIn(self, event):
        dpid = event.connection.dpid

        inport = event.port
        packet = copy.deepcopy(event.parsed)
        if not packet.parsed:
            log.warning("%i %i ignoring unparsed packet", dpid, inport)
            return

        if dpid not in self.arpTable:
            # New switch -- create an empty table
            self.arpTable[dpid] = {}
            for fake in self.fakeways:
                self.arpTable[dpid][IPAddr(fake)] = Entry(
                    of.OFPP_NONE, dpid_to_mac(dpid))

        # store the mac, ip info of the DNS SERVER into arpTable
        self.arpTable[dpid][IPAddr(IP_OF_DNS_SERVER)] = Entry(
            6633, EthAddr(MAC_OF_DNS_SERVER))

        if packet.type == ethernet.LLDP_TYPE:
            # Ignore LLDP packets
            return

        global s1_dpid, s2_dpid, s3_dpid, s4_dpid, s5_dpid, s6_dpid, s7_dpid, s8_dpid, s9_dpid, s10_dpid
        global v_ip
        if v_ip is None:
            v_ip = self.v_ip
        packet = event.parsed

        ap = packet.find('arp')
        icm = packet.find('icmp')

        if ap:
            _arp_output(event.connection.dpid, ap.protodst, event,
                        self.out_port)

        if isinstance(packet.next, ipv4):
            _mut_forward(event.connection.dpid, packet.next.dstip,
                         packet.next.srcip, event, self.out_port, v_ip,
                         self.vip_rip_map)
    def __init__(self, connection, transparent):
        self.connection = connection
        self.transparent = transparent
        """DP Flow Table Register"""
        self.flowTabReg = []
        """MAC & IP Address Tables"""
        self.arp_table = {}
        self.mac_to_port = {}
        self.mac_to_ip = {}
        self.addr = 2

        ips = check_output(["hostname", "-I"]).split()
        macs = re.findall(
            r"[\w\W\d]{2}:[\w\W\d]{2}:[\w\W\d]{2}:[\w\W\d]{2}:[\w\W\d]{2}:[\w\W\d]{2}",
            check_output(["ifconfig"]))

        for i in range(len(ips)):
            self.arp_table[IPAddr(ips[i])] = EthAddr(macs[i])

        connection.addListeners(self)
        self.hold_down_expired = _flood_delay == 0
        def forward (message = None):
            this_dpid = dpid_to_str(event.dpid)

            if packet.dst.is_multicast:
                flood()
                return
            else:
                log.debug("Got unicast packet for %s at %s (input port %d):",
                        packet.dst, dpid_to_str(event.dpid), event.port)

                try:
                    out_port = self.portmap(dpid_to_str(event.dpid), EthAddr(packet.src), EthAddr(packet.dst), event.port, tcpp)
                    print "out_port:", out_port
                    if out_port:
                        install_fwdrule(event,packet,out_port)

                except AttributeError:
                    log.debug("packet type has no transport ports, flooding")

                    # flood and install the flow table entry for the flood
                    install_fwdrule(event,packet,of.OFPP_FLOOD)
Beispiel #19
0
 def of_send_link_up(self, dpid, rmac):
     for connection in core.openflow.connections:
         if connection.dpid == dpid:
             # Parse rmac the OF way
             rmac = EthAddr(rmac)
             log.debug('Got you!')
             # Block in Node 1 incoming from node 2
             fm = of.ofp_flow_mod()
             fm.match.dl_src = rmac
             fm.command = of.OFPFC_DELETE
             # Many OpenVswitch  versions do not support OFPP_NONE
             # Instead of the no action is defined
             # hence an empty action
             #fm.actions.append(of.ofp_action_output( port=of.OFPP_NONE ))
             connection.send(fm)
             # Block in Node 1 outcoming to node 2
             fm = of.ofp_flow_mod()
             fm.match.dl_dst = rmac
             fm.command = of.OFPFC_DELETE
             #fm.actions.append(of.ofp_action_output( port=of.OFPP_NONE ))
             connection.send(fm)
Beispiel #20
0
    def send_proxied_arp_request(self, connection, ip):
        ARP = arp()
        ARP.opcode = arp.REQUEST
        ARP.hwsrc = self.lb_mac
        ARP.hwdst = EthAddr("ff:ff:ff:ff:ff:ff")
        ARP.protosrc = self.service_ip
        ARP.protodst = ip

        ETHERNET = ethernet(type=ethernet.ARP_TYPE,
                            src=ARP.hwsrc,
                            dst=ARP.hwdst)
        ETHERNET.set_payload(ARP)

        log.info("Sending ARP request " + str(ARP))

        msg = of.ofp_packet_out()
        msg.data = ETHERNET.pack()
        msg.actions.append(of.ofp_action_output(port=of.OFPP_FLOOD))
        msg.in_port = of.OFPP_NONE
        self.connection.send(msg)
        return
Beispiel #21
0
    def do_l2_learning(self, con, inport, packet):
        """Given a packet, learn the source and peg to a switch/inport 
    """
        # learn MAC on incoming port
        srcaddr = EthAddr(packet.src)
        #if ord(srcaddr[0]) & 1:
        #  return
        if self.st[con].has_key(srcaddr.toStr()):  # change to raw?
            # we had already heard from this switch
            dst = self.st[con][srcaddr.toStr()]  # raw?
            if dst[0] != inport:
                # but from a different port
                log.info('MAC has moved from ' + str(dst) + 'to' + str(inport))
            else:
                return
        else:
            log.info('learned MAC ' + srcaddr.toStr() +
                     ' on Switch %s, Port %d' % (con.dpid, inport))

        # learn or update timestamp of entry
        self.st[con][srcaddr.toStr()] = (inport, time(), packet)  # raw?
Beispiel #22
0
def pClient(username, mac, ip=""):
    # permit traffic from the client to the router - i.e. auth successful
    connection = core.openflow.getConnection(strToDPID(dpid))
    MAC = EthAddr(mac)
    IP = IPAddr(ip)
    vlan = getVLANs(ip)
    query = "INSERT into tbl_nac_session (username,mac_address,ip_address,start_dt) VALUES ('%s','%s','%s',now())" % (
        username, mac, ip)
    msg = None

    # note: if the openflow switch supports L3 matching in addition to L2 matching
    # note: matching on both will result in higher security - but not all support both.
    # note: if we match on L3 and ARP matching is not supported (see sPortal),
    # note: ARPs from the client will not flow to the router but rather to the portal
    # note: so it does not make sense to match on L3 unless we can also match on ARPs
    # note: but technically you could comment out "and dp_supports_arp_match" if you don't
    # note: care that ARPs from clients always go to your portal which runs proxy ARP
    if dp_supports_l3_match and dp_supports_arp_match:
        msg = of.ofp_flow_mod()
        msg.flags = of.OFPFF_SEND_FLOW_REM
        msg.idle_timeout = client_idle_timeout
        msg.priority = 32768
        msg.match.in_port = client_port_match
        msg.match.dl_src = MAC
        msg.match.dl_type = pkt.ethernet.IP_TYPE
        msg.match.nw_src = IP
        msg.actions.append(of.ofp_action_vlan_vid(vlan_vid=vlan['trusted']))
        msg.actions.append(of.ofp_action_output(port=router_port_action))
    else:
        msg = of.ofp_flow_mod()
        msg.flags = of.OFPFF_SEND_FLOW_REM
        msg.idle_timeout = client_idle_timeout
        msg.priority = 32768
        msg.match.dl_src = MAC
        msg.actions.append(of.ofp_action_vlan_vid(vlan_vid=vlan['trusted']))
        msg.actions.append(of.ofp_action_output(port=router_port_action))
    if msg:
        cursor = db.cursor()
        cursor.execute(query)
        connection.send(msg)
Beispiel #23
0
  def _handle_PacketIn (self, event):
    """
    Packets not handled by the router rules will be
    forwarded to this method to be handled by the controller
    """

    # arbitrary
    our_mac = EthAddr('00:00:00:00:00:07')

    packet = event.parsed # This is the parsed packet data.
    if not packet.parsed:
      log.warning("Ignoring incomplete packet")
      return

    if packet.type == 0x806:  # ARP
        a = packet.payload

        # install flow based on ARP: for all IP packets addressed
        # to a.protosrc (whoever sent the ARP), change the ethernet
        # header to theirs (a.hwsrc) and send it out on event.port
        # (where we recieved this ARP from)
        msg = of.ofp_flow_mod()
        msg.priority = 0
        msg.match.dl_type = 0x800  # IPv4
        msg.match.nw_dst = a.protosrc
        msg.actions.append(of.ofp_action_dl_addr.set_dst(a.hwsrc))
        msg.actions.append(of.ofp_action_output(port=event.port))
        self.connection.send(msg)

        # respond to the ARP with our MAC address so that we can handle
        # their IP traffic in the future
        a.opcode = 2 # REPLY
        tmp = a.protodst
        a.protodst = a.protosrc
        a.protosrc = tmp
        a.hwdst = a.hwsrc
        a.hwsrc = our_mac
        packet.dst = packet.src
        packet.src = our_mac
        self.resend_packet(packet, event.port)
def send_arp_request(connection,
                     ip,
                     port=of.OFPP_FLOOD,
                     src_mac=None,
                     src_ip=None):
    if src_mac is None:
        src_mac = _dpid_to_mac(connection.dpid)
    else:
        src_mac = EthAddr(src_mac)
    r = arp()
    r.opcode = r.REQUEST
    r.hwdst = ETHER_BROADCAST
    r.protodst = IPAddr(ip)
    r.hwsrc = src_mac
    r.protosrc = IPAddr("0.0.0.0") if src_ip is None else IPAddr(src_ip)
    e = ethernet(type=ethernet.ARP_TYPE, src=src_mac, dst=r.hwdst)
    e.payload = r
    msg = of.ofp_packet_out()
    msg.data = e.pack()
    msg.actions.append(of.ofp_action_output(port=port))
    msg.in_port = of.OFPP_NONE
    connection.send(msg)
Beispiel #25
0
    def arp_request(self, packet, src_ip, out_port, src_mac):

        p = arp()
        p.hwtype = arp.HW_TYPE_ETHERNET
        p.prototype = arp.PROTO_TYPE_IP
        p.hwlen = 6
        p.protolen = 4
        p.opcode = arp.REQUEST
        p.hwdst = EthAddr('ff:ff:ff:ff:ff:ff')
        p.hwsrc = src_mac
        #log.info('p.hwsrc is %s' %p.hwsrc)
        p.protodst = packet.payload.dstip
        #log.info('p.protodst is %s' %p.protodst)
        p.protosrc = src_ip
        #log.info('port is %s' %out_port)

        E = ethernet(type=ethernet.ARP_TYPE, src=p.hwsrc, dst=p.hwdst)
        #log.info('src is %s , %s' %(p.hwsrc,p.hwdst))
        E.payload = p
        #log.info("ARP request for %s" %(str(p.protodst)))

        self.resend_packet(E, of.OFPP_ALL)
    def _handle_PacketIn(self, event):
        packet = event.parsed
        if packet.type == ethernet.IPV6_TYPE: return  # Doesn't handle IPV6
        if packet.dst.is_multicast:
            #print "src/dst", packet.src, packet.next.protodst, ip_to_mac[packet.next.protodst.toStr()]
            packet.dst = EthAddr(ip_to_mac[packet.next.protodst.toStr()])

        srcname = mac_to_name(packet.src.toStr())
        dstname = mac_to_name(packet.dst.toStr())

        #print "Adding at sw ", self.switch_name, (srcname, dstname), p
        next = False
        destination = dstname
        for s in default_route[(srcname, dstname)]:
            if s == self.switch_name:  # Found current switch
                next = True
            elif next:
                destination = s
                break

        outport = 1
        for ethend in switch_ports[self.switch_name]:
            if ethend == destination:
                break
            else:
                outport += 1

        msg = of.ofp_flow_mod()
        msg.match = of.ofp_match.from_packet(packet, event.port)
        msg.match.tp_src = None
        msg.match.tp_dst = None
        msg.match.nw_dst = None
        msg.match.nw_src = None
        msg.idle_timeout = 0
        msg.hard_timeout = 0
        msg.actions.append(of.ofp_action_output(port=outport))
        print self.switch_name, "forwarding ", srcname, " to ", dstname, "at", outport
        msg.data = event.ofp
        self.connection.send(msg.pack())
Beispiel #27
0
 def _handle_ConnectionUp(self, event):
     log.debug("Connection %d is up" % event.dpid)
     dpid = event.dpid
     if dpid not in self.connections:
         self.connections[dpid] = event.connection
     if dpid not in self.arptable:
         self.arptable[dpid] = {}
     if dpid not in self.routingtable:
         self.routingtable[dpid] = {}
     if dpid not in self.arpwait:
         self.arpwait[dpid] = {}
     ip = IPAddr('10.0.%d.1' % dpid)
     mac = EthAddr("%012x" %
                   (event.dpid & 0xffffffffffff | 0x0000000000f0, ))
     self.routerIP[dpid] = ip
     self.arptable[dpid][ip] = mac
     log.debug("Router %d: adding MAC %s, IP %s as router" %
               (dpid, mac, ip))
     if len(self.routerIP) == 2:
         self.forward_arp_request(ip,
                                  IPAddr('10.0.%d.1' % (3 - event.dpid)),
                                  mac, of.OFPP_FLOOD, dpid)
Beispiel #28
0
 def check_device_status(self):
     remote_stream = ChangesStream(self.selected_db, heartbeat=True, since=self.last_seq, filter='homework-remote/devices_pox')
     for change in remote_stream:
         self.last_seq = change['seq']
         the_id = change['id']
         the_rev = change['changes'][0]['rev']
         doc = self.selected_db.open_doc(the_id, rev=the_rev)
         prompt = True if (doc['state'] == 'pending') else False
         doc_arr = [{'doc_id': the_id, 'doc_rev': the_rev, 'doc_collection': 'devices', 'action': 'edit'}]
         strings = self.get_history_strings(doc['device_name'],
                                            doc['action'])
         timestamp = doc['event_timestamp'] if 'event_timestamp' in doc else None
         add_history_item(strings['title'], strings['desc'],
                          docs=doc_arr,
                          undoable=True,
                          prompt=prompt,
                          ts=timestamp)
         device = {'mac': EthAddr(doc['mac_address']),
                   'action': doc['action']}
         devices = [device]
         self.raiseEvent(DeviceStateChange(devices))
     core.callDelayed(1, self.check_device_status)
Beispiel #29
0
  def __init__ (self, connection, transparent):
    # Switch we'll be adding L2 learning switch capabilities to
    self.connection = connection
    self.transparent = transparent

    # Our table
    self.macToPort = {}

    # Our firewall table in the form of Dictionary
    self.firewall = {}

    # Add a Couple of Rules Static entries
    # Two type of rules: (srcip,dstip) or (dstip,dstport)
    self.AddRule(dpid_to_str(connection.dpid), EthAddr('00:00:00:00:00:02'), 0, 0, 0)
    self.AddRule(dpid_to_str(connection.dpid), 0, IPAddr('10.0.0.1'), IPAddr('10.0.0.4'),0)
    self.AddRule(dpid_to_str(connection.dpid), 0, 0, IPAddr('10.0.0.3'), 80)

    # We want to hear PacketIn messages, so we listen
    # to the connection
    connection.addListeners(self)

    # We just use this to know when to log a helpful message
    self.hold_down_expired = _flood_delay == 0
Beispiel #30
0
def launch(dpid, port, port_eth=None, name=None, __INSTANCE__=None):
    """
  Launch

  port_eth unspecified: "DPID MAC"
  port_eth enabled: Port MAC
  port_eth specified: Use that
  """
    if port_eth in (True, None):
        pass
    else:
        port_eth = EthAddr(port_eth)

    dpid = str_to_dpid(dpid)
    try:
        port = int(port)
    except:
        pass

    def dhcpclient_init():
        n = name
        if n is None:
            s = ''
            while True:
                if not core.hasComponent("DHCPClient" + s):
                    n = "DHCPClient" + s
                    break
                s = str(int('0' + s) + 1)
        else:
            if core.hasComponent(n):
                self.log.error("Already have component %s", n)
                return

        client = DHCPClient(port=port, dpid=dpid, name=n, port_eth=port_eth)
        core.register(n, client)

    core.call_when_ready(dhcpclient_init, ['openflow'])