Exemplo n.º 1
0
	def _handle_GoingUpEvent(self,event):
		self.listenTo(core.openflow)
		self.listenTo(core.adaptiveThreatPrevention)
		Timer(10,self.updateThreshold, recurring=True)
Exemplo n.º 2
0
 def _handle_core_UpEvent(self, e):
     self.send_timer = Timer(self.SEND_TIMER, self._on_send, recurring=True)
Exemplo n.º 3
0
    def __init__(self):
        # This timer handles expiring stuff
        self._expire_timer = Timer(5, _handle_expiration, recurring=True)

        core.addListeners(self)
    def _handle_openflow_PacketIn(self, event):
        dpid = event.connection.dpid
        inport = event.port
        packet = event.parsed
        global set_Timer
        global defendDDOS
        global blockPort
        timerSet = False
        global diction

        def preventing():
            global diction
            global set_Timer
            if not set_Timer:
                set_Timer = True

            if len(diction) == 0:
                print("Empty diction ", str(event.connection.dpid),
                      str(event.port))
                diction[event.connection.dpid] = {}
                diction[event.connection.dpid][event.port] = 1
            elif event.connection.dpid not in diction:
                diction[event.connection.dpid] = {}
                diction[event.connection.dpid][event.port] = 1
            else:
                if event.connection.dpid in diction:
                    if event.port in diction[event.connection.dpid]:
                        temp_count = 0
                        temp_count = diction[event.connection.dpid][event.port]
                        temp_count = temp_count + 1
                        diction[event.connection.dpid][event.port] = temp_count
                        #print "*****************************************************************************************************************************************************************************"
                        print("dpid port and its packet count: ",
                              str(event.connection.dpid),
                              str(diction[event.connection.dpid]),
                              str(diction[event.connection.dpid][event.port]))
                        #print "*****************************************************************************************************************************************************************************"
                    else:
                        diction[event.connection.dpid][event.port] = 1

        def _timer_func():
            global diction
            global set_Timer

            if set_Timer == True:
                for k, v in diction.items():
                    for i, j in v.items():
                        if j >= 5:
                            print(
                                "_____________________________________________________________________________________________"
                            )
                            print(
                                "\n                               DDOS DETECTED                                              \n"
                            )
                            print("\n", str(diction))
                            print("\n", datetime.datetime.now(),
                                  ": BLOCKED PORT NUMBER  : ", str(i),
                                  " OF SWITCH ID: ", str(k))
                            print(
                                "\n___________________________________________________________________________________________"
                            )
                            os._exit(0)
                            dpid = k
                            msg = of.ofp_packet_out(in_port=i)
                            core.openflow.sendToDPID(dpid, msg)
            diction = {}

        if not packet.parsed:
            log.warning("%i %i ignoring unparsed packet", dpid, inport)
            return

        if dpid not in self.arpTable:
            self.arpTable[dpid] = {}
            for fake in self.fakeways:
                self.arpTable[dpid][IPAddr(fake)] = Entry(
                    of.OFPP_NONE, dpid_to_mac(dpid))

        if packet.type == ethernet.LLDP_TYPE:
            return

        if isinstance(packet.next, ipv4):
            log.debug("%i %i IP %s => %s", dpid, inport, packet.next.srcip,
                      packet.next.dstip)
            ent_obj.collectStats(event.parsed.next.dstip)
            print("Entropy : ", str(ent_obj.value))
            if ent_obj.value < 1.0:
                preventing()
                if timerSet is not True:
                    Timer(1, _timer_func, recurring=True)
                    timerSet = False
            else:
                timerSet = False

            self._send_lost_buffers(dpid, packet.next.srcip, packet.src,
                                    inport)

            if packet.next.srcip in self.arpTable[dpid]:
                if self.arpTable[dpid][packet.next.srcip] != (inport,
                                                              packet.src):
                    log.info("%i %i RE-learned %s", dpid, inport,
                             packet.next.srcip)
                    if self.wide:
                        msg = of.ofp_flow_mod(command=of.OFPFC_DELETE)
                        msg.match.nw_dst = packet.next.srcip
                        msg.match.dl_type = ethernet.IP_TYPE
                        event.connection.send(msg)
            else:
                log.debug("%i %i learned %s", dpid, inport, packet.next.srcip)
            self.arpTable[dpid][packet.next.srcip] = Entry(inport, packet.src)

            dstaddr = packet.next.dstip
            if dstaddr in self.arpTable[dpid]:

                prt = self.arpTable[dpid][dstaddr].port
                mac = self.arpTable[dpid][dstaddr].mac
                if prt == inport:
                    log.warning(
                        "%i %i not sending packet for %s back out of the "
                        "input port" % (dpid, inport, dstaddr))
                else:
                    log.debug(
                        "%i %i installing flow for %s => %s out port %i" %
                        (dpid, inport, packet.next.srcip, dstaddr, prt))

                    actions = []
                    actions.append(of.ofp_action_dl_addr.set_dst(mac))
                    actions.append(of.ofp_action_output(port=prt))
                    if self.wide:
                        match = of.ofp_match(dl_type=packet.type,
                                             nw_dst=dstaddr)
                    else:
                        match = of.ofp_match.from_packet(packet, inport)

                    msg = of.ofp_flow_mod(command=of.OFPFC_ADD,
                                          idle_timeout=FLOW_IDLE_TIMEOUT,
                                          hard_timeout=of.OFP_FLOW_PERMANENT,
                                          buffer_id=event.ofp.buffer_id,
                                          actions=actions,
                                          match=match)
                    event.connection.send(msg.pack())
            elif self.arp_for_unknowns:
                if (dpid, dstaddr) not in self.lost_buffers:
                    self.lost_buffers[(dpid, dstaddr)] = []
                bucket = self.lost_buffers[(dpid, dstaddr)]
                entry = (time.time() + MAX_BUFFER_TIME, event.ofp.buffer_id,
                         inport)
                bucket.append(entry)
                while len(bucket) > MAX_BUFFERED_PER_IP:
                    del bucket[0]

                self.outstanding_arps = {
                    k: v
                    for k, v in self.outstanding_arps.items()
                    if v > time.time()
                }

                if (dpid, dstaddr) in self.outstanding_arps:
                    return

                self.outstanding_arps[(dpid, dstaddr)] = time.time() + 4

                r = arp()
                r.hwtype = r.HW_TYPE_ETHERNET
                r.prototype = r.PROTO_TYPE_IP
                r.hwlen = 6
                r.protolen = r.protolen
                r.opcode = r.REQUEST
                r.hwdst = ETHER_BROADCAST
                r.protodst = dstaddr
                r.hwsrc = packet.src
                r.protosrc = packet.next.srcip
                e = ethernet(type=ethernet.ARP_TYPE,
                             src=packet.src,
                             dst=ETHER_BROADCAST)
                e.set_payload(r)
                log.debug("%i %i ARPing for %s on behalf of %s" %
                          (dpid, inport, r.protodst, r.protosrc))
                msg = of.ofp_packet_out()
                msg.data = e.pack()
                msg.actions.append(of.ofp_action_output(port=of.OFPP_FLOOD))
                msg.in_port = inport
                event.connection.send(msg)

        elif isinstance(packet.next, arp):
            a = packet.next
            log.debug("%i %i ARP %s %s => %s", dpid, inport, {
                arp.REQUEST: "request",
                arp.REPLY: "reply"
            }.get(a.opcode, 'op:%i' % (a.opcode, )), a.protosrc, a.protodst)

            if a.prototype == arp.PROTO_TYPE_IP:
                if a.hwtype == arp.HW_TYPE_ETHERNET:
                    if a.protosrc != 0:

                        if a.protosrc in self.arpTable[dpid]:
                            if self.arpTable[dpid][a.protosrc] != (inport,
                                                                   packet.src):
                                log.info("%i %i RE-learned %s", dpid, inport,
                                         a.protosrc)
                                if self.wide:
                                    msg = of.ofp_flow_mod(
                                        command=of.OFPFC_DELETE)
                                    msg.match.dl_type = ethernet.IP_TYPE
                                    msg.match.nw_dst = a.protosrc
                                    event.connection.send(msg)
                        else:
                            log.debug("%i %i learned %s", dpid, inport,
                                      a.protosrc)
                        self.arpTable[dpid][a.protosrc] = Entry(
                            inport, packet.src)

                        self._send_lost_buffers(dpid, a.protosrc, packet.src,
                                                inport)

                        if a.opcode == arp.REQUEST:

                            if a.protodst in self.arpTable[dpid]:

                                if not self.arpTable[dpid][
                                        a.protodst].isExpired():

                                    r = arp()
                                    r.hwtype = a.hwtype
                                    r.prototype = a.prototype
                                    r.hwlen = a.hwlen
                                    r.protolen = a.protolen
                                    r.opcode = arp.REPLY
                                    r.hwdst = a.hwsrc
                                    r.protodst = a.protosrc
                                    r.protosrc = a.protodst
                                    r.hwsrc = self.arpTable[dpid][
                                        a.protodst].mac
                                    e = ethernet(type=packet.type,
                                                 src=dpid_to_mac(dpid),
                                                 dst=a.hwsrc)
                                    e.set_payload(r)
                                    log.debug("%i %i answering ARP for %s" %
                                              (dpid, inport, r.protosrc))
                                    msg = of.ofp_packet_out()
                                    msg.data = e.pack()
                                    msg.actions.append(
                                        of.ofp_action_output(
                                            port=of.OFPP_IN_PORT))
                                    msg.in_port = inport
                                    event.connection.send(msg)
                                    return

            log.debug("%i %i flooding ARP %s %s => %s" % (dpid, inport, {
                arp.REQUEST: "request",
                arp.REPLY: "reply"
            }.get(a.opcode, 'op:%i' % (a.opcode, )), a.protosrc, a.protodst))

            msg = of.ofp_packet_out(
                in_port=inport,
                data=event.ofp,
                action=of.ofp_action_output(port=of.OFPP_FLOOD))
            event.connection.send(msg)
