Beispiel #1
0
    def on_packet_in(self, message):
        """ receives a packet from the real network  """

        if message.payload is None: return self

        message.payload = self.pre_in_packet(message)

        if message.payload.haslayer('DHCP'):
            dhcpMsg  =  DHCPTypes[message.payload[DHCP].options[0][1]]
            msgName = 'dhcp_'+dhcpMsg
            signalQueue.put_nowait(simMessage(msgName,mac=message.payload['Ethernet'].dst,payload=message.payload))
            return self

        if message.payload.haslayer('ARP'):
            arpLogger.debug("ARP_WHOHAS for %s", message.payload['ARP'].pdst)
            signalQueue.put_nowait(simMessage("arp_whohas",mac=message.payload['ARP'].pdst,payload=message.payload))
            return self

        if message.payload.haslayer('ICMP'):
            pktType=message.payload['ICMP'].getfieldval('type')
            if pktType==ECHO_REQUEST: # ICMP echo-request
                icmpLogger.debug("ICMP_ECHOREQUEST for %s", message.payload['Ethernet'].dst)
                signalQueue.put_nowait(simMessage("icmp_echoRequest",mac=message.payload['Ethernet'].dst,payload=message.payload))
                return self

        if message.payload.haslayer('TFTP'):
            tftpLogger.debug("device %s had just received a tftp packet" % (message.payload['Ethernet'].dst))
            signalQueue.put_nowait(simMessage("tftp_recvblk",mac=message.payload['Ethernet'].dst,payload=message.payload))

        return self
Beispiel #2
0
    def __init__(self, discPacket, ctx=None, parent=None):
        super(DHCP_Acking, self).__init__(ctx, parent=self)

        self.context.ip = discPacket[BOOTP].yiaddr

        if self.context.deviceKind == "CM":
            # loop over the options sended by server
            for data in discPacket[DHCP].options:
                # option 67 is bootfile-name
                if data[0]==67: self.context.tftp.bootfileName=data[1]
                if data[0]=='lease_time':
                    tEvent = TimerItem(ltime=time.time() + data[1] / 2.0, mac=self.context.mac, msg="dhcp_renew")
                    eventTimers.append(tEvent)
                    #dhcpLogger.warning("Adding timer event #(%d) %s for %s in %ds (%f)",len(eventTimers),tEvent.msg,tEvent.mac,data[1],tEvent.lTimer)

        dhcpLogger.debug("mac=%s ip=%s tftp=%s ACK RECEIVED (%d)",self.context.mac,self.context.ip, discPacket[BOOTP].siaddr, simulatorStats.getitem('DHCP_ACK'))

        # register the IP assigned into a dictionary of running devices
        self.context.emulator.runningDevices[discPacket[BOOTP].yiaddr]=self.context

        # check if device has tftp instance reference
        if ( getattr(self.context,'tftp',False) ):
            # tftp server travels on siaddr
            self.context.tftp.tftpIPserver = discPacket[BOOTP].siaddr
            self.signal( simMessage("tftp_readrequest",mac=self.context.mac) )
Beispiel #3
0
    def __init__(self, renewPacket, ctx=None, parent=None):
        super(DHCP_Renewing, self).__init__(ctx, parent=self)

        dhcpLogger.info("(DHCP RENEW) State DHCP_Renewing::mac=%s IP=%s to dhcpserver(%s:%s)",self.context.mac,self.context.ip,self.context.dhcpServerIP,self.context.dhcpServerMac)

        et=Ether(dst=self.context.dhcpServerMac,src='')
        ip=IP(src=self.context.ip,dst=self.context.dhcpServerIP)
        udp=UDP(sport=BOOTPC,dport=BOOTPS)

        newmac=''
        for pos in self.context.mac.split(':'): newmac+=binascii.unhexlify(pos)
        bootp=BOOTP(chaddr=newmac,ciaddr=self.context.ip,xid=random.randint(0,2**32))

        dhcp_options=DHCP(options=[("message-type","request"),
                ("relay_agent_Information",'\x01\x04\x88\x01\x00\x04\x02\x06'+newmac),
                ("vendor_class_id", self.context.dhcp_options['vendor_class_id']),
                ("param_req_list", self.context.requestedParameters),
                "end"])

        pkg=et/ip/udp/bootp/dhcp_options

        m = simMessage("send_packet", mac=self.context.mac, payload=pkg)
        self.signal(m)

        simulatorStats.increment('DHCP_RENEW') # for stats

        # register timer for dhcp_request
        try: self.context.cmtimers['dhcp_request'] = time.time()
        except AttributeError:
            #dhcpLogger.error("%s Could not set DHCP REQUEST timer",self.context.mac)
            pass

        return 
