def fwd(target, duration=(RULE_DURATION_SEC, RULE_DURATION_SEC)): if not isinstance(duration, tuple): duration = (duration, duration) # srcip -> dstip msg = of.ofp_flow_mod() #msg.match = of.ofp_match.from_packet(packet) msg.match = of.ofp_match(dl_type=0x800, nw_src=ip.srcip, nw_dst=ip.dstip) msg.idle_timeout = duration[0] msg.hard_timeout = duration[1] msg.actions.append(of.ofp_action_nw_addr.set_dst(target)) msg.actions.append(of.ofp_action_output(port=of.OFPP_FLOOD)) event.connection.send(msg) # target -> srcip msg = of.ofp_flow_mod() msg.match = of.ofp_match(dl_type=0x800, nw_src=target, nw_dst=ip.srcip) msg.idle_timeout = duration[0] msg.hard_timeout = duration[1] msg.actions.append(of.ofp_action_nw_addr.set_src(ip.dstip)) msg.actions.append(of.ofp_action_output(port=of.OFPP_FLOOD)) event.connection.send(msg) # send this pkt msg = of.ofp_packet_out() msg.actions.append(of.ofp_action_nw_addr.set_dst(target)) msg.actions.append(of.ofp_action_output(port=of.OFPP_FLOOD)) msg.data = event.ofp msg.in_port = event.port event.connection.send(msg)
def flow_add(): my_match = of.ofp_match() my_match.nw_src = IPAddr("10.0.0.2") my_match.nw_dst = IPAddr("10.0.0.3") my_match.dl_type=0x800 msg = of.ofp_flow_mod() msg.match = my_match msg.actions.append(of.ofp_action_nw_addr.set_src(IPAddr("10.0.0.4"))) log.info("msg builded") for conn in core.openflow.connections: log.info("in connections loop") conn.send(msg) match_2 = of.ofp_match() match_2.nw_src = IPAddr("10.0.0.1") match_2.nw_dst = IPAddr("10.0.0.4") match_2.dl_type = 0x800 msg2 = of.ofp_flow_mod() msg2.match = match_2 msg2.actions.append(of.ofp_action_nw_addr.set_dst(IPAddr("10.0.0.4"))) for conn in core.openflow.connections: conn.send(msg2) match3 = of.ofp_match() match3.nw_src = IPAddr("10.0.0.4") match3.nw_dst = IPAddr("10.0.0.1") match3.dl_type = 0x800 msg3 = of.ofp_flow_mod() msg3.match = match3 msg3.actions.append(of.ofp_action_nw_addr.set_dst(IPAddr("10.0.0.2"))) for conn in core.openflow.connections: conn.send(msg3)
def update_server_address(self): match32 = of.ofp_match() #flow1 = of.ofp_flow_mod(match=match32) #flow1.priority = 65535 match32.nw_src='10.0.0.1' match32.nw_dst='10.0.0.5' match32.dl_type=0x800 match32.dl_type mac_addr2='00:00:00:00:00:04' ip_addr2='10.0.0.4' #mac_addr='00:00:00:00:00:06' #ip_addr='10.0.0.6' action11=of.ofp_action_dl_addr.set_dst(mac_addr2) action12=of.ofp_action_nw_addr.set_dst(ip_addr2) action13 = of.ofp_action_output(port=4) flow2 = of.ofp_flow_mod(match=match32) flow2.actions.append(action11) flow2.actions.append(action12) flow2.actions.append(action13) #action21=of.ofp_action_dl_addr.set_dst(mac_addr2) #action22=of.ofp_action_nw_addr.set_dst(ip_addr2) #action23 = of.ofp_action_output(port=4) #flow1.actions.append(action21) #flow1.actions.append(action22) #flow1.actions.append(action23) #flow1.actions.append(action4) #flow1.actions.append(action2) #flow1.actions.append(action3) self.my_config=Configuration() match = of.ofp_match() print "match.in_port" + str(match.in_port) print("*******************************************************I come here ***************************************************************************************") flow2.priority = 65535 self.my_config.add_flow_mod(flow2,1) core.consistent_update.update_config(self.my_config)
def verifyIdentity(self, mac_addr): """ retry authentication to check if is the same user who send packets """ mac_addr = checkMac(mac_addr) self.authenticatedToProgress(mac_addr) port = self.host_progress[mac_addr]['port'] #Ajout de 2 flux pour la gestion de 802.1x msg = of.ofp_flow_mod() msg.match = of.ofp_match() msg.match.dl_type= 0x888e msg.match.in_port = port msg.match.dl_src = mac_addr msg.priority = 200 action = of.ofp_action_output( port = of.OFPP_CONTROLLER ) msg.actions.append(action) self.connection.send(msg) self.host_progress[mac_addr]['match'].append(msg.match) msg = of.ofp_flow_mod() msg.match = of.ofp_match() msg.match.dl_type = 0x888e msg.match.in_port= of.OFPP_CONTROLLER msg.match.dl_dst = mac_addr action = of.ofp_action_output( port = port) msg.actions.append(action) msg.priority = 200 self.connection.send(msg) self.host_progress[mac_addr]['match'].append(msg.match) self.sendRequestIdentity(mac_addr, self.host_progress[mac_addr]['port'])
def _handle_ConnectionUp (self, event): policies = self.read_policies(policyFile) for policy in policies.itervalues(): # TODO: implement the code to add a rule to block the flow # between the source and destination specified in each policy # Note: The policy data structure has two fields which you can # access to turn the policy into a rule. policy.dl_src will # give you the source mac address and policy.dl_dst will give # you the destination mac address # Note: Set the priority for your rule to 20 so that it # doesn't conflict with the learning bridge setup #### Solution starts here: # Idea: If you don't specify any action in a openflow msg, # then matching packets will be dropped. # http://courses.engr.illinois.edu/cs538/assignments/a1.pdf match1 = of.ofp_match() match1.dl_src = policy.dl_src match1.dl_dst = policy.dl_dst msg1 = of.ofp_flow_mod() msg1.match = match1 event.connection.send(msg1) match2 = of.ofp_match() match2.dl_src = policy.dl_dst match2.dl_dst = policy.dl_src msg2 = of.ofp_flow_mod() msg2.match = match2 event.connection.send(msg2) log.debug("Firewall rules installed on %s", dpidToStr(event.dpid))
def AddFlowFromModel(self, flow): # add outgoing flow msg = of.ofp_flow_mod() msg.match = of.ofp_match() msg.match.dl_type = ethernet.IP_TYPE msg.match.nw_src = str(flow.internalip) msg.match.nw_dst = str(flow.externalip) msg.match.in_port = flow.internalport msg.idle_timeout = flow.idletime msg.hard_timeout = flow.hardtime msg.actions.append(of.ofp_action_output(port = flow.externalport)) log.debug("installing Manos Flow 1") self.connection.send(msg) # add incoming flow msg = of.ofp_flow_mod() msg.match = of.ofp_match() msg.match.dl_type = ethernet.IP_TYPE msg.match.nw_src = str(flow.externalip) msg.match.nw_dst = str(flow.internalip) msg.match.in_port = flow.externalport msg.idle_timeout = flow.idletime msg.hard_timeout = flow.hardtime msg.actions.append(of.ofp_action_output(port = flow.internalport)) log.debug("installing Manos Flow 2") self.connection.send(msg)
def _setup_data_fwd_flows(self, switch_id, dst_mac): """ Given a switch and dst_mac address, setup two flows for data forwarding on the switch and its peer switch if the two are not the same. If the same, setup only one flow. """ (peer_switch_id, peer_fwd_port) = (self.inception. mac_to_dpid_port[dst_mac]) peer_ip = self.inception.dpid_to_ip[peer_switch_id] # two switches are different, setup a first flow at switch if switch_id != peer_switch_id: fwd_port = self.inception.dpid_ip_to_port[(switch_id, peer_ip)] core.openflow.sendToDPID(switch_id, of.ofp_flow_mod( match=of.ofp_match(dl_dst=dst_mac), action=of.ofp_action_output(port=fwd_port), priority=priority.DATA_FWD)) LOGGER.info("Setup forward flow on switch=%s for dst_mac=%s", dpid_to_str(switch_id), dst_mac) # Setup flow at the peer switch core.openflow.sendToDPID(peer_switch_id, of.ofp_flow_mod( match=of.ofp_match(dl_dst=dst_mac), action=of.ofp_action_output(port=peer_fwd_port), priority=priority.DATA_FWD)) LOGGER.info("Setup forward flow on switch=%s for dst_mac=%s", dpid_to_str(peer_switch_id), dst_mac)
def _handle_PacketIn(event): packet = event.parsed packet_in = event.ofp if not packet: return src = str(packet.src) dst = str(packet.dst) # If the packet is from host side.. if packet_in.in_port == HOST_PORT: # Register the host to dpid mapping hst2swtch[src] = event.dpid swtch2hst[event.dpid] = src # log.info('Record from %s' % event.dpid) if dst in hst2swtch: target_swtch = hst2swtch[dst] if target_swtch == event.dpid: event.connection.send( of.ofp_flow_mod( action=of.ofp_action_output(port=HOST_PORT), match=of.ofp_match(dl_dst=packet.dst) )) # log.info('from %s to %s' % (event.dpid, str(dst))) return # Otherwise the packet is sent for next hop # Find the shortest path from current # switch to target switch # returns the next-hop switch next_dpid = switches[event.dpid].goTo(target_swtch) log.info('from %s to %s' % (event.dpid, next_dpid)) # l = str((next_dpid, event.dpid)) # lr = str((event.dpid, next_dpid)) # target_port = None # if l in lset: # (l1, p1, l2, p2) = lset[l] # target_port = lset[l][3] # elif lr in lset: # target = lset[l][1] # else: return # event.connection.send( of.ofp_flow_mod( # action=of.ofp_action_output(port=target_port), # match=of.ofp_match(dl_dst=packet.dst) # )) else: if dst == 'ff:ff:ff:ff:ff:ff': # timestamp = time.time() # log.info(str(timestamp) + 'From ARP_TYPE: ' + str(packet)) # log.info(str(timestamp) + 'From ARP_TYPE:' + str(packet_in)) ####################################### event.connection.send( of.ofp_flow_mod( action=of.ofp_action_output(port=of.OFPP_ALL), match=of.ofp_match(dl_dst=EthAddr('ff:ff:ff:ff:ff:ff')) ))
def __init__ (self, connection, transparent): # Switch we'll be adding L2 learning switch capabilities to self.connection = connection self.transparent = transparent # Check the type of the switch self.isEdgeSwitch = True # Create one thread to monitor the ARP packets on the ports. t = threading.Thread(target=self.monitorPorts, args = ()) t.start() # Switch Port ARP count Table self.portARPCount = {} # Our Switch table self.macToPort = {} # Mutex for port ARP count Table self.mutex = Lock() # 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 log.debug("Initializing LearningSwitch, transparent=%s", str(self.transparent)) # Now add entries to the switch for capturing ARP traffic at the controller. # This will send all ARP packets to the controller. msg = of.ofp_flow_mod() msg.match = of.ofp_match(dl_type = pkt.ethernet.ARP_TYPE); msg.idle_timeout = of.OFP_FLOW_PERMANENT; msg.hard_timeout = of.OFP_FLOW_PERMANENT; msg.priority = 10 msg.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) self.connection.send(msg) # Add flow entries to capture DHCP packets at the controller. # Send all DHCP packets to the controller. msg = of.ofp_flow_mod() msg.match = of.ofp_match(nw_proto = 17, tp_src = 67 , tp_dst = 68 ); msg.idle_timeout = of.OFP_FLOW_PERMANENT; msg.hard_timeout = of.OFP_FLOW_PERMANENT; msg.priority = 10 msg.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) self.connection.send(msg) # Register a handler for DHCP IP lease at the controller. # This is called when DHCP lease is given by the controller DHCP server. print "DCHP LISTENER ADDED\n" core.DHCPD.addListenerByName('DHCPLease',self._handle_dhcp_lease)
def installFlows(self): for conn in self.connections: log.debug(dpid_to_str(conn.dpid)) msg = of.ofp_flow_mod(action=of.ofp_action_output(port=2), match=of.ofp_match(dl_type=0x800, nw_dst="10.0.0.2")) conn.send(msg) msg = of.ofp_flow_mod(action=of.ofp_action_output(port=1), match=of.ofp_match(dl_type=0x800, nw_dst="10.0.0.1")) conn.send(msg) log.debug("Flows installed")
def Configure_FW1(self, event): # Forward DNS (UDP:53) to H3 match = of.ofp_match(dl_type = ETH_IP, nw_dst = HOST_DNS, nw_proto = PROTO_UDP, tp_dst = PORT_DNS) action = of.ofp_action_output(port = 2) msg = of.ofp_flow_mod(match = match, actions = [action], command = of.OFPFC_ADD) event.connection.send(msg) # Forward WEB (TCP:80) to H4 match = of.ofp_match(dl_type = ETH_IP, nw_dst = HOST_WEB, nw_proto = PROTO_TCP, tp_dst = PORT_WEB) action = of.ofp_action_output(port = 2) msg = of.ofp_flow_mod(match = match, actions = [action], command = of.OFPFC_ADD) event.connection.send(msg)
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: def return_port(s1, mac_1, mac_2, port) : if self.portmap.has_key((s1, mac_1, mac_2, port)) : return self.adjacency[s1][self.portmap[(s1, mac_1, mac_2, port)]] else : return self.other[(s1, mac_2)] s1 = dpid_to_str(event.dpid) mac_1 = EthAddr(packet.src) mac_2 = EthAddr(packet.dst) if not tcpp: install_fwdrule(event, packet, of.OFPP_FLOOD) elif tcpp.dstport == 80: msg = of.ofp_flow_mod() msg.match = of.ofp_match(dl_type = pkt.ethernet.IP_TYPE, nw_proto = pkt.ipv4.TCP_PROTOCOL, tp_dst = 80) msg.match.in_port = event.port outport = return_port(s1, mac_1, mac_2, 80) msg.actions.append(of.ofp_action_output(port = outport)) event.connection.send(msg) elif tcpp.srcport == 80: msg = of.ofp_flow_mod() msg.match = of.ofp_match(dl_type = pkt.ethernet.IP_TYPE, nw_proto = pkt.ipv4.TCP_PROTOCOL, tp_src = 80) msg.match.in_port = event.port outport = return_port(s1, mac_1, mac_2, 80) msg.actions.append(of.ofp_action_output(port = outport)) event.connection.send(msg) else : msg = of.ofp_flow_mod() msg.match = of.ofp_match(dl_type = pkt.ethernet.IP_TYPE, nw_proto = pkt.ipv4.TCP_PROTOCOL, tp_dst = tcpp.dst, tp_src = tcpp.src) outport = return_port(s1, mac_1, mac_2, 22) msg.actions.append(of.ofp_action_output(port = outport)) msg.match.in_port = event.port event.connection.send(msg) 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)
def port_flows(self, event, port_tuple): match = of.ofp_match() match.in_port = port_tuple[0] msg = of.ofp_flow_mod() msg.match = match msg.actions.append(of.ofp_action_output(port = port_tuple[1])) event.connection.send(msg) match = of.ofp_match() match.in_port = port_tuple[1] msg = of.ofp_flow_mod() msg.match = match msg.actions.append(of.ofp_action_output(port = port_tuple[0])) event.connection.send(msg)
def flowModEAPStart(self, mac_addr, port): """ Cette fonction permet d ebloquer tout le traffic a destination d'une machine, excepte les flux EAP """ mac_addr = checkMac(mac_addr) port = checkInt(port) #Bloque tout le traffic depuis et vers la machine concerne msg = of.ofp_flow_mod() msg.match= of.ofp_match() msg.match.in_port= port msg.match.dl_src= mac_addr msg.priority = 1 self.connection.send(msg) self.host_progress[mac_addr]['match'].append(msg.match) msg = of.ofp_flow_mod() msg.match= of.ofp_match() msg.match.dl_dst= mac_addr msg.priority = 1 self.connection.send(msg) self.host_progress[mac_addr]['match'].append(msg.match) #Ajout de 2 flux pour la gestion de 802.1x msg = of.ofp_flow_mod() msg.match = of.ofp_match() msg.match.dl_type= 0x888e msg.match.in_port = port msg.match.dl_src = mac_addr msg.priority = 200 action = of.ofp_action_output( port = of.OFPP_CONTROLLER ) msg.actions.append(action) self.connection.send(msg) self.host_progress[mac_addr]['match'].append(msg.match) msg = of.ofp_flow_mod() msg.match = of.ofp_match() msg.match.dl_type = 0x888e msg.match.in_port= of.OFPP_CONTROLLER msg.match.dl_dst = mac_addr action = of.ofp_action_output( port = port) msg.actions.append(action) msg.priority = 200 self.connection.send(msg) self.host_progress[mac_addr]['match'].append(msg.match)
def deleteFlows(self, mac_addr): mac_addr = checkMac(mac_addr) msg = of.ofp_flow_mod() msg.command = of.OFPFC_DELETE msg.match= of.ofp_match() msg.match.dl_src= mac_addr self.connection.send(msg) msg = of.ofp_flow_mod() msg.command = of.OFPFC_DELETE msg.match= of.ofp_match() msg.match.dl_dst= mac_addr self.connection.send(msg)
def _handle_PacketIn(self, event): def flood(): msg = of.ofp_packet_out() msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD)) msg.buffer_id = event.ofp.buffer_id msg.in_port = event.port event.connection.send(msg) packet = event.parse() self.mac_to_port[packet.src] = event.port if packet.dst.isMulticast(): flood() else: if packet.dst not in self.mac_to_port: log.debug("port for %s unknown -- flooding" % (packet.dst,)) flood() else: port = self.mac_to_port[packet.dst] log.debug("installing flow for %s.%i -> %s.%i" % (packet.src, event.port, packet.dst, port)) msg = of.ofp_flow_mod() #msg.match = of.ofp_match.from_packet(packet) msg.match = of.ofp_match(in_port=event.port, dl_dst=EthAddr(packet.dst)) msg.idle_timeout = 10 msg.hard_timeout = 30 msg.actions.append(of.ofp_action_output(port=port)) msg.buffer_id = event.ofp.buffer_id event.connection.send(msg) return
def _install_proactive_path(self, src, dst): """Install entries on route between two hosts based on MAC addrs. src and dst are unsigned ints. """ src_sw = self.t.up_nodes(self.t.id_gen(dpid = src).name_str()) assert len(src_sw) == 1 src_sw_name = src_sw[0] dst_sw = self.t.up_nodes(self.t.id_gen(dpid = dst).name_str()) assert len(dst_sw) == 1 dst_sw_name = dst_sw[0] hash_ = self._src_dst_hash(src, dst) route = self.r.get_route(src_sw_name, dst_sw_name, hash_, False) log.info("route: %s" % route) # Form OF match match = of.ofp_match() match.dl_src = self._int_to_eth(src) match.dl_dst = self._int_to_eth(dst) dst_host_name = self.t.id_gen(dpid = dst).name_str() final_out_port, ignore = self.t.port(route[-1], dst_host_name) for i, node in enumerate(route): node_dpid = self.t.id_gen(name = node).dpid if i < len(route) - 1: next_node = route[i + 1] out_port, next_in_port = self.t.port(node, next_node) else: out_port = final_out_port self.switches[node_dpid].install(out_port, match)
def _handle_openflow_ConnectionUp(self, event): print('DPID %s is UP' % (event.dpid)) if bucket.matrix_adj.get(event.dpid) is None: bucket.matrix_adj[event.dpid] = {} bucket.port_info[event.dpid] = {} bucket.flow_entry[event.dpid] = {} for i,v in enumerate(event.ofp.ports): if (v.port_no < 60000): bucket.port_info[event.dpid][v.port_no] = PortDetail(i, v.name, v.port_no, v.state, curr_to_capacity(v.curr)) if config.USE_DHCP: msg = of.ofp_flow_mod() msg.match = of.ofp_match() msg.match.dl_type = 0x0800 # IP type in 3rd layer msg.match.nw_proto = 17 # UDP type in 4th layer # msg.match.nw_dst = IP_BROADCAST msg.match.tp_src = 68 # DHCP client port msg.match.tp_dst = 67 # DHCP server port msg.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) event.connection.send(msg)
def handle_flows_redirection(cls, dpid, connections, switch_addresss, message): """ Sends flow mod messages to redirect flows to created queues """ #print 'message from ' + str(switch_addresss) #print 'Connections ' + str(dir(connections)) dpid = dpid[:len(dpid)-1] dpid = dpid[len(dpid)-12:] #print 'Received dpid: ' + str(dpid) #print "message to be used for redirection" + str(message) msg = of.ofp_flow_mod(command=of.OFPFC_DELETE) msg.priority = 65535 #print "dpid parameter: " + str(dpid) for connection in connections: connection_dpid = connection.dpid dpid_str = dpidToStr(connection_dpid) dpid_str = dpid_str.replace("-", "") #print 'Real dpid_str: ' + dpid_str if dpid == dpid_str: connection.send(msg) #print 'Sent to: ' + str(connection) #print 'Well...done' for i in range(len(message['bw_list'])): # We only want to redirect outgoing flows if message['bw_list'][i]['action'] != 'OFPP_LOCAL': my_match = of.ofp_match(dl_type = 0x800,nw_src=message['bw_list'][i]['nw_src'],nw_dst=message['bw_list'][i]['nw_dst']) #print "Flow Match: " + str(my_match) msg = of.ofp_flow_mod() msg.match = my_match msg.priority = 65535 msg.idle_timeout = 0 msg.hard_timeout = 0 msg.actions.append(of.ofp_action_enqueue(port=int(message['bw_list'][i]['action']), queue_id=int(message['queue_list'][i]['queueId']))) #print "Flow mod message: " + str(msg) #toDo: Check a better way to do this #print "dpid parameter: " + str(dpid) for connection in connections: connection_dpid=connection.dpid #print "Connection dpid: " + str(connection_dpid) dpid_str=dpidToStr(connection_dpid) dpid_str=dpid_str.replace("-", "") #print 'Real dpid_str: ' + dpid_str if dpid == dpid_str: connection.send(msg) global flow_mod_time flow_mod_time = time.time() print "Notification time: " + str(notification_time) print "Flow stats reply: " + str(flow_stats_reply_time) print "Queues done time: " + str(queues_done_time) print "Flow mode time :" + str(flow_mod_time)
def _install_flow_bcast(self, mhst): for v in mhst._adj_matrix: if is_host(v): continue for u in mhst._adj_matrix[v]: # create flow for bcast packet match = of.ofp_match() match.dl_type = pkt.ethernet.IP_TYPE match.in_port = mhst._adj_matrix[v][u] #match.dl_src = EthAddr("00:00:00:FF:FF:FF") match.dl_dst = EthAddr("00:00:00:FF:FF:FF") msg = of.ofp_flow_mod() msg.priority = 40000 msg.match = match #msg.actions.append(of.ofp_action_dl_addr.set_src(EthAddr("00:00:00:FF:FF:FF"))) for w in mhst._adj_matrix[v]: if w != u: out_port = mhst._adj_matrix[v][w] # if output link to host change dst mac addr to that machine #if is_host(w): # dl_dst = self._host_list[w].mac_address # msg.actions.append(of.ofp_action_dl_addr.set_dst(dl_dst)) msg.actions.append(of.ofp_action_output(port = out_port)) self._datapath_list[str_to_dpid(v)].connection.send(msg)
def _handle_openflow_ConnectionUp (self, event): sw = switches.get(event.dpid) print "DPID for",event.dpid," = ",dpidToStr(event.dpid) if sw is None: # New switch sw = Switch() sw.dpid = event.dpid switches[event.dpid] = sw sw.connect(event.connection) else: sw.connect(event.connection) dpids.append(event.dpid) ports[dpidToStr(event.dpid)] = {} print "Add ports to link status DB" dpid_ts[event.dpid] = 0.000 dpid_latency[event.dpid] = 0.000 dpid_stats[event.dpid] = [] for p in event.ofp.ports: port = [0.0, 100, 0] ports[dpidToStr(event.dpid)][p.port_no] = port """ Tell all switches to forward latency packets to controller """ print "Connected to switch",dpidToStr(event.dpid) connection = event.connection match = of.ofp_match(dl_type = LAT_TYPE,dl_dst = pkt.ETHERNET.NDP_MULTICAST) msg = of.ofp_flow_mod() msg.priority = 65000 msg.match = match msg.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) connection.send(msg)
def _install_flow_shortest_path(self, src_host, dst_host): src_host = str(src_host) dst_host = str(dst_host) (path, out_ports, in_ports) = self._host_host_path[src_host][dst_host] for dp, out_port, in_port in zip(path, out_ports, in_ports): #nw_tos|tp_dst|dl_dst|dl_src|in_port|dl_vlan_pcp|nw_proto|dl_vlan|tp_src|dl_type|nw_src(/0)|nw_dst(/0) # create flow for send src to dst in shortest path match = of.ofp_match() match.dl_type = pkt.ethernet.IP_TYPE match.in_port = in_port match.nw_src = IPAddr(src_host) match.nw_dst = IPAddr(dst_host) msg = of.ofp_flow_mod() msg.priority = 30000 msg.match = match msg.actions.append(of.ofp_action_output(port = out_port)) self._datapath_list[str_to_dpid(dp)].connection.send(msg) # special match that check source MAC address """
def _handle_LinkEvent (self, event): def flip (link): return Discovery.Link(link[2],link[3], link[0],link[1]) l = event.link sw1 = switches[l.dpid1] sw2 = switches[l.dpid2] # Invalidate all flows and path info. # For link adds, this makes sure that if a new link leads to an # improved path, we use it. # For link removals, this makes sure that we don't use a # path that may have been broken. #NOTE: This could be radically improved! (e.g., not *ALL* paths break) clear = of.ofp_flow_mod(match=of.ofp_match(),command=of.OFPFC_DELETE) for sw in switches.itervalues(): sw.connection.send(clear) path_map.clear() if event.removed: # This link no longer okay if sw2 in adjacency[sw1]: del adjacency[sw1][sw2] if sw1 in adjacency[sw2]: del adjacency[sw2][sw1] # But maybe there's another way to connect these... for ll in core.openflow_discovery.adjacency: if ll.dpid1 == l.dpid1 and ll.dpid2 == l.dpid2: if flip(ll) in core.openflow_discovery.adjacency: # Yup, link goes both ways adjacency[sw1][sw2] = ll.port1 adjacency[sw2][sw1] = ll.port2 # Fixed -- new link chosen to connect these break else: # If we already consider these nodes connected, we can # ignore this link up. # Otherwise, we might be interested... if adjacency[sw1][sw2] is None: # These previously weren't connected. If the link # exists in both directions, we consider them connected now. if flip(l) in core.openflow_discovery.adjacency: # Yup, link goes both ways -- connected! adjacency[sw1][sw2] = l.port1 adjacency[sw2][sw1] = l.port2 # If we have learned a MAC on this port which we now know to # be connected to a switch, unlearn it. bad_macs = set() for mac,(sw,port) in mac_map.iteritems(): #print sw,sw1,port,l.port1 if sw is sw1 and port == l.port1: if mac not in bad_macs: log.debug("Unlearned %s", mac) bad_macs.add(mac) if sw is sw2 and port == l.port2: if mac not in bad_macs: log.debug("Unlearned %s", mac) bad_macs.add(mac) for mac in bad_macs: del mac_map[mac]
def _delete_old_vlan_flows(self): # print "*** DELETING OLD VLANS %s *** " % self._vlan match = of.ofp_match() match.dl_vlan = self._vlan flow_mod = of.ofp_flow_mod(match=match, command=of.OFPFC_DELETE) # print "FM = %s" % str(flow_mod) self.forwardToAllAppropriateSwitches(flow_mod)
def _handle_ConnectionUp (self, event): policies = self.read_policies(policyFile) for policy in policies.itervalues(): # TODO: implement the code to add a rule to block the flow # between the source and destination specified in each policy # Note: The policy data structure has two fields which you can # access to turn the policy into a rule. policy.dl_src will # give you the source mac address and policy.dl_dst will give # you the destination mac address # Note: Set the priority for your rule to 20 so that it # doesn't conflict with the learning bridge setup # pass # debug to see the source and destination MAC addresses log.debug("~~> Source Mac is %s", policy.dl_src) log.debug("~~> Destination Mac is %s", policy.dl_dst) # define a set of headers for packets to match against # if the MAC address is between H1 and H2 block #match = of.ofp_match() #match.dl_src = policy.dl_src #match.dl_dst = policy.dl_dst match = of.ofp_match(dl_src = policy.dl_src, dl_dst = policy.dl_dst) # install the mods to block matches fm = of.ofp_flow_mod() fm.priority = 20 fm.match = match event.connection.send(fm) log.debug("Firewall rules installed on %s", dpidToStr(event.dpid))
def _exec_cmd_get_flow_stats (self, event): try: msg = event.msg dpid = strToDPID(msg['dpid']) con = core.openflow.getConnection(dpid) if con is None: raise RuntimeError("No such switch") match = event.msg.get('match') table_id = event.msg.get('table_id', 0xff) out_port = event.msg.get('out_port', of.OFPP_NONE) sr = of.ofp_stats_request() sr.body = of.ofp_flow_stats_request() if match is None: match = of.ofp_match() else: match = dict_to_match(match) sr.body.match = match sr.body.table_id = table_id sr.body.out_port = out_port con.send(sr) self.reply(event,**{'type':'set_table','xid':sr.xid}) except: #log.exception("Exception in get_flow_stats") log.debug("Exception in get_flow_stats - %s:%s", sys.exc_info()[0].__name__, sys.exc_info()[1]) self.reply(event, exception="%s: %s" % (sys.exc_info()[0],sys.exc_info()[1]), traceback=traceback.format_exc())
def _handle_ConnectionUp (self, event): """ On datapath join, create a new LLDP packet per port """ assert event.dpid not in self._dps if self.install_flow: log.debug("Installing flow for %s", dpidToStr(event.dpid)) msg = of.ofp_flow_mod(match = of.ofp_match(dl_type = ethernet.LLDP_TYPE, dl_dst = NDP_MULTICAST)) msg.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) #msg.hard_timeout = 5 msg.flags = 1 """ event.connection.send(msg) """ # Install through NOM dp = core.topology.getEntityByID(event.dpid) dp.installFlow(priority=msg.priority, cookie=msg.cookie, \ idle_timeout=msg.idle_timeout, hard_timeout=msg.hard_timeout, \ match=msg.match, actions=msg.actions) self._dps.add(event.dpid) self._sender.addSwitch(event.dpid, [(p.port_no, p.hw_addr) for p in event.ofp.ports])
def extractMatch(ethernet): """ Extracts and returns flow attributes from the given 'ethernet' packet. The caller is responsible for setting IN_PORT itself. """ match = of.ofp_match() match.wildcards = of.OFPFW_ALL #match.dl_src = ethernet.src.tolist() #match.dl_dst = ethernet.dst.tolist() match.dl_src = bytearray(ethernet.src) match.dl_dst = bytearray(ethernet.dst) match.dl_type = ethernet.type p = ethernet.next if isinstance(p, vlan): match.dl_vlan = p.id match.dl_vlan_pcp = p.pcp p = p.next else: match.dl_vlan = 0xffff # XXX should be written OFP_VLAN_NONE if isinstance(p, ipv4): match.nw_src = p.srcip match.nw_dst = p.dstip match.nw_proto = p.protocol p = p.next if isinstance(p, udp) or isinstance(p, tcp): match.tp_src = p.srcport match.tp_dst = p.dstport else: if isinstance(p, icmp): match.tp_src = p.type match.tp_dst = p.code return Match(match)
def build_of_match(self,switch,inport,pred): ### BUILD OF MATCH match = of.ofp_match() match.in_port = inport if 'srcmac' in pred: match.dl_src = pred['srcmac'] if 'dstmac' in pred: match.dl_dst = pred['dstmac'] if 'ethtype' in pred: match.dl_type = pred['ethtype'] if 'vlan_id' in pred: match.dl_vlan = pred['vlan_id'] if 'vlan_pcp' in pred: match.dl_vlan_pcp = pred['vlan_pcp'] if 'protocol' in pred: match.nw_proto = pred['protocol'] if 'srcip' in pred: match.set_nw_src(pred['srcip']) if 'dstip' in pred: match.set_nw_dst(pred['dstip']) if 'tos' in pred: match.nw_tos = pred['tos'] if 'srcport' in pred: match.tp_src = pred['srcport'] if 'dstport' in pred: match.tp_dst = pred['dstport'] return match
def handle_FEATURES_REPLY (self, con, msg): connecting = con.connect_time == None con.features = msg con.original_ports._ports = set(msg.ports) con.ports._reset() con.dpid = msg.datapath_id nexus = core.OpenFlowConnectionArbiter.getNexus(con) if nexus is None: # Cancel connection con.info("No OpenFlow nexus for " + pox.lib.util.dpidToStr(msg.datapath_id)) con.disconnect() return con.ofnexus = nexus con.ofnexus._connect(con) #TODO: Add a timeout for finish_connecting if con.ofnexus.miss_send_len is not None: con.send(of.ofp_set_config(miss_send_len = con.ofnexus.miss_send_len)) if con.ofnexus.clear_flows_on_connect: con.send(of.ofp_flow_mod(match=of.ofp_match(),command=of.OFPFC_DELETE)) self._barrier = of.ofp_barrier_request() con.send(self._barrier)
def send_packet(self,sid,src,dest,dpidstr): print "Src is ",str(src) print "Src is ",str(EthAddr(src)) match = of.ofp_match() msg = of.ofp_flow_mod() msg.priority = 32768 msg.match.dl_src = EthAddr(src) msg.match.dl_dst = EthAddr(dest) self.connection.send(msg)
def _handle_ConnectionUp(self, event): for (src, dst) in self.deny: match = of.ofp_match() match.dl_src = src match.dl_dst = dst msg = of.ofp_flow_mod() msg.match = match event.connection.send(msg) log.debug("Firewall rules installed on %s", dpidToStr(event.dpid))
def _handle_ConnectionUp(self, event): for src, dst in self.rules: msg = of.ofp_flow_mod() msg.match = of.ofp_match() msg.match.dl_src = src msg.match.dl_dst = dst msg.priority = 65535 event.connection.send(msg) log.debug("Firewall rules installed on %s", dpidToStr(event.dpid))
def _handle_ConnectionUp (self, event): if self._install_flow: msg = of.ofp_flow_mod() msg.match = of.ofp_match() msg.match.dl_type = pkt.ethernet.IP_TYPE msg.match.nw_proto = pkt.ipv4.UDP_PROTOCOL msg.match.tp_src = 5353 msg.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) event.connection.send(msg)
def strip_match(o): m = of.ofp_match() fields = 'dl_dst dl_src nw_dst nw_src tp_dst tp_src dl_type nw_proto' for f in fields.split(): setattr(m, f, getattr(o, f)) return m
def get_flow_mod(in_port, out_port, vlan=1550): msg = of.ofp_flow_mod() msg.match = of.ofp_match(in_port=in_port, dl_vlan=vlan) msg.idle_timeout = 200 msg.hard_timeout = 200 msg.priority = 40 msg.actions.append(of.ofp_action_output(port=out_port)) msg.actions.append(of.ofp_action_output(port=of.OFPP_CONTROLLER)) return msg
def block_icmp_hnotrust1(self): match = of.ofp_match() match.nw_proto = pkt.ipv4.ICMP_PROTOCOL match.dl_type = pkt.ethernet.IP_TYPE match.set_nw_src(IPS["hnotrust"][0]) fm = of.ofp_flow_mod() fm.match = match fm.priority = 200 self.connection.send(fm)
def add_ip_flow(self, nw, dmac, port, dpid): msg = of.ofp_flow_mod() msg.match = of.ofp_match(dl_type=pkt.ethernet.IP_TYPE, nw_dst=nw) #msg.idle_timeout = 120 msg.actions.append(of.ofp_action_dl_addr.set_dst(EthAddr(dmac))) msg.actions.append(of.ofp_action_dl_addr.set_src(self.mac[dpid])) msg.actions.append(of.ofp_action_output(port=port)) self.connection[dpid].send(msg) log.debug("add ip flow (%s, %s) from %d", nw, dmac, port)
def block_flow(event, src, dst): block = of.ofp_match() block.dl_src = EthAddr(src) block.dl_dst = EthAddr(dst) flow_mod = of.ofp_flow_mod() flow_mod.match = block flow_mod.idle_timeout = 30 flow_mod.hard_timeout = 30 event.connection.send(flow_mod)
def _handle_ConnectionUp(self, event): for rule in rules: block = of.ofp_match(dl_type=0x800, nw_proto=pkt.ipv4.ICMP_PROTOCOL) block.nw_src = IPAddr(rule[0]) block.nw_dst = IPAddr(rule[1]) flow_mod = of.ofp_flow_mod() flow_mod.match = block event.connection.send(flow_mod)
def block_ip_hnotrust1_to_dcs31(self): match = of.ofp_match() match.dl_type = pkt.ethernet.IP_TYPE match.set_nw_src(IPS["hnotrust"][0]) match.set_nw_dst(IPS["serv1"][0]) fm = of.ofp_flow_mod() fm.match = match fm.priority = 201 self.connection.send(fm)
def blockSpoofer (self, mac, event): spoofer = self.spoofers[mac] match = of.ofp_match(in_port = spoofer.inport) msg = of.ofp_flow_mod (match=match) msg.priprity = 100 msg.idle_timeout = of.OFP_FLOW_PERMANENT msg.hard_timeout = of.OFP_FLOW_PERMANENT event.connection.send (msg) spoofer.count = 0
def testeMatch(self): msg1 = of.ofp_match() msg1.dl_type = 0x800 msg1.nw_proto = 17 #msg1.nw_dst = IPAddr('10.1.0.2') msg1.nw_src = IPAddr('10.1.0.1') msg1.tp_src = 65534 #msg1.tp_dst = 7000 self.addRegra(of.ofp_flow_mod(match=msg1, command=of.OFPFC_MODIFY, actions=[of.ofp_action_output(port=3)]))
def gen_path_rules(self, path, prio=None): if not prio: prio = 65535 # core.openflow.getConnection(dpid) log.info("Path: " + str(path)) rules = [] src = path[0] dst = path[-1] path = path[1:-1] src_ip = of.IPAddr("10.0.0." + src[1:]) dst_ip = of.IPAddr("10.0.0." + dst[1:]) prev_hop = src cur_hop = path[0] path = path[1:] for next_hop in path: match = of.ofp_match(dl_type=0x800, nw_src=src_ip, nw_dst=dst_ip) match.in_port = self.topo.topo.ports[str(cur_hop)][str(prev_hop)] flow = of.ofp_flow_mod(match=match) flow.idle_timeout = of.OFP_FLOW_PERMANENT flow.hard_timeout = of.OFP_FLOW_PERMANENT flow.priority = prio flow.actions = [ of.ofp_action_output( port=self.topo.topo.ports[str(cur_hop)][str(next_hop)]) ] con = core.openflow.getConnection(cur_hop) rules.append((con, flow)) prev_hop = cur_hop cur_hop = next_hop # Now need to install final rule to dst host next_hop = dst match = of.ofp_match(dl_type=0x800, nw_src=src_ip, nw_dst=dst_ip) match.in_port = self.topo.topo.ports[str(cur_hop)][str(prev_hop)] flow = of.ofp_flow_mod(match=match) flow.idle_timeout = of.OFP_FLOW_PERMANENT flow.hard_timeout = of.OFP_FLOW_PERMANENT flow.priority = prio flow.actions = [ of.ofp_action_output( port=self.topo.topo.ports[str(cur_hop)][str(next_hop)]) ] con = core.openflow.getConnection(cur_hop) rules.append((con, flow)) return rules
def _handle_RtpFromSwitch(self, event): clientMac = clientIP_mac[event.clientIP] dest = mac_map[clientMac] switch = switches[event.switchDpid] switchMac = EthAddr(DPID_MAC[dpid_to_str(switch.dpid)]) p = _get_path(switch, dest[0], of.OFPP_LOCAL, dest[1]) match = of.ofp_match() match.dl_type = pkt.ethernet.IP_TYPE match.dl_src = switchMac match.dl_dst = clientMac #match.nw_proto = pkt.ipv4.UDP_PROTOCOL match.nw_src = IPAddr('192.168.1.1') match.nw_dst = event.clientIP match1 = of.ofp_match() match1.dl_type = pkt.ethernet.IP_TYPE match1.dl_dst = switchMac match1.dl_src = clientMac match1.in_port = dest[1] flow1 = of.ofp_flow_mod() flow1.match = match1 flow1.actions.append(of.ofp_action_output(port=of.OFPP_LOCAL)) switch.connection.send(flow1) match2 = of.ofp_match() match2.dl_type = pkt.ethernet.ARP_TYPE match2.dl_src = switchMac match2.in_port = of.OFPP_LOCAL flow2 = of.ofp_flow_mod() flow2.match = match2 flow2.actions.append(of.ofp_action_output(port=of.OFPP_ALL)) switch.connection.send(flow2) match3 = of.ofp_match() match3.dl_type = pkt.ethernet.ARP_TYPE match3.dl_dst = switchMac flow3 = of.ofp_flow_mod() flow3.match = match3 flow3.actions.append(of.ofp_action_output(port=of.OFPP_LOCAL)) switch.connection.send(flow3) _install_rtp_path(p, match, event.dumpPort)
def _handle_BarrierIn(event): global tempoEnv if (event.xid == 77777): event.connection.send(of.ofp_barrier_request(xid=77771)) tempoEnv = time.time() - t temporec = time.time() - t if (event.xid == 66661): vRecebido.append(temporec) v = len(vRecebido) - 1 print "1 " + str(vRegras[v]) + ' ' + str(vEnviado[v]) + ' ' + str( vRecebido[v]) elif (event.xid == 66660): tempoEnv = time.time() - t vEnviado.append(tempoEnv) numRegras = [250, 500, 750, 1000, 1250, 1500, 1750, 2000, 2250] #max=2611 #numRegras = [250,500,750] #max=2611 global pos log.info("Barrier Reply recebido em: " + str(time.time() - t) + " ID:" + str(event.xid)) if (event.xid == 66661 and pos > len(numRegras)): log.info("Removendo regras port=1") event.connection.send( of.ofp_flow_mod(match=of.ofp_match(in_port=1), command=of.OFPFC_DELETE)) log.info("Finalizado.") if (event.xid == 77771 and pos < len(numRegras)): event.connection.send( of.ofp_flow_mod(match=of.ofp_match(in_port=1), command=of.OFPFC_DELETE)) log.info("Regras port=1 removidas") log.info("Instalando " + str(numRegras[pos]) + " regras") flood(event, 0, numRegras[pos]) vRegras.append(numRegras[pos]) modificaRegras(event, 0, numRegras[pos]) log.info("Regras port=1 alteradas: output=2 -> output=3") pos += 1 elif (event.xid == 77771 and pos == len(numRegras)): log.info("Esperando ultimo BarrierReply ID 66661") pos += 1
def act_like_switch(self, packet, packet_in): """ :packet: PacketIn event.parsed :packet_in: PacketIn event.ofp """ # save source MAC to inport mapping self.mac_to_port[str(packet.src)] = packet_in.in_port self.check_arp_spoof(packet, packet_in) if self.arp_spoof_detected(packet, packet_in): # Maybe the log statement should have source/destination/port? log.debug("Installing drop flow...") msg = of.ofp_flow_mod() # Set fields to match received packet source msg.match = of.ofp_match( dl_src=packet.src) # if source MAC is equal to the source #We don't want the flow to last forever, so we set it to time out #Make the blocked, potential ARP poisoner wait twice as long as other flows to time out msg.idle_timeout = TimerQuantumDuration * 2 # set flow_mod idle timeout #Output to IDS_PORT msg.actions.append(of.ofp_action_output(port=IDS_PORT)) self.connection.send(msg) elif (str(packet.dst) in self.mac_to_port): log.debug('MAC ' + str(packet.src) + ' on port ' + str(packet_in.in_port)) # Send packet out the associated port self.send_packet(packet_in.buffer_id, packet_in.data, self.mac_to_port[str(packet.dst)], packet_in.in_port) log.debug("Installing flow...") # Maybe the log statement should have source/destination/port? msg = of.ofp_flow_mod(cookie=self.int_of_ip(packet, packet_in), flags=of.OFPFF_SEND_FLOW_REM) # Set fields to match received packet source msg.match.dl_dst = packet.dst #Uncomment line below to lock on more fields #msg.match = of.ofp_match.from_packet(packet) #We don't want the flow to last forever, so we set it to time out msg.idle_timeout = TimerQuantumDuration msg.actions.append( of.ofp_action_output(port=self.mac_to_port[str(packet.dst)])) self.connection.send(msg) else: # Flood the packet out everything but the input port # This part looks familiar, right? self.send_packet(packet_in.buffer_id, packet_in.data, of.OFPP_FLOOD, packet_in.in_port)
def _handle_PacketIn(event): global server_index packet = event.parsed # First make sure the packet is addressed using IPv4 if (not event.parsed.find("ipv4")): return EventContinue msg = of.ofp_flow_mod() msg.match = of.ofp_match.from_packet(packet) # If the ip matches controller virtual ip then continue if (msg.match.nw_dst != controllerip): return EventContinue # Employing round robin algorithm here index = server_index % total_servers print index selected_server_ip = server[index]['ip'] selected_server_mac = server[index]['mac'] selected_server_outport = server[index]['outport'] server_index += 1 # Setup route to server msg.buffer_id = event.ofp.buffer_id msg.in_port = event.port msg.actions.append( of.ofp_action_dl_addr(of.OFPAT_SET_DL_DST, selected_server_mac)) msg.actions.append( of.ofp_action_nw_addr(of.OFPAT_SET_NW_DST, selected_server_ip)) msg.actions.append(of.ofp_action_output(port=selected_server_outport)) event.connection.send(msg) # Once the last server is reached, reverse the route reverse_msg = of.ofp_flow_mod() reverse_msg.buffer_id = None reverse_msg.in_port = selected_server_outport reverse_msg.match = of.ofp_match() reverse_msg.match.dl_src = selected_server_mac reverse_msg.match.nw_src = selected_server_ip reverse_msg.match.tp_src = msg.match.tp_dst reverse_msg.match.dl_dst = msg.match.dl_src reverse_msg.match.nw_dst = msg.match.nw_src reverse_msg.match.tp_dst = msg.match.tp_src reverse_msg.actions.append( of.ofp_action_dl_addr(of.OFPAT_SET_DL_SRC, controllermac)) reverse_msg.actions.append( of.ofp_action_nw_addr(of.OFPAT_SET_NW_SRC, controllerip)) reverse_msg.actions.append(of.ofp_action_output(port=msg.in_port)) event.connection.send(reverse_msg) return EventHalt
def _handle_PacketIn(event): global server_index packet = event.parsed # Only handle IPv4 flows if (not event.parsed.find("ipv4")): return EventContinue msg = of.ofp_flow_mod() msg.match = of.ofp_match.from_packet(packet) # Only handle traffic destined to virtual IP if (msg.match.nw_dst != virtual_ip): return EventContinue # Round robin selection of servers index = server_index % total_servers print index selected_server_ip = server[index]['ip'] selected_server_mac = server[index]['mac'] selected_server_outport = server[index]['outport'] server_index += 1 # Setup route to server msg.buffer_id = event.ofp.buffer_id msg.in_port = event.port msg.actions.append( of.ofp_action_dl_addr(of.OFPAT_SET_DL_DST, selected_server_mac)) msg.actions.append( of.ofp_action_nw_addr(of.OFPAT_SET_NW_DST, selected_server_ip)) msg.actions.append(of.ofp_action_output(port=selected_server_outport)) event.connection.send(msg) # Setup reverse route from server reverse_msg = of.ofp_flow_mod() reverse_msg.buffer_id = None reverse_msg.in_port = selected_server_outport reverse_msg.match = of.ofp_match() reverse_msg.match.dl_src = selected_server_mac reverse_msg.match.nw_src = selected_server_ip reverse_msg.match.tp_src = msg.match.tp_dst reverse_msg.match.dl_dst = msg.match.dl_src reverse_msg.match.nw_dst = msg.match.nw_src reverse_msg.match.tp_dst = msg.match.tp_src reverse_msg.actions.append( of.ofp_action_dl_addr(of.OFPAT_SET_DL_SRC, virtual_mac)) reverse_msg.actions.append( of.ofp_action_nw_addr(of.OFPAT_SET_NW_SRC, virtual_ip)) reverse_msg.actions.append(of.ofp_action_output(port=msg.in_port)) event.connection.send(reverse_msg) return EventHalt
def installProtocolRule(self, dl_type, proto): msg = of.ofp_flow_mod() match = of.ofp_match() match.dl_type = dl_type match.nw_proto = proto msg.match = match action = of.ofp_action_output(port=of.OFPP_NORMAL) msg.actions.append(action) print('Adding flow for protocol : ' + str(proto)) self.connection.send(msg)
def keepARP(): msg = of.ofp_flow_mod() msg.priorty = 2000 # higher priority indicated by higer number #msg.idle_timeout = 5 #msg.hard_timeout = 5 match = of.ofp_match() match.dl_type = 0x806 # for ARP msg.match = match msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD)) self.connection.send(msg)
def _handle_ConnectionUp (self, event): log.debug("*** Switch %s has come up ***", dpid_to_str(event.dpid)) for v in rules: msg = of.ofp_flow_mod() # Mensaje FlowMod match = of.ofp_match(in_port = v['in_port']) # Instancia asociada al match action = of.ofp_action_output(port = v['out_port']) #Instancia asociada a la action msg.match = match # Agregando el match al mensaje FlowMod msg.actions.append(action) # Agregando el action al mensaje FlowMod event.connection.send(msg) # Envio del flujo al switch log.debug("+ Installing flow --> in_port: %d, out_port: %d.",v['in_port'],v['out_port'])
def install_firewall(event, packet, h1, h2): msg = of.ofp_flow_mod() msg.match = of.ofp_match() print h1 print h2 print "Inside install_firewall" msg.match.dl_src = EthAddr(h1) msg.match.dl_dst = EthAddr(h2) msg.actions.append(of.ofp_action_output(port=of.OFPP_NONE)) event.connection.send(msg)
def __init__(self, connection): # Keep track of the connection to the switch so that we can # send it messages! self.connection = connection # This binds our PacketIn event listener connection.addListeners(self) #add switch rules here msgICMP = of.ofp_flow_mod() match = of.ofp_match(nw_proto=1, dl_type=0x0800) msgICMP.match = match msgICMP.actions.append(of.ofp_action_output(port=of.OFPP_FLOOD)) self.connection.send(msgICMP) msgARP = of.ofp_flow_mod() match = of.ofp_match(dl_type=0x0806) msgARP.match = match # ARP msgARP.actions.append(of.ofp_action_output(port=of.OFPP_FLOOD)) self.connection.send(msgARP)
def _handle_ConnectionUp(self, event): for (first, second) in self.list: match = of.ofp_match() match.dl_src = source match.dl_dst = dest msg = of.ofp_flow_mod() msg.match = match event.connection.send(msg) log.debug("Firewall rules installed on %s", dpidToStr(event.dpid))
def install_end_to_end_IP_path(self, event, dst_dpid, final_port, packet): source_switch = event.dpid #take the switch node triggered the event dest_switch = dst_dpid #take the destination node switch random_path = random.choice( self.switches[source_switch]._paths[dest_switch] ) #compute a random path between shortest selected length_path = len(random_path) - 1 # last path index length_random = len(random_path) if source_switch == dest_switch: #means that we are in the same switch edge match = of.ofp_match() match.dl_type = ethernet.IP_TYPE match.nw_src = packet.next.srcip match.nw_dst = packet.next.dstip self.switches[source_switch].install_output_flow_rule( final_port, match) #install rule to the edge switch self.switches[source_switch].send_packet( final_port, event.data) #send icmp packet else: for index in range(length_random): reverse_index = length_path - index #go to the last index match = of.ofp_match() match.dl_type = ethernet.IP_TYPE match.nw_src = packet.next.srcip match.nw_dst = packet.next.dstip if (reverse_index != length_path): outport = self.sw_sw_ports[( random_path[reverse_index], random_path[reverse_index + 1])] #else if we are in the other switches else: outport = final_port #if we are in the last switch self.switches[ random_path[reverse_index]].install_output_flow_rule( outport, match) #install rules in route self.switches[source_switch].send_packet( self.sw_sw_ports[(source_switch, random_path[1])], event.data) # send the icmp packet
def webFlow(event): """first define match rules""" msg = of.ofp_flow_mod() webMatch = of.ofp_match(tp_src=80) msg.match = webMatch """if its web, send packet to controller""" print "Pushing web flow to " + dpid_to_str(event.dpid) msg.actions.append(of.ofp_action_output(port=of.OFPP_CONTROLLER)) event.connection.send(msg) """packet gets sent to controller. need a listener function for this, packetIn"""
def _install_flow_forward_to_controller(self, ipAddress): ''' install a flow entry that forwards packet to controller for certain destination-ip-address ''' msg = of.ofp_flow_mod() msg.match = of.ofp_match(dl_type = self.DL_IP4, nw_dst = ipAddress) msg.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) self.connection.send(msg)
def _handle_ConnectionUp(self, event): ''' Add your logic here ... ''' for rule in rules: block = of.ofp_match() block.dl_src = EthAddr(rule[0]) block.dl_dst = EthAddr(rule[1]) flow_mod = of.ofp_flow_mod() flow_mod.match = block event.connection.send(flow_mod) log.debug("Firewall rules installed on %s", dpidToStr(event.dpid))
def _send_rewrite_rule (self, ip, mac): p = ipinfo(ip)[1] msg = of.ofp_flow_mod() msg.match = of.ofp_match() msg.match.dl_type = pkt.ethernet.IP_TYPE msg.match.nw_dst = ip msg.actions.append(of.ofp_action_dl_addr.set_src(self.mac)) msg.actions.append(of.ofp_action_dl_addr.set_dst(mac)) msg.actions.append(of.ofp_action_output(port=p)) self.connection.send(msg)