Exemplo n.º 5
0
class l3_switch(EventMixin):
    #Both maps help us convert Virtual to Real IP
    R2V_Map = {
        "10.0.0.1": "",
        "10.0.0.2": "",
        "10.0.0.3": "",
        "10.0.0.4": "",
        "10.0.0.5": "",
        "10.0.0.6": "",
        "10.0.0.7": "",
        "10.0.0.8": "",
        "10.0.0.9": "",
        "10.0.0.10": "",
        "10.0.0.11": "",
        "10.0.0.12": "",
        "10.0.0.13": "",
        "10.0.0.14": "",
        "10.0.0.15": "",
        "10.0.0.16": "",
        "10.0.0.17": "",
        "10.0.0.18": "",
        "10.0.0.19": "",
        "10.0.0.20": ""
    }
    V2R_Map = {}

    def __init__(self, fakeways=[], arp_for_unknowns=False):
        # "t1" thread performs TimerEventGen function. It contains a while loop that every 4 seconds
        # changes the virtual IP of the hosts by calling the sub-function "_move_the_target"
        def TimerEventGen():
            self._move_the_target()
            while 1:
                time.sleep(15)
                self._move_the_target()
                #print "After Timer"

        # These are "fake gateways" -- we'll answer ARPs for them with MAC
        # of the switch they're connected to.
        self.fakeways = set(fakeways)

        # If this is true and we see a packet for an unknown
        # host, we'll ARP for it.
        self.arp_for_unknowns = arp_for_unknowns

        # (dpid,IP) -> expire_time
        # We use this to keep from spamming ARPs
        self.outstanding_arps = {}

        # (dpid,IP) -> [(expire_time,buffer_id,in_port), ...]
        # These are buffers we've gotten at this datapath for this IP which
        # we can't deliver because we don't know where they go.
        self.lost_buffers = {}

        # For each switch, we map IP addresses to Entries
        self.arpTable = {}

        # This timer handles expiring stuff
        self._expire_timer = Timer(2, self._handle_expiration, recurring=True)
        self.listenTo(core)
        #Here we call TimeEventGen that performs bt t1 thread
        t1 = threading.Thread(target=TimerEventGen)
        t1.start()
        # self.HostMem is another dictionary that links host's IP address to datapath id (dpid) parameter
        self.HostMem = {}
        self.IP_Packets_Table = {}
        self.count = 0
        self.packetin = 0

    def _move_the_target(self):
        #log.debug("timer success")
        #random.seed(time())
        pseudo_ranum = random.randint(21, N_IP - 1)
        print("Random Number:", pseudo_ranum)
        for keys in self.R2V_Map.keys():
            #self.R2V_Map[keys] = "10.0."+ str(random.randint(0, 9)) +"." + str(pseudo_ranum)  #space: 5*80
            self.R2V_Map[keys] = "10." + "0" + "." + "0" + "." + str(
                pseudo_ranum)
            #print self.R2V_Map[keys]
            # pseudo_ranum is updated to point to next index (cyclic)
            pseudo_ranum = (pseudo_ranum + 1) % N_IP
        self.V2R_Map = {v: k for k, v in self.R2V_Map.items()}
        print "**********", self.R2V_Map, "***********"
        print "**********", self.V2R_Map, "***********"

# create ofp_flow_mod message to delete all flows
# (note that flow_mods match all flows by default)
#msg = of.ofp_flow_mod(command=of.OFPFC_DELETE)