Beispiel #4
0
    def on_tftp_recvblk(self, message):

        tftpref = self.context.tftp
    
        if TFTP_ERROR in message.payload:
            tftpLogger.error("Error !!!")
            message.payload.show()
            return self

        if TFTP_DATA in message.payload:
            if message.payload[TFTP_DATA].block == tftpref.awaiting:
                if tftpref.server_tid is None:
                    tftpref.server_tid = message.payload[UDP].sport
                    message.payload[UDP].dport = tftpref.server_tid
            else:
                tftpLogger.error("Error receiving !!. Wrong bloknumber. %d vs awaiting=%d !!" ,message.payload[TFTP_DATA].block, tftpref.awaiting)
                message.payload.show()

        if Raw in message.payload:
            recvd = message.payload[Raw].load
        else:
            recvd = ""

        tftpLogger.debug("ReceivingFile::CM %s had received file portion. Awaiting block %d len(recvd)=%d blocksize=%d",self.context.ip,tftpref.awaiting,len(recvd),self.blocksize)
        tftpref.bootfileSize_tmp += len(recvd)
        tftpref.bootfile += recvd

        self.signal ( simMessage("tftp_ack", mac=self.context.mac, payload=message.payload) )
        return TFTP_ack()
Beispiel #5
0
    def on_icmp_echoRequest(self, message):
        icmpLogger.debug("ICMP_ECHOREQUEST arrived for %s",
                         message.payload['Ethernet'].dst)

        ICMPPacket = message.payload
        NICMPPacket = ICMPPacket

        # for IP and ICMP chksum recalculation
        del (NICMPPacket['IP'].chksum)
        del (NICMPPacket['IP'].len)
        del (NICMPPacket['ICMP'].chksum)

        # response with echo request
        NICMPPacket['ICMP'].type = ECHO_REPLY
        NICMPPacket['Ethernet'].dst = ICMPPacket['Ethernet'].src
        # src should be set by ethernet layer....
        NICMPPacket['Ethernet'].src = ''
        NICMPPacket['IP'].dst, NICMPPacket['IP'].src = ICMPPacket[
            'IP'].src, ICMPPacket['IP'].dst
        NICMPPacket['IP'].flags = 0
        #NICMPPacket['IP'].ttl=128
        NICMPPacket['IP'].id = random.randint(1000, 5000)
        #NICMPPacket['ICMP'].load = ICMPPacket['ICMP'].load

        m = simMessage("send_packet",
                       mac=self.context.mac,
                       payload=NICMPPacket)
        self.signal(m)

        return self
Beispiel #6
0
    def on_tftp_ack(self, message):
        tftpref = self.context.tftp

        et=Ether(dst=tftpref.tftpMACserver,src='')
        #self.tftpPacket=et/IP(src=self.context.ip,dst=tftpref.tftpIPserver)/UDP(sport=tftpref.my_tid,dport=tftpref.port)/TFTP()
        self.tftpPacket=et/IP(src=self.context.ip,dst=tftpref.tftpIPserver)/UDP(sport=tftpref.my_tid,dport=TFTP_PORT)/TFTP()
        self.lastPacket = self.tftpPacket / TFTP_ACK(block = tftpref.awaiting)

        tftpref.awaiting += 1
        self.lastPacket[UDP].dport = tftpref.server_tid
    
        self.signal ( simMessage("send_packet", mac=self.context.mac, payload=self.lastPacket) )

        if Raw in message.payload:
            recvd = message.payload[Raw].load
        else:
            recvd = ""

        if len(recvd) != tftpref.blocksize:
            self.context.cmTimers['tftp_end'] = time.time()
            tftpref.bootfileSize = tftpref.bootfileSize_tmp
            tftpLogger.debug("TFTP_ReceivingFile(%s:%s):: blockSize=%d jump to TFTP_end fileZize=%d",self.context.ip,self.context.mac, len(recvd), tftpref.bootfileSize)
            tftpLogger.info("(%s:%s)::Had completely received %s(fileSize=%d)",self.context.ip,self.context.mac, tftpref.bootfileName, tftpref.bootfileSize)
            return TFTP_Idle()
        
        return TFTP_ReceivingFile()