# iterate over all connected switches and delete all their flows
#	for connection in core.openflow.connections: # _connections.values() before betta
# 		connection.send(msg)
#log.debug("Clearing all flows from %s." % (dpidToStr(connection.dpid),))

    def isRealIPAddress(self, ipAddr):
        '''Returns True id IP address is real'''
        #print ipAddr
        if ipAddr in self.R2V_Map.keys():
            return True

    def isVirtualIPAddress(self, ipAddr):
        ''' Returns True if the IP address is virtual'''
        #print ipAddr
        if ipAddr in self.R2V_Map.values():
            return True

    def ReturnRealIP(self, ipAddr):
        ip2 = '10.0.0.3'
        if ipAddr in self.R2V_Map.keys():
            ip2 = ipAddr
        elif ipAddr in self.R2V_Map.values():
            #print("Changing DST Virtual IP " + ipAddr + "---> Real DST IP " + V2R_Map[ipAddr])
            ip2 = V2R_Map[ipAddr]
        #print ipAddr
        return ip2

    ########################################################

    def _handle_expiration(self):
        # Called by a timer so that we can remove old items.
        empty = []
        for k, v in self.lost_buffers.iteritems():
            dpid, ip = k

            for item in list(v):
                expires_at, buffer_id, in_port = item
                if expires_at < time.time():
                    # This packet is old.  Tell this switch to drop it.
                    v.remove(item)
                    po = of.ofp_packet_out(buffer_id=buffer_id,
                                           in_port=in_port)
                    core.openflow.sendToDPID(dpid, po)
            if len(v) == 0: empty.append(k)

        # Remove empty buffer bins
        for k in empty:
            del self.lost_buffers[k]

    def _send_lost_buffers(self, dpid, ipaddr, macaddr, port):
        """
    We may have "lost" buffers -- packets we got but didn't know
    where to send at the time.  We may know now.  Try and see.
    """
        if (dpid, ipaddr) in self.lost_buffers:
            # Yup!
            bucket = self.lost_buffers[(dpid, ipaddr)]
            del self.lost_buffers[(dpid, ipaddr)]
            #log.debug("Sending %i buffered packets to %s from %s"
            #         % (len(bucket),ipaddr,dpid_to_str(dpid)))
            for _, buffer_id, in_port in bucket:
                po = of.ofp_packet_out(buffer_id=buffer_id, in_port=in_port)
                po.actions.append(of.ofp_action_dl_addr.set_dst(macaddr))
                po.actions.append(of.ofp_action_output(port=port))
                core.openflow.sendToDPID(dpid, po)

    def _handle_GoingUpEvent(self, event):
        self.listenTo(core.openflow)
        log.debug("Up...")

    def handle_timer_elapse(message):
        print "I was told to tell you:", message

    Timer(10, handle_timer_elapse, args=["Hello"])

    def _handle_PacketIn(self, event):
        self.packetin = self.packetin + 1
        dpid = event.connection.dpid
        inport = event.port

        packet = 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
            print "new switch"
            self.arpTable[dpid] = {}

            for fake in self.fakeways:
                self.arpTable[dpid][IPAddr(fake)] = Entry(
                    of.OFPP_NONE, dpid_to_mac(dpid))

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

        flag = 0
        # This part of code handles packet in and write to file.py count variable that informs
        # us how many malicious packets Arrived to Virtual IPs
        ###################################################################################################
        if isinstance(packet.next, ipv4):
            if (self.isVirtualIPAddress(str(packet.next.dstip))):
                flag = 1
            elif (self.isRealIPAddress(str(packet.next.dstip))):
                flag = 1
            if (flag == 0):
                print "Unknown IP: %s,Dropping packet" % str(packet.next.dstip)

        if isinstance(packet.next, arp):
            print "after if arp: %s " % str(packet.next.protodst)

            if (self.isVirtualIPAddress(str(packet.next.protodst))):
                flag = 1
                self.count = self.count + 1
                print "$$$$$$$$$$ count = %i $$$$$$$$$$" % self.count
            if (flag == 0):
                print "Unknown IP: %s,Dropping packet" % str(
                    packet.next.protodst)
        f = open('file.py', 'w')
        f.write('count = ' + str(self.count) + '   ' + 'num of packts in:' +
                ' ' + str(self.packetin) + '\n')
        f.close()
        ########################################################################################

        # handling IPV4 packets
        if isinstance(packet.next, ipv4):
            log.debug("%i %i IP %s => %s", dpid, inport, packet.next.srcip,
                      packet.next.dstip)
            srcaddr = packet.next.srcip
            srcaddr_old = packet.next.srcip
            dstaddr = packet.next.dstip
            dstaddr_old = packet.next.dstip
            # if source is virtual we change it to real
            if self.isVirtualIPAddress(str(srcaddr)):
                srcaddr = IPAddr(self.V2R_Map[str(srcaddr)])
                print("Changing SRC VIRTUAL IP " + self.R2V_Map[str(srcaddr)] +
                      "---> REAL SRC IP " + str(srcaddr))

# if destination is virtual we change it to real
            if self.isVirtualIPAddress(str(dstaddr)):
                dstaddr = IPAddr(self.V2R_Map[str(dstaddr)])
                print("Changing DST VIRTUAL IP " + self.R2V_Map[str(dstaddr)] +
                      "---> REAL SRC IP " + str(dstaddr))
# if the IP was real we update HostMem (ip---dpid) mapping
            if self.isRealIPAddress(
                    str(srcaddr_old)) and srcaddr not in self.HostMem.keys():
                self.HostMem[srcaddr] = dpid
            dpid = self.HostMem[srcaddr]
            if self.isRealIPAddress(
                    str(dstaddr_old)) and dstaddr not in self.HostMem.keys():
                self.HostMem[dstaddr] = dpid
            dpid = self.HostMem[dstaddr]

            #update the correct macaddr
            if self.isVirtualIPAddress(str(srcaddr_old)):
                macaddr = dpid_to_mac(dpid)
            else:
                macaddr = packet.src
            self._send_lost_buffers(dpid, srcaddr, macaddr, inport)
            # Learn or update the correct port/MAC fron arpTable
            if srcaddr in self.arpTable[dpid]:
                if self.arpTable[dpid][srcaddr] != (inport, macaddr):
                    log.info("%i %i RE-learned %s", dpid, inport, srcaddr)
            else:
                log.debug("%i %i learned %s", dpid, inport, str(srcaddr))
            # if source was real update arpTable
            if (self.isRealIPAddress(str(srcaddr_old))):
                self.arpTable[dpid][srcaddr] = Entry(inport, macaddr)
            # if source was virtual take the correct values from arpTable
# mininet give us wrong values when we use virtual IP
            if self.isVirtualIPAddress(str(srcaddr_old)):
                inport = self.arpTable[dpid][srcaddr].port
                macaddr = self.arpTable[dpid][srcaddr].mac

            # if we have a destination forward the packet
            if dstaddr in self.arpTable[dpid]:

                prt = self.arpTable[dpid][dstaddr].port
                mac = self.arpTable[dpid][dstaddr].mac
                if prt == inport:
                    log.warning(
                        "%i %i not sending packet for %s back out of the " +
                        "input port" % (dpid, inport, str(dstaddr)))
                else:
                    log.debug(
                        "%i %i installing flow for %s => %s out port %i" %
                        (dpid, inport, srcaddr, dstaddr, prt))

                    actions = []
                    actions.append(of.ofp_action_dl_addr.set_dst(mac))
                    actions.append(of.ofp_action_output(port=prt))
                    match = of.ofp_match.from_packet(packet, inport)
                    match.dl_src = None  # Wildcard source MAC

                    msg = of.ofp_flow_mod(command=of.OFPFC_ADD,
                                          idle_timeout=FLOW_IDLE_TIMEOUT,
                                          hard_timeout=of.OFP_FLOW_PERMANENT,
                                          buffer_id=event.ofp.buffer_id,
                                          actions=actions,
                                          match=of.ofp_match.from_packet(
                                              packet, inport))
                    event.connection.send(msg.pack())
# if we don't have a destination drop the packet.
            elif not (self.isRealIPAddress(
                    str(dstaddr))) or not (self.isRealIPAddress(str(srcaddr))):
                po = of.ofp_packet_out(buffer_id=buffer_id, in_port=in_port)
                core.openflow.sendToDPID(dpid, po)
                log.warning(
                    "Moving Targed Defense has blocked a packet from unknown source"
                )

# handles arp packet
        elif isinstance(packet.next, arp):
            a = packet.next

            log.debug("%i %i ARP %s %s => %s", dpid, inport, {
                arp.REQUEST: "request",
                arp.REPLY: "reply"
            }.get(a.opcode, 'op:%i' % (a.opcode, )), str(a.protosrc),
                      str(a.protodst))
            dstaddr2 = a.protodst
            dstaddr2_old = a.protodst
            srcaddr2 = a.protosrc
            srcaddr2_old = srcaddr2

            if self.isVirtualIPAddress(str(srcaddr2)):
                srcaddr2 = IPAddr(self.V2R_Map[str(srcaddr2)])
                print("arp: Changing SRC VIRTUAL IP " +
                      self.R2V_Map[str(srcaddr2)] + "---> REAL SRC IP " +
                      str(srcaddr2))
            if self.isVirtualIPAddress(str(dstaddr2)):
                dstaddr2 = IPAddr(self.V2R_Map[str(dstaddr2)])
                print("arp: Changing DST VIRTUAL IP " +
                      self.R2V_Map[str(dstaddr2)] + "---> REAL DST IP " +
                      str(dstaddr2))
            if self.isRealIPAddress(
                    str(srcaddr2_old)) and srcaddr2 not in self.HostMem.keys():
                self.HostMem[srcaddr2] = dpid
            if self.isRealIPAddress(
                    str(dstaddr2_old)) and dstaddr2 not in self.HostMem.keys():
                self.HostMem[dstaddr2] = dpid
            dpid = self.HostMem[srcaddr2]
            if self.isVirtualIPAddress(str(srcaddr2_old)):
                macaddr = dpid_to_mac(dpid)
            else:
                macaddr = packet.src
            #macaddr = self.arpTable[dpid][srcaddr2].mac
            a.prototype = arp.PROTO_TYPE_IP
            a.hwtype = arp.HW_TYPE_ETHERNET

            if srcaddr2 != 0:

                # Learn or update port/MAC info
                if srcaddr2 in self.arpTable[dpid]:
                    if self.arpTable[dpid][srcaddr2] != (inport, macaddr):
                        log.info("%i %i RE-learned %s", dpid, inport,
                                 str(srcaddr2))
                else:
                    log.debug("%i %i learned %s", dpid, inport, str(srcaddr2))
                if (self.isRealIPAddress(str(srcaddr2_old))):
                    self.arpTable[dpid][srcaddr2] = Entry(inport, macaddr)
                if self.isVirtualIPAddress(str(srcaddr2_old)):
                    #for keys,values in self.HostMem :
                    # print (keys)
                    #print (values)
                    inport = self.arpTable[dpid][srcaddr2].port
                # Send any waiting packets...
                self._send_lost_buffers(dpid, str(srcaddr2), macaddr, inport)

                if a.opcode == arp.REQUEST:
                    # Check if we can answer
                    dstaddr2 = a.protodst

                    if dstaddr2 in self.arpTable[dpid]:
                        # destination exists

                        if not self.arpTable[dpid][dstaddr2].isExpired():

                            # We will reply ourselves

                            r = arp()
                            r.hwtype = a.hwtype
                            r.prototype = a.prototype
                            r.hwlen = a.hwlen
                            r.protolen = a.protolen
                            r.opcode = arp.REPLY
                            r.hwdst = a.hwsrc
                            r.protodst = IPAddr(self.ReturnRealIP(srcaddr2))
                            r.protosrc = IPAddr(self.ReturnRealIP(dstaddr2))
                            r.hwsrc = self.arpTable[dpid][dstaddr2].mac
                            e = ethernet(type=packet.type,
                                         src=dpid_to_mac(dpid),
                                         dst=a.hwsrc)
                            e.set_payload(r)
                            log.debug("%i %i answering ARP for %s" %
                                      (dpid, inport, str(r.protosrc)))
                            msg = of.ofp_packet_out()
                            msg.data = e.pack()
                            msg.actions.append(
                                of.ofp_action_output(port=of.OFPP_IN_PORT))
                            msg.in_port = inport
                            event.connection.send(msg)
                            return

# if source and dest were not virtual or real we dropp the packet
                    elif not (self.isRealIPAddress(str(dstaddr2))) or not (
                            self.isRealIPAddress(str(srcaddr2))):
                        po = of.ofp_packet_out(buffer_id=buffer_id,
                                               in_port=in_port)
                        core.openflow.sendToDPID(dpid, po)
                        log.warning(
                            "Moving Targed Defense has blocked a packet from unknown source"
                        )

            srcaddr2_old = srcaddr2

            # unrecognized arp: if source is recognized av Virtual or Real than
            # we flood the packet throgh the network

            if self.isVirtualIPAddress(str(srcaddr2)):
                srcaddr2 = IPAddr(self.V2R_Map[str(srcaddr2)])
                print("arp flood: Changing SRC VIRTUAL IP " +
                      self.R2V_Map[str(srcaddr2)] + "---> REAL SRC IP " +
                      str(srcaddr2))
            if self.isVirtualIPAddress(str(dstaddr2)):
                dstaddr2 = IPAddr(self.V2R_Map[str(dstaddr2)])
                print("arp flood: Changing DST VIRTUAL IP " +
                      self.R2V_Map[str(dstaddr2)] + "---> REAL DST IP " +
                      str(dstaddr2))
            if self.isRealIPAddress(
                    str(srcaddr2_old)) and srcaddr2 not in self.HostMem.keys():
                self.HostMem[srcaddr2] = dpid
            dpid = self.HostMem[srcaddr2]
            macaddr = self.arpTable[dpid][srcaddr2].mac
            macaddr = dpid_to_mac(dpid)
            if self.isVirtualIPAddress(str(srcaddr2_old)):
                inport = self.arpTable[dpid][srcaddr2].port
            # just flood it
            log.debug("%i %i flooding ARP %s %s => %s" % (dpid, inport, {
                arp.REQUEST: "request",
                arp.REPLY: "reply"
            }.get(a.opcode, 'op:%i' %
                  (a.opcode, )), str(srcaddr2), str(dstaddr2)))
            msg = of.ofp_packet_out(
                in_port=inport,
                data=event.ofp,
                action=of.ofp_action_output(port=of.OFPP_FLOOD))
            event.connection.send(msg)