Beispiel #7
0
    def on_arp_whohas(self, message):
        ARPPacket=message.payload
        arpLogger.debug("(%s) IS_AT=%s", self.context.mac, self.context.ip)
        ARP_answer = Ether(dst=ARPPacket.hwsrc)/\
                     ARP(hwdst=ARPPacket.hwsrc,hwsrc=self.context.mac,psrc=ARPPacket.pdst,pdst=ARPPacket.psrc,op=IS_AT)
        m = simMessage("send_packet", mac=self.context.mac, payload=ARP_answer)
        self.signal(m)

        return self
Beispiel #8
0
    def on_arp_whohas(self, message):
        ARPPacket = message.payload
        arpLogger.debug("(%s) IS_AT=%s", self.context.mac, self.context.ip)
        ARP_answer = Ether(dst=ARPPacket.hwsrc)/\
                     ARP(hwdst=ARPPacket.hwsrc,hwsrc=self.context.mac,psrc=ARPPacket.pdst,pdst=ARPPacket.psrc,op=IS_AT)
        m = simMessage("send_packet", mac=self.context.mac, payload=ARP_answer)
        self.signal(m)

        return self
Beispiel #9
0
 def run(self):
     while self.__run:
         try:
             pkg = self.__realnetwork.get()
             self.__realnetwork.task_done()
             if ( pkg['Ethernet'].dst is not None ): 
                 self.__simqueue.put_nowait( simMessage("packet_in",mac=pkg['Ethernet'].dst,payload=pkg) )
         except (AttributeError,IndexError):  # we could sniff wifi protocol (802.3)    
             networkLogger.warning("Got packet without Ethernet layer !")
Beispiel #10
0
    def on_packet_in(self, message):
        """ receives a packet from the real network  """

        if message.payload is None: return self

        message.payload = self.pre_in_packet(message)

        if message.payload.haslayer('DHCP'):
            dhcpMsg = DHCPTypes[message.payload[DHCP].options[0][1]]
            msgName = 'dhcp_' + dhcpMsg
            signalQueue.put_nowait(
                simMessage(msgName,
                           mac=message.payload['Ethernet'].dst,
                           payload=message.payload))
            return self

        if message.payload.haslayer('ARP'):
            arpLogger.debug("ARP_WHOHAS for %s", message.payload['ARP'].pdst)
            signalQueue.put_nowait(
                simMessage("arp_whohas",
                           mac=message.payload['ARP'].pdst,
                           payload=message.payload))
            return self

        if message.payload.haslayer('ICMP'):
            pktType = message.payload['ICMP'].getfieldval('type')
            if pktType == ECHO_REQUEST:  # ICMP echo-request
                icmpLogger.debug("ICMP_ECHOREQUEST for %s",
                                 message.payload['Ethernet'].dst)
                signalQueue.put_nowait(
                    simMessage("icmp_echoRequest",
                               mac=message.payload['Ethernet'].dst,
                               payload=message.payload))
                return self

        if message.payload.haslayer('TFTP'):
            tftpLogger.debug("device %s had just received a tftp packet" %
                             (message.payload['Ethernet'].dst))
            signalQueue.put_nowait(
                simMessage("tftp_recvblk",
                           mac=message.payload['Ethernet'].dst,
                           payload=message.payload))

        return self