Exemplo n.º 6
0
def launch():
    from pox.lib.recoco import Timer
    core.registerNew(Phase1)

    global INTERVAL
    Timer(INTERVAL, core.Phase1.timer_func, recurring=True)
Exemplo n.º 7
0
def new_timer(t, f):
    return Timer(t, f)
Exemplo n.º 8
0
def launch():
    core.registerNew(l2_multi)

    timeout = min(max(PATH_SETUP_TIME, 5) * 2, 15)
    Timer(timeout, WaitingPath.expire_waiting_paths, recurring=True)
    thread.start_new_thread(generate_channel, ())  ###get channel thread
Exemplo n.º 9
0
def launch ():
  Timer(5,check_flows,recurring = True)
  core.openflow.addListenerByName("ConnectionUp", _handle_ConnectionUp)
  core.openflow.addListenerByName("PacketIn",_handle_PacketIn)
Exemplo n.º 10
0
 def start(self, **kwargs):
     Timer(self.CHECK_TIME, self.request_switch_statistics, recurring=True)
Exemplo n.º 11
0
 def pushRTHelper(self):
     self.pushRT()
     Timer(LocalViro.UPDATE_RT_TIME, self.pushRTHelper)
Exemplo n.º 12
0
 def __init__(self):
     self._session_key_salt = str(time.time()) + "POX"
     self._connections = {}
     #self._t = Timer(5, self._check_timeouts, recurring=True)
     self._t = Timer(60 * 2, self._check_timeouts, recurring=True)
Exemplo n.º 13
0
    def _handle_FlowStatsReceived(self, event):
        print("FlowStatsReceived")
        for f in event.stats:

            #print(f.__dict__)
            #print(f.actions[0].__dict__)
            #print(f.match)

            flow = Flow(f.match.nw_src, f.match.nw_dst,
                        f.match.tp_src if hasattr(f.match, 'tp_src') else None,
                        f.match.tp_dst if hasattr(f.match, 'tp_dst') else None,
                        f.match)
            if flow in self.flows:
                # Flow exists: Assign flow to the flow variable
                index = self.flows.index(flow)
                flow = self.flows[index]
            else:
                # Flow doesn't exists: Add flow to list
                self.flows.append(flow)
                # Try to find the Full Flow:
                fullFlow = FullFlow(
                    Flow(flow.dst, flow.src, flow.tp_dst, flow.tp_src))
                if fullFlow in self.fullFlows:
                    index = self.fullFlows.index(fullFlow)
                    fullFlow = self.fullFlows[index]
                    fullFlow.addBackward(flow)
                else:
                    self.fullFlows.append(FullFlow(flow))
            # Add reading to flow
            flow.add(f.duration_sec, f.byte_count, f.packet_count)
        # if os.path.exists(file):
        # 	os.remove(file)
        for f in self.fullFlows:
            #f.printValues()
            if f.isFlow():
                f.printStats()
            # Blocking Logic
            # if f.forward.needsBlocking():
            # 	# Block Flow
            # 	print("-------------------------------------")
            # 	print("Blocking flow: {}", f.forward.description())
            # 	msg = of.ofp_flow_mod()
            # 	msg.command = 1 # OFPFC_MODIFY
            # 	msg.match = f.forward.match
            # 	msg.idle_timeout = 0
            # 	msg.hard_timeout = 0
            # 	msg.actions = []
            # 	event.connection.send(msg)
            # 	f.forward.blocked = True
            # if hasattr(f, 'backward') and f.backward.needsBlocking():
            # 	# Block Flow
            # 	print("-------------------------------------")
            # 	print("Blocking flow: {}", f.backward.description())
            # 	msg = of.ofp_flow_mod()
            # 	msg.command = 1  # OFPFC_MODIFY
            # 	msg.match = f.backward.match
            # 	msg.idle_timeout = 0
            # 	msg.hard_timeout = 0
            # 	msg.actions = []
            # 	event.connection.send(msg)
            # 	f.backward.blocked = True

        Timer(self.interval, self.sendTableStatsRequest, args=[event])
Exemplo n.º 14
0
 def __init__(self):
     "Declaring listeners of OpenFlow events. In this application we are going to hear 'ConnectionUp', 'PacketIn' and 'FlowStats' events"
     self.listenTo(core.openflow)
     "Declaring a timer to periodically (1s) call the method 'request_stats', which will request"
     Timer(1, self.request_stats, recurring=True)
Exemplo n.º 15
0
 def send_table(self):
     if self.pending: return
     self.pending = True
     Timer(.2, self._do_send_table, recurring=False)
Exemplo n.º 16
0
 def startup ():
   self.HOST_TIMEOUT = 15                # time (in seconds) to perform cleanup, generally it should be greater than expected HARD_TIMEOUTs
   Timer(self.HOST_TIMEOUT, self.host_refresh, recurring=True)
   core.openflow.addListeners(self, priority=0)
   core.openflow_discovery.addListeners(self)
def launch():
    core.openflow.addListenerByName("ConnectionUp", _handle_ConnectionUp)
    core.openflow.addListenerByName("PacketIn", _handle_PacketIn)
    core.openflow.addListenerByName("PortStatsReceived",
                                    _handle_portstats_received)
    Timer(5, _timer_func, recurring=True)
 def _handle_TableStatsReceived(self, event):
     sw = 's%s' % event.dpid
     self.tableActiveCount[sw] = event.stats[0].active_count
     print "TableStatsReceived"
     print self.tableActiveCount
     Timer(self.interval, self.sendTableStatsRequest, args=[event])
Exemplo n.º 19
0
 def trigger_update(self):
     if self.triggered_pending: return
     self.triggered_pending = True
     t = Timer(self.TRIGGERED_TIMER, self._on_triggered_update)
Exemplo n.º 20
0
 def _handle_timer (self):
   self.t = Timer(1, self._handle_timer)
   for sw in self.switches.values():
     sw._handle_timer()
	def _handle_GoingUpEvent (self, event):
		self.listenTo(core.openflow)    
		Timer(5, self._timely_flow_stats, recurring=True)
Exemplo n.º 22
0
              or str(flow.match.nw_dst) == "100.100.100.2"):
            if (event.connection.dpid == 1):
                pkt_info["packet_count"] = flow.packet_count
                pkt_info["src_port"] = flow.match.tp_src
                web_packet[str(flow.match.nw_src)] = pkt_info
        else:
            print("didn't go to any of the host")

    for ip, pinfo in web_packet.items():
        #if (packet_count != "0"):
        print("IP: %s  Source Port: %s  Packet Counts: %s  " %
              (ip, pinfo["src_port"], pinfo["packet_count"]))

    #log.debug("FlowStatsReceived from %s: %s", dpidToStr(event.connection.dpid), stats)
    #for flow in event.stats:
    #print (stats)


#attach handlers to listenrs
#Listens for the swithces' response to the flow_stats_request
core.openflow.addListenerByName("FlowStatsReceived",
                                _handle_flowstats_received)

#
Timer(0.1, _timer_func, recurring=True)
#Timer(0.5, _screen_output, recurring=True)

#h1: dl_src = 4a:39:6e:1e:3a:21
#h2: dl_src = 56:56:37:29:10:e9
#h3: dl_src = e2:a9:50:b6:9d:a2
#h4: dl_src = ea:61:0f:0a:5c:e4
Exemplo n.º 23
0
    def clientThread(self, conn):
        #wait for HELLO message
        helloReceived = False
        while not helloReceived:
            message_json = json.loads(conn.recv(2048))
            if message_json['message_type'] == 'HELLO':
                print json.dumps(message_json,
                                 sort_keys=True,
                                 indent=4,
                                 separators=(',', ':'))
                helloReceived = True

        #send MENU message
        self.sendMenu(conn)

        #receive ORDER message
        message_json = json.loads(conn.recv(2048))
        print json.dumps(message_json,
                         sort_keys=True,
                         indent=4,
                         separators=(',', ':'))

        if (message_json['message_type'] == 'PREORDER'):
            print "GOT PREORDER"
            preorder = message_json['data']
            preorder = json.loads(preorder)
            level = preorder['level']
            ip1 = preorder['ip1']
            ip2 = preorder['ip2']

            result = self.controller.preorder(ip1, ip2, level)

            print "PREORDER RESULT: " + str(result)

            if (result):
                self.sendPreorderResponse(conn, "TRUE")
            else:
                self.sendPreorderResponse(conn, "FALSE")

        elif (message_json['message_type'] == 'ORDER'):
            print "GOT ORDER"
            #read ORDER and verify on IOTA network that client payed (optional)
            payment_id = message_json['verification']
            signature = message_json['signature']
            order = message_json['data']
            order = json.loads(order)
            level = order['level']
            buyer_address = order['address']
            buyer_key = order['public-key']
            ip1 = order['ip1']
            ip2 = order['ip2']

            #skipping verification for now

            #raise event ServiceChanged (controller listens)
            if 'time' in order:
                time = order['time']
                self.raiseEvent(ServiceChanged(ip1, ip2, level, "ADD"))
                Timer(int(time),
                      self.raiseEvent,
                      args=[ServiceChanged(ip1, ip2, level, "REMOVE")])

            else:
                self.raiseEvent(ServiceChanged(ip1, ip2, level, "ADD"))
Exemplo n.º 24
0
 def __init__(self, nexus=None):
     Transport.__init__(self, nexus)
     self._connections = {}
     self._t = Timer(SESSION_TIMEOUT, self._check_timeouts, recurring=True)