Beispiel #11
0
    def startSimulator(self):
        SimulatorLogger.info("#CMs to boot:%d", len(self.machine.cms))

        self.doLoop = True

        while self.doLoop:
            # retrieve signals from simulator signal queue
            message = self.get_new_message()

            #look for scheduled events...
            now = time.time()
            #leventTimers=sorted(eventTimers, key=lambda item: now - item.lTimer)
            eventTimers.sort(key=lambda item: now - item.lTimer, reverse=True)

            # remove all timer events to execute
            while (len(eventTimers) > 0) and (
                (eventTimers[-1].lTimer - now) < 0):
                # remove timer from list
                tItem = eventTimers.pop()
                print "adding ", tItem.msg, "event for ", tItem.mac, tItem.msg
                signalQueue.put_nowait(
                    simMessage(name=tItem.msg, mac=tItem.mac, payload=None))

            if self.simulatorStatus:
                if message is not None:
                    if message.name == 'exit':
                        SimulatorLogger.info(
                            "Message received=EXIT. Leaving....")
                        self.doLoop = False
                    else:
                        SimulatorLogger.debug(
                            "Simulator new message::msg.mac=%s msg.name=%s",
                            message.mac, message.name)
                        self.machine.dispatch_message(message)

        provisioned = 0
        for mac, device in self.machine.cms.iteritems():
            if (device.ip != '0.0.0.0'):
                SimulatorLogger.debug(
                    "%s.....%s ProvTime=%d", mac, device.ip,
                    device.cmTimers['dhcp_ack'] -
                    device.cmTimers['dhcp_discover'])
                #print "\n",mac,"......",device.ip, " ProvTime=", device.cmTimers['dhcp_ack'] - device.cmTimers['dhcp_discover'],
                #if device.cmTimers.has_key('tftp_end') and device.cmTimers.has_key('tftp_start'):
                #    print " TFTP Time=",device.cmTimers['tftp_end'] - device.cmTimers['tftp_start'],
                provisioned += 1
            else:
                SimulatorLogger.debug("%s.....%s", mac, device.ip)

        SimulatorLogger.debug("Signals procesed in queue:%d",
                              self.signalCounter)
        SimulatorLogger.info("#CM provisioned = %d\nSimulator Stats...",
                             provisioned)
        for k, v in simulatorStats.getdata().iteritems():
            SimulatorLogger.info("%s.....%d", k, v)
Beispiel #12
0
    def on_tftp_readrequest(self, message):
        tftpref = self.context.tftp

        # XXX FIX !!
        # tftp mac should be obteined automatically, but need to understand how arping works requesting self ip address
        # tftpref.tftpMACserver='00:0c:29:f4:c1:fa'
        tftpLogger.debug("CM(%s)::registering TFTPServer(%s,%s)",
                         self.context.mac, tftpref.tftpIPserver,
                         tftpref.tftpMACserver)

        if (tftpref.tftpIPserver is None):
            tftpLogger.error(
                "TFTP(%s)::Could not retrieve TFTP Server(%s) macaddress",
                self.context.mac, tftpref.tftpIPserver)
            return self

        # obtain tftp server mac address by ARP
        # ans = arping(tftpref.tftpIPserver)
        # if ( len(ans[0]) > 0 ):
        # means we received an answer
        #     tftpref.tftpMACserver = ans[0][0][1]['Ethernet'].src
        #    tftpLogger.debug("CM(%s)::registering TFTPServer(%s,%s)",self.context.mac, tftpref.tftpIPserver, tftpref.tftpMACserver)
        # else:
        #     tftpLogger.error("CM(%s)::Could not retrieve TFTP Server(%s) macaddress",self.context.mac, tftpref.tftpIPserver)
        #     return self

        et = Ether(dst=tftpref.tftpMACserver, src='')
        tftpPacket = et / IP(
            src=self.context.ip, dst=tftpref.tftpIPserver) / UDP(
                sport=tftpref.my_tid, dport=TFTP_PORT) / TFTP()
        self.last_packet = tftpPacket / TFTP_RRQ(filename=tftpref.bootfileName,
                                                 mode="octet")

        tftpref.awaiting = 1
        tftpref.server_tid = None
        tftpref.bootfileSize = 0
        tftpref.bootfileSize_tmp = 0
        tftpref.bootfile = ""

        tftpLogger.debug(
            "CM %s had received tftp read request (%s).Awaiting=%d my_tid=%d server_tid=None",
            self.context.ip, tftpref.bootfileName, tftpref.awaiting,
            tftpref.my_tid)

        # register tftp start time
        self.context.cmTimers['tftp_start'] = time.time()

        self.signal(
            simMessage("send_packet",
                       mac=self.context.mac,
                       payload=self.last_packet))
        return TFTP_ReceivingFile()