Exemplo n.º 25
0
    def _handle_openflow_PacketIn(self, event):
        dpid = event.connection.dpid
        inport = event.port
        packet = event.parsed
        global set_Timer
        global defendDDOS
        global blockPort
        timerSet = False
        global diction

        def preventing():
            global diction
            global set_Timer
            if not set_Timer:
                set_Timer = True
            #Timer(1, _timer_func(), recurring=True)

            #print"\n\n*********new packetIN************"
            if len(diction) == 0:
                print("Enpty diction ", str(event.connection.dpid),
                      str(event.port))
                diction[event.connection.dpid] = {}
                diction[event.connection.dpid][event.port] = 1
            elif event.connection.dpid not in diction:
                diction[event.connection.dpid] = {}
                diction[event.connection.dpid][event.port] = 1
                #print "ERROR"
            else:
                if event.connection.dpid in diction:
                    # temp = diction[event.connection.dpid]
                    #print(temp)
                    #print "error check " , str(diction[event.connection.dpid][event.port])
                    if event.port in diction[event.connection.dpid]:
                        temp_count = 0
                        temp_count = diction[event.connection.dpid][event.port]
                        temp_count = temp_count + 1
                        diction[event.connection.dpid][event.port] = temp_count
                        #print "printting dpid port number and its packet count: ",  str(event.connection.dpid), str(diction[event.connection.dpid]), str(diction[event.connection.dpid][event.port])
                    else:
                        diction[event.connection.dpid][event.port] = 1

            print "\n", datetime.datetime.now(), ": printing diction ", str(
                diction), "\n"

        def _timer_func():
            global diction
            global set_Timer
            if set_Timer == True:
                #print datetime.datetime.now(),": calling timer fucntion now!!!!!"
                for k, v in diction.iteritems():
                    for i, j in v.iteritems():
                        if j >= 50:
                            print "_____________________________________________________________________________________________"
                            print "\n", datetime.datetime.now(
                            ), "*******    DDOS DETECTED   ********"
                            print "\n", str(diction)
                            print "\n", datetime.datetime.now(
                            ), ": BLOCKED PORT NUMBER  : ", str(
                                i), " OF SWITCH ID: ", str(k)
                            print "\n_____________________________________________________________________________________________"

                            #self.dropDDOS ()
                            dpid = k
                            msg = of.ofp_packet_out(in_port=i)
                            #msg.priority=42
                            #msg.in_port = event.port
                            #po = of.ofp_packet_out(buffer_id = buffer_id, in_port = in_port)
                            core.openflow.sendToDPID(dpid, msg)

            diction = {}

        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))

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

        if isinstance(packet.next, ipv4):
            log.debug("%i %i IP %s => %s", dpid, inport, packet.next.srcip,
                      packet.next.dstip)
            ent_obj.statcolect(event.parsed.next.dstip)  #editing
            print "\n***** Entropy Value = ", str(ent_obj.value), "*****\n"
            if ent_obj.value < 0.5:
                preventing()
                if timerSet is not True:
                    Timer(2, _timer_func, recurring=True)
                    timerSet = False
            else:
                timerSet = False

            # Send any waiting packets...
            self._send_lost_buffers(dpid, packet.next.srcip, packet.src,
                                    inport)

            # Learn or update port/MAC info
            if packet.next.srcip in self.arpTable[dpid]:
                if self.arpTable[dpid][packet.next.srcip] != (inport,
                                                              packet.src):
                    log.info("%i %i RE-learned %s", dpid, inport,
                             packet.next.srcip)
                    if self.wide:
                        # Make sure we don't have any entries with the old info...
                        msg = of.ofp_flow_mod(command=of.OFPFC_DELETE)
                        msg.match.nw_dst = packet.next.srcip
                        msg.match.dl_type = ethernet.IP_TYPE
                        event.connection.send(msg)
            else:
                log.debug("%i %i learned %s", dpid, inport, packet.next.srcip)
            self.arpTable[dpid][packet.next.srcip] = Entry(inport, packet.src)
            #nandan: getting source ip address from the packetIn
            #myPacketInSrcIP= packet.next.srcip
            #myPacketInSrcEth= packet.src
            #myPacketInDstIP= packet.next.dstip
            #myPacketInDstEth= packet.dst

            #print "switcID: "+str(dpid)+" ,Port: "+str(event.port)+" ,MAC address: "+str(myPacketInSrcEth)+" ,SrcIP: "+ str(myPacketInSrcIP)+", Dst Mac: "+str(myPacketInDstEth)+", Dst IP: "+str(myPacketInDstEth)
            # Try to forward
            dstaddr = packet.next.dstip
            if dstaddr in self.arpTable[dpid]:
                # We have info about what port to send it out on...

                prt = self.arpTable[dpid][dstaddr].port
                mac = self.arpTable[dpid][dstaddr].mac
                if prt == inport:
                    log.warning(
                        "%i %i not sending packet for %s back out of the "
                        "input port" % (dpid, inport, dstaddr))
                else:
                    log.debug(
                        "%i %i installing flow for %s => %s out port %i" %
                        (dpid, inport, packet.next.srcip, dstaddr, prt))

                    actions = []
                    actions.append(of.ofp_action_dl_addr.set_dst(mac))
                    actions.append(of.ofp_action_output(port=prt))
                    if self.wide:
                        match = of.ofp_match(dl_type=packet.type,
                                             nw_dst=dstaddr)
                    else:
                        match = of.ofp_match.from_packet(packet, inport)

                    msg = of.ofp_flow_mod(command=of.OFPFC_ADD,
                                          idle_timeout=FLOW_IDLE_TIMEOUT,
                                          hard_timeout=of.OFP_FLOW_PERMANENT,
                                          buffer_id=event.ofp.buffer_id,
                                          actions=actions,
                                          match=match)
                    event.connection.send(msg.pack())
            elif self.arp_for_unknowns:
                # We don't know this destination.
                # First, we track this buffer so that we can try to resend it later
                # if we learn the destination, second we ARP for the destination,
                # which should ultimately result in it responding and us learning
                # where it is

                # Add to tracked buffers
                if (dpid, dstaddr) not in self.lost_buffers:
                    self.lost_buffers[(dpid, dstaddr)] = []
                bucket = self.lost_buffers[(dpid, dstaddr)]
                entry = (time.time() + MAX_BUFFER_TIME, event.ofp.buffer_id,
                         inport)
                bucket.append(entry)
                while len(bucket) > MAX_BUFFERED_PER_IP:
                    del bucket[0]

                # Expire things from our outstanding ARP list...
                self.outstanding_arps = {
                    k: v
                    for k, v in self.outstanding_arps.iteritems()
                    if v > time.time()
                }

                # Check if we've already ARPed recently
                if (dpid, dstaddr) in self.outstanding_arps:
                    # Oop, we've already done this one recently.
                    return

                # And ARP...
                self.outstanding_arps[(dpid, dstaddr)] = time.time() + 4

                r = arp()
                r.hwtype = r.HW_TYPE_ETHERNET
                r.prototype = r.PROTO_TYPE_IP
                r.hwlen = 6
                r.protolen = r.protolen
                r.opcode = r.REQUEST
                r.hwdst = ETHER_BROADCAST
                r.protodst = dstaddr
                r.hwsrc = packet.src
                r.protosrc = packet.next.srcip
                e = ethernet(type=ethernet.ARP_TYPE,
                             src=packet.src,
                             dst=ETHER_BROADCAST)
                e.set_payload(r)
                log.debug("%i %i ARPing for %s on behalf of %s" %
                          (dpid, inport, r.protodst, r.protosrc))
                msg = of.ofp_packet_out()
                msg.data = e.pack()
                msg.actions.append(of.ofp_action_output(port=of.OFPP_FLOOD))
                msg.in_port = inport
                event.connection.send(msg)

        elif isinstance(packet.next, arp):
            a = packet.next
            log.debug("%i %i ARP %s %s => %s", dpid, inport, {
                arp.REQUEST: "request",
                arp.REPLY: "reply"
            }.get(a.opcode, 'op:%i' % (a.opcode, )), a.protosrc, a.protodst)

            if a.prototype == arp.PROTO_TYPE_IP:
                if a.hwtype == arp.HW_TYPE_ETHERNET:
                    if a.protosrc != 0:

                        # Learn or update port/MAC info
                        if a.protosrc in self.arpTable[dpid]:
                            if self.arpTable[dpid][a.protosrc] != (inport,
                                                                   packet.src):
                                log.info("%i %i RE-learned %s", dpid, inport,
                                         a.protosrc)
                                if self.wide:
                                    # Make sure we don't have any entries with the old info...
                                    msg = of.ofp_flow_mod(
                                        command=of.OFPFC_DELETE)
                                    msg.match.dl_type = ethernet.IP_TYPE
                                    msg.match.nw_dst = a.protosrc
                                    event.connection.send(msg)
                        else:
                            log.debug("%i %i learned %s", dpid, inport,
                                      a.protosrc)
                        self.arpTable[dpid][a.protosrc] = Entry(
                            inport, packet.src)

                        # Send any waiting packets...
                        self._send_lost_buffers(dpid, a.protosrc, packet.src,
                                                inport)

                        if a.opcode == arp.REQUEST:
                            # Maybe we can answer

                            if a.protodst in self.arpTable[dpid]:
                                # We have an answer...

                                if not self.arpTable[dpid][
                                        a.protodst].isExpired():
                                    # .. and it's relatively current, so we'll reply ourselves

                                    r = arp()
                                    r.hwtype = a.hwtype
                                    r.prototype = a.prototype
                                    r.hwlen = a.hwlen
                                    r.protolen = a.protolen
                                    r.opcode = arp.REPLY
                                    r.hwdst = a.hwsrc
                                    r.protodst = a.protosrc
                                    r.protosrc = a.protodst
                                    r.hwsrc = self.arpTable[dpid][
                                        a.protodst].mac
                                    e = ethernet(type=packet.type,
                                                 src=dpid_to_mac(dpid),
                                                 dst=a.hwsrc)
                                    e.set_payload(r)
                                    log.debug("%i %i answering ARP for %s" %
                                              (dpid, inport, r.protosrc))
                                    msg = of.ofp_packet_out()
                                    msg.data = e.pack()
                                    msg.actions.append(
                                        of.ofp_action_output(
                                            port=of.OFPP_IN_PORT))
                                    msg.in_port = inport
                                    event.connection.send(msg)
                                    return

            # Didn't know how to answer or otherwise handle this ARP, so just flood it
            log.debug("%i %i flooding ARP %s %s => %s" % (dpid, inport, {
                arp.REQUEST: "request",
                arp.REPLY: "reply"
            }.get(a.opcode, 'op:%i' % (a.opcode, )), a.protosrc, a.protodst))

            msg = of.ofp_packet_out(
                in_port=inport,
                data=event.ofp,
                action=of.ofp_action_output(port=of.OFPP_FLOOD))
            event.connection.send(msg)