Beispiel #13
0
    def on_send_packet(self, message):
        """ Sending a packet to the real network """
        #message.payload['Ethernet'].src = self.context.mac

        message.payload = self.pre_send_packet(message)

        if ( self.context.nexthop == "border_router" ):
            # Send packet to real network 
            sendp(message.payload)
        else:
            signalQueue.put_nowait(simMessage("send_packet",mac=self.context.nexthop,payload=message.payload))

        return self
Beispiel #14
0
 def run(self):
     while self.__run:
         try:
             pkg = self.__realnetwork.get()
             self.__realnetwork.task_done()
             if (pkg['Ethernet'].dst is not None):
                 self.__simqueue.put_nowait(
                     simMessage("packet_in",
                                mac=pkg['Ethernet'].dst,
                                payload=pkg))
         except (AttributeError,
                 IndexError):  # we could sniff wifi protocol (802.3)
             networkLogger.warning("Got packet without Ethernet layer !")
Beispiel #15
0
    def on_dhcp_discover(self, message):
        super(DHCP_Idle, self).__init__(self.context,parent=self)
        # Build discover packet
        # Dont set Eth.src. Ethernet layer will do it
        et=Ether(dst="ff:ff:ff:ff:ff:ff",src='')
        ip=IP(src="0.0.0.0",dst="255.255.255.255")
        self.context.ip = "0.0.0.0"
        udp=UDP(sport=BOOTPC,dport=BOOTPS)

        # Build the pkg
        if self.fuzzPackets:
            # XXX the corruption should be parametrisable. Now it's hardcoded
            self.bootp = BOOTP( CorruptedBytes(BOOTP(),0.9) )
            self.bootp.op = 1 # BOOTPREQUEST need to send a correct DHCP packet id
            # XXX the corruption should be parametrisable. Now it's hardcoded
            pkg=et/ip/udp/self.bootp/DHCP( CorruptedBytes(DHCP(options=["end"]) ,0.9) )
        else:
            newmac=''
            for pos in self.context.mac.split(':'): newmac+=binascii.unhexlify(pos)
            # xid is 4 byte long 
            self.bootp=BOOTP(chaddr=newmac,xid=random.randint(0,2**32))
            self.dhcp_options = DHCP(options=[("message-type","discover"),
                ("relay_agent_Information",'\x01\x04\x88\x01\x00\x04\x02\x06'+newmac),
                ("vendor_specific",'\x08\x03\x00\x20\x40\x04\x18\x31\x33\x34\x35\x30\x33\x34\x32\x35\x32\x31\x32\x39\x38\x36\x35\x30\x31\x30\x31\x30\x30\x30\x30\x05\x01\x31\x06\x19\x53\x42\x35\x31\x30\x31\x2d\x32\x2e\x34\x2e\x34\x2e\x30\x2d\x53\x43\x4d\x30\x30\x2d\x4e\x4f\x53\x48\x07\x04\x32\x31\x36\x34\x09\x06\x53\x42\x35\x31\x30\x31\x0a\x14\x4d\x6f\x74\x6f\x72\x6f\x6c\x61\x20\x43\x6f\x72\x70\x6f\x72\x61\x74\x69\x6f\x6e'),
                ("vendor_class_id", self.context.dhcp_options['vendor_class_id']),
                ("param_req_list", self.context.requestedParameters),
                "end"])
            pkg=et/ip/udp/self.bootp/self.dhcp_options

        m = simMessage("send_packet", mac=self.context.mac, payload=pkg)
        dhcpLogger.debug("mac=%s DISCOVERING",self.context.mac)
		
        simulatorStats.increment('DHCP_DISCOVER') # for stats

        # according to RFC 2131
        # The client begins in INIT state and forms a DHCPDISCOVER message.
        # The client SHOULD wait a random time between one and ten seconds to
        # desynchronize the use of DHCP at startup.
        # XXX should be something more .... multithreadable with some signals
        #time.sleep(random.randint(0,10))

        self.signal(m)

        # register timer for dhcp_discover
        try: self.context.cmTimers['dhcp_discover'] = time.time()
        except AttributeError:
            #dhcpLogger.error("%s Could not set DHCP DISCOVER timer",self.context.mac)
            pass

        return DHCP_Discovering(self.context,parent=self)
Beispiel #16
0
    def on_send_packet(self, message):
        """ Sending a packet to the real network from the CMTS point of view..."""
        if not message.payload.haslayer('TFTP'):
            message.payload['Ethernet'].src = self.context.mac

        message.payload = self.pre_send_packet(message)


        if ( self.context.nexthop == "border_router" ):
            # Send packet to real network 
            sendp(message.payload)
        else:
            signalQueue.put_nowait( simMessage("send_packet",mac=self.context.nexthop,payload=message.payload))

        return self
Beispiel #17
0
    def on_send_packet(self, message):
        """ Sending a packet to the real network """
        #message.payload['Ethernet'].src = self.context.mac

        message.payload = self.pre_send_packet(message)

        if (self.context.nexthop == "border_router"):
            # Send packet to real network
            sendp(message.payload)
        else:
            signalQueue.put_nowait(
                simMessage("send_packet",
                           mac=self.context.nexthop,
                           payload=message.payload))

        return self
Beispiel #18
0
    def on_send_packet(self, message):
        """ Sending a packet to the real network from the CMTS point of view..."""
        if not message.payload.haslayer('TFTP'):
            message.payload['Ethernet'].src = self.context.mac

        message.payload = self.pre_send_packet(message)

        if (self.context.nexthop == "border_router"):
            # Send packet to real network
            sendp(message.payload)
        else:
            signalQueue.put_nowait(
                simMessage("send_packet",
                           mac=self.context.nexthop,
                           payload=message.payload))

        return self
Beispiel #19
0
    def startSimulator(self):
        SimulatorLogger.info("#CMs to boot:%d",len(self.machine.cms))

        self.doLoop = True

        while self.doLoop:
            # retrieve signals from simulator signal queue
            message = self.get_new_message()

            #look for scheduled events...
            now = time.time()
            #leventTimers=sorted(eventTimers, key=lambda item: now - item.lTimer)
            eventTimers.sort(key=lambda item: now - item.lTimer, reverse=True)

            # remove all timer events to execute
            while (len(eventTimers)>0) and ((eventTimers[-1].lTimer - now) < 0):
                # remove timer from list
                tItem = eventTimers.pop()
                print "adding ",tItem.msg,"event for ",tItem.mac,tItem.msg
                signalQueue.put_nowait( simMessage(name=tItem.msg, mac=tItem.mac, payload=None) )

            if self.simulatorStatus:
                if message is not None:
                    if message.name == 'exit':
                        SimulatorLogger.info("Message received=EXIT. Leaving....")
                        self.doLoop = False
                    else:
                        SimulatorLogger.debug("Simulator new message::msg.mac=%s msg.name=%s" ,message.mac,message.name)
                        self.machine.dispatch_message(message)

        provisioned = 0  
        for mac,device in self.machine.cms.iteritems():
            if (device.ip != '0.0.0.0'):
                SimulatorLogger.debug("%s.....%s ProvTime=%d",mac,device.ip, device.cmTimers['dhcp_ack'] - device.cmTimers['dhcp_discover'])
                #print "\n",mac,"......",device.ip, " ProvTime=", device.cmTimers['dhcp_ack'] - device.cmTimers['dhcp_discover'],
                #if device.cmTimers.has_key('tftp_end') and device.cmTimers.has_key('tftp_start'):
                #    print " TFTP Time=",device.cmTimers['tftp_end'] - device.cmTimers['tftp_start'],
                provisioned+=1
            else:
                SimulatorLogger.debug("%s.....%s",mac,device.ip)

        SimulatorLogger.debug("Signals procesed in queue:%d",self.signalCounter)
        SimulatorLogger.info("#CM provisioned = %d\nSimulator Stats...",provisioned)
        for k,v in simulatorStats.getdata().iteritems():
            SimulatorLogger.info("%s.....%d",k,v)