Exemplo n.º 26
0
 def install_openflow_rules(self, groupflow_trace_event = None):
     """Selects routes for active receivers from the cached shortest path tree, and installs/removes OpenFlow rules accordingly."""
     reception_state = self.groupflow_manager.get_reception_state(self.dst_mcast_address, self.src_ip)
     log.debug('Reception state for ' + str(self.dst_mcast_address) + ': ' + str(reception_state))
     outgoing_rules = defaultdict(lambda : None)
     
     if not groupflow_trace_event is None:
         groupflow_trace_event.set_route_processing_start_time(self.dst_mcast_address, self.src_ip)
         
     # Calculate the paths for the specific receivers that are currently active from the previously
     # calculated mst
     edges_to_install = []
     calculated_path_router_dpids = []
     for receiver in reception_state:
         if receiver[0] == self.src_router_dpid:
             continue
         if receiver[0] in calculated_path_router_dpids:
             continue
         
         # log.debug('Building path for receiver on router: ' + dpid_to_str(receiver[0]))
         receiver_path = self.path_tree_map[receiver[0]]
         log.debug('Receiver path for receiver ' + str(receiver[0]) + ': ' + str(receiver_path))
         if receiver_path is None:
             log.warn('Path could not be determined for receiver ' + dpid_to_str(receiver[0]) + ' (network is not fully connected)')
             continue
             
         while receiver_path[1]:
             edges_to_install.append((receiver_path[1][0], receiver_path[0]))
             receiver_path = receiver_path[1]
         calculated_path_router_dpids.append(receiver[0])
                 
     # Get rid of duplicates in the edge list (must be a more efficient way to do this, find it eventually)
     edges_to_install = list(Set(edges_to_install))
     if not edges_to_install is None:
         # log.info('Installing edges:')
         for edge in edges_to_install:
             log.debug('Installing: ' + str(edge[0]) + ' -> ' + str(edge[1]))
     
     if not groupflow_trace_event is None:
         groupflow_trace_event.set_route_processing_end_time()
         groupflow_trace_event.set_flow_installation_start_time()
     
     for edge in edges_to_install:
         if edge[0] in outgoing_rules:
             # Add the output action to an existing rule if it has already been generated
             output_port = self.groupflow_manager.adjacency[edge[0]][edge[1]]
             outgoing_rules[edge[0]].actions.append(of.ofp_action_output(port = output_port))
             #log.debug('ER: Configured router ' + dpid_to_str(edge[0]) + ' to forward group ' + \
             #    str(self.dst_mcast_address) + ' to next router ' + \
             #    dpid_to_str(edge[1]) + ' over port: ' + str(output_port))
         else:
             # Otherwise, generate a new flow mod
             msg = of.ofp_flow_mod()
             msg.hard_timeout = 0
             msg.idle_timeout = 0
             if edge[0] in self.installed_node_list:
                 msg.command = of.OFPFC_MODIFY
             else:
                 msg.command = of.OFPFC_ADD
             msg.match.dl_type = 0x800   # IPV4
             msg.match.nw_dst = self.dst_mcast_address
             msg.match.nw_src = self.src_ip
             msg.cookie = self.flow_cookie
             output_port = self.groupflow_manager.adjacency[edge[0]][edge[1]]
             msg.actions.append(of.ofp_action_output(port = output_port))
             outgoing_rules[edge[0]] = msg
             #log.debug('NR: Configured router ' + dpid_to_str(edge[0]) + ' to forward group ' + \
             #    str(self.dst_mcast_address) + ' to next router ' + \
             #    dpid_to_str(edge[1]) + ' over port: ' + str(output_port))
     
     for receiver in reception_state:
         if receiver[0] in outgoing_rules:
             # Add the output action to an existing rule if it has already been generated
             output_port = receiver[1]
             outgoing_rules[receiver[0]].actions.append(of.ofp_action_output(port = output_port))
             #log.debug('ER: Configured router ' + dpid_to_str(receiver[0]) + ' to forward group ' + \
             #        str(self.dst_mcast_address) + ' to network over port: ' + str(output_port))
         else:
             # Otherwise, generate a new flow mod
             msg = of.ofp_flow_mod()
             msg.hard_timeout = 0
             msg.idle_timeout = 0
             if receiver[0] in self.installed_node_list:
                 msg.command = of.OFPFC_MODIFY
             else:
                 msg.command = of.OFPFC_ADD
             msg.cookie = self.flow_cookie
             msg.match.dl_type = 0x800   # IPV4
             msg.match.nw_dst = self.dst_mcast_address
             msg.match.nw_src = self.src_ip
             output_port = receiver[1]
             msg.actions.append(of.ofp_action_output(port = output_port))
             outgoing_rules[receiver[0]] = msg
             #log.debug('NR: Configured router ' + dpid_to_str(receiver[0]) + ' to forward group ' + \
             #        str(self.dst_mcast_address) + ' to network over port: ' + str(output_port))
     
     # Setup empty rules for any router not involved in this path
     for router_dpid in self.node_list:
         if not router_dpid in outgoing_rules and router_dpid in self.installed_node_list:
             msg = of.ofp_flow_mod()
             msg.cookie = self.flow_cookie
             msg.match.dl_type = 0x800   # IPV4
             msg.match.nw_dst = self.dst_mcast_address
             msg.match.nw_src = self.src_ip
             msg.command = of.OFPFC_DELETE
             outgoing_rules[router_dpid] = msg
             #log.debug('Removed rule on router ' + dpid_to_str(router_dpid) + ' for group ' + str(self.dst_mcast_address))
     
     for router_dpid in outgoing_rules:
         connection = core.openflow.getConnection(router_dpid)
         if connection is not None:
             connection.send(outgoing_rules[router_dpid])
             if not outgoing_rules[router_dpid].command == of.OFPFC_DELETE:
                 self.installed_node_list.append(router_dpid)
             else:
                 self.installed_node_list.remove(router_dpid)
         else:
             log.warn('Could not get connection for router: ' + dpid_to_str(router_dpid))
     
     log.debug('New flows installed for Group: ' + str(self.dst_mcast_address) + ' Source: ' + str(self.src_ip) + ' FlowCookie: ' + str(self.flow_cookie))
     
     if self.groupflow_manager.flow_replacement_mode == PERIODIC_FLOW_REPLACEMENT and self._flow_replacement_timer is None:
         log.debug('Starting flow replacement timer for Group: ' + str(self.dst_mcast_address) + ' Source: ' + str(self.src_ip) + ' FlowCookie: ' + str(self.flow_cookie))
         self._flow_replacement_timer = Timer(self.groupflow_manager.flow_replacement_interval, self.update_flow_placement, recurring=True)
     
     if not groupflow_trace_event is None:
         groupflow_trace_event.set_flow_installation_end_time()
         core.groupflow_event_tracer.archive_trace_event(groupflow_trace_event)
Exemplo n.º 27
0
 def __init__(self, nexus=None):
     Transport.__init__(self, nexus)
     self._connections = {}
     #self._t = Timer(5, self._check_timeouts, recurring=True)
     self._t = Timer(60 * 2, self._check_timeouts, recurring=True)
Exemplo n.º 28
0
    def _all_dependencies_met(self):
        self._startup("poxdesk_topo")

        # Periodically just send a topo
        self.timer = Timer(10, self.send_table, recurring=True)
        log.debug("Ready to rip.")
Exemplo n.º 29
0
def launch():
    core.registerNew(l2_multi)

    timeout = min(max(PATH_SETUP_TIME, 5) * 2, 15)
    Timer(timeout, WaitingPath.expire_waiting_paths, recurring=True)
Exemplo n.º 30
0
def launch():
    #clear some unimportant message
    core.getLogger("packet").setLevel(logging.ERROR)
    core.registerNew(Sp_network)
    Timer(25, _handle_timer, recurring=False, args=["Now 1 ping 2 is not ok!"])