Beispiel #20
0
    def __init__(self, discPacket, ctx=None, parent=None):
        super(DHCP_Requesting, self).__init__(ctx, parent=self)

        dhcpLogger.debug("mac=%s REQUESTING IP=%s",self.context.mac,discPacket[BOOTP].yiaddr)
        
        # keep dhcp server ip address 
        self.context.dhcpServerIP = discPacket[IP].src
        self.context.dhcpServerMac = discPacket['Ethernet'].src

        et=Ether(dst="ff:ff:ff:ff:ff:ff",src='')
        ip=IP(src="0.0.0.0",dst="255.255.255.255")
        udp=UDP(sport=BOOTPC,dport=BOOTPS)

        newmac=''
        for pos in self.context.mac.split(':'): newmac+=binascii.unhexlify(pos)
        bootp=BOOTP(chaddr=newmac,xid=discPacket[BOOTP].xid)
        
        dhcp_options=DHCP(options=[("message-type","request"),
                ("server_id",discPacket[IP].src),
                ("relay_agent_Information",'\x01\x04\x88\x01\x00\x04\x02\x06'+newmac),
                ("vendor_class_id", self.context.dhcp_options['vendor_class_id']),
                #("param_req_list",'\x42\x43\x01\x03\x02\x04\x07\x7a'),
                ("param_req_list", self.context.requestedParameters),
                ("requested_addr",discPacket[BOOTP].yiaddr),
                "end"])

        # build the pkg
        pkg=et/ip/udp/bootp/dhcp_options

        m = simMessage("send_packet", mac=self.context.mac, payload=pkg)
        self.signal(m)

        simulatorStats.increment('DHCP_REQUEST') # for stats

        # register timer for dhcp_request
        try: self.context.cmTimers['dhcp_request'] = time.time()
        except AttributeError:
            #dhcpLogger.error("%s Could not set DHCP REQUEST timer",self.context.mac)
            pass

        return 
Beispiel #21
0
    def on_tftp_readrequest(self, message):
        tftpref = self.context.tftp
       
        # XXX FIX !! 
        # tftp mac should be obteined automatically, but need to understand how arping works requesting self ip address
        # tftpref.tftpMACserver='00:0c:29:f4:c1:fa'
        tftpLogger.debug("CM(%s)::registering TFTPServer(%s,%s)",self.context.mac, tftpref.tftpIPserver, tftpref.tftpMACserver)

        if ( tftpref.tftpIPserver is None):
            tftpLogger.error("TFTP(%s)::Could not retrieve TFTP Server(%s) macaddress",self.context.mac, tftpref.tftpIPserver)
            return self

        # obtain tftp server mac address by ARP 
        # ans = arping(tftpref.tftpIPserver)
        # if ( len(ans[0]) > 0 ):
            # means we received an answer        
        #     tftpref.tftpMACserver = ans[0][0][1]['Ethernet'].src
        #    tftpLogger.debug("CM(%s)::registering TFTPServer(%s,%s)",self.context.mac, tftpref.tftpIPserver, tftpref.tftpMACserver)
        # else:
        #     tftpLogger.error("CM(%s)::Could not retrieve TFTP Server(%s) macaddress",self.context.mac, tftpref.tftpIPserver)
        #     return self

        et=Ether(dst=tftpref.tftpMACserver,src='')
        tftpPacket=et/IP(src=self.context.ip,dst=tftpref.tftpIPserver)/UDP(sport=tftpref.my_tid,dport=TFTP_PORT)/TFTP()
        self.last_packet = tftpPacket/TFTP_RRQ(filename=tftpref.bootfileName, mode="octet")

        tftpref.awaiting = 1
        tftpref.server_tid = None
        tftpref.bootfileSize = 0
        tftpref.bootfileSize_tmp = 0
        tftpref.bootfile = ""

        tftpLogger.debug("CM %s had received tftp read request (%s).Awaiting=%d my_tid=%d server_tid=None" ,self.context.ip,tftpref.bootfileName,tftpref.awaiting, tftpref.my_tid)

        # register tftp start time
        self.context.cmTimers['tftp_start'] = time.time()

        self.signal( simMessage("send_packet", mac=self.context.mac, payload=self.last_packet) )
        return TFTP_ReceivingFile()
Beispiel #22
0
    def on_tftp_recvblk(self, message):

        tftpref = self.context.tftp

        if TFTP_ERROR in message.payload:
            tftpLogger.error("Error !!!")
            message.payload.show()
            return self

        if TFTP_DATA in message.payload:
            if message.payload[TFTP_DATA].block == tftpref.awaiting:
                if tftpref.server_tid is None:
                    tftpref.server_tid = message.payload[UDP].sport
                    message.payload[UDP].dport = tftpref.server_tid
            else:
                tftpLogger.error(
                    "Error receiving !!. Wrong bloknumber. %d vs awaiting=%d !!",
                    message.payload[TFTP_DATA].block, tftpref.awaiting)
                message.payload.show()

        if Raw in message.payload:
            recvd = message.payload[Raw].load
        else:
            recvd = ""

        tftpLogger.debug(
            "ReceivingFile::CM %s had received file portion. Awaiting block %d len(recvd)=%d blocksize=%d",
            self.context.ip, tftpref.awaiting, len(recvd), self.blocksize)
        tftpref.bootfileSize_tmp += len(recvd)
        tftpref.bootfile += recvd

        self.signal(
            simMessage("tftp_ack",
                       mac=self.context.mac,
                       payload=message.payload))
        return TFTP_ack()
Beispiel #23
0
    def on_tftp_ack(self, message):
        tftpref = self.context.tftp

        et = Ether(dst=tftpref.tftpMACserver, src='')
        #self.tftpPacket=et/IP(src=self.context.ip,dst=tftpref.tftpIPserver)/UDP(sport=tftpref.my_tid,dport=tftpref.port)/TFTP()
        self.tftpPacket = et / IP(
            src=self.context.ip, dst=tftpref.tftpIPserver) / UDP(
                sport=tftpref.my_tid, dport=TFTP_PORT) / TFTP()
        self.lastPacket = self.tftpPacket / TFTP_ACK(block=tftpref.awaiting)

        tftpref.awaiting += 1
        self.lastPacket[UDP].dport = tftpref.server_tid

        self.signal(
            simMessage("send_packet",
                       mac=self.context.mac,
                       payload=self.lastPacket))

        if Raw in message.payload:
            recvd = message.payload[Raw].load
        else:
            recvd = ""

        if len(recvd) != tftpref.blocksize:
            self.context.cmTimers['tftp_end'] = time.time()
            tftpref.bootfileSize = tftpref.bootfileSize_tmp
            tftpLogger.debug(
                "TFTP_ReceivingFile(%s:%s):: blockSize=%d jump to TFTP_end fileZize=%d",
                self.context.ip, self.context.mac, len(recvd),
                tftpref.bootfileSize)
            tftpLogger.info("(%s:%s)::Had completely received %s(fileSize=%d)",
                            self.context.ip, self.context.mac,
                            tftpref.bootfileName, tftpref.bootfileSize)
            return TFTP_Idle()

        return TFTP_ReceivingFile()
Beispiel #24
0
 def on_dhcp_renew(self, message):
     dhcpLogger.debug("(State=DHCP_Ack)::Renewing IP %s for CM %s (dhcp renew msg received)",self.context.ip,self.context.mac)
     signalQueue.put_nowait(simMessage("dhcp_renew",mac=self.context.mac))
     return DHCP_Renewing( renewPacket=message.payload, ctx=self.context, parent=self)
Beispiel #25
0
 def on_dhcp_discover(self,message):
     dhcpLogger.debug("(State=DHCP_Ack)::Booting up CM %s (dhcp discover msg received)",self.context.mac)
     signalQueue.put_nowait(simMessage("dhcp_discover",mac=self.context.mac))
     return DHCP_Idle(self.context,parent=self)