def datagram_received(self, data, addr):
        try:
            reply = Packet(packet=data, dict=self.client.dict)

            if reply and reply.id in self.pending_requests:
                req = self.pending_requests[reply.id]
                packet = req['packet']

                reply.dict = packet.dict
                reply.secret = packet.secret

                if packet.VerifyReply(reply, data):
                    req['future'].set_result(reply)
                    # Remove request for map
                    del self.pending_requests[reply.id]
                else:
                    self.logger.warn(
                        '[%s:%d] Ignore invalid reply for id %d. %s',
                        self.server, self.port, reply.id)
            else:
                self.logger.warn('[%s:%d] Ignore invalid reply: %d',
                                 self.server, self.port, data)

        except Exception as exc:
            self.logger.error('[%s:%d] Error on decode packet: %s',
                              self.server, self.port, exc)
Exemple #2
0
    def datagram_received(self, data, addr):
        try:
            reply = Packet(packet=data, dict=self.client.dict)
            self.logger.info(reply)

            if reply and reply.id in self.pending_requests:
                self.logger.info('Request found')
                req = self.pending_requests[reply.id]
                packet = req['packet']

                reply.dict = packet.dict
                reply.secret = packet.secret

                if packet.VerifyReply(reply, data):
                    req['future'].set_result(reply)
                    # Remove request for map
                    del self.pending_requests[reply.id]
                else:
                    self.logger.warn(
                        '[{}:{}] Ignore invalid reply for id {}'.format(
                            self.server, self.port, reply.id))
            else:
                self.logger.info('Request was not found')
                try:
                    self.logger.warn('[{}:{}] Ignore invalid reply: {}'.format(
                        self.server, self.port, data.decode('utf-8')))
                except:
                    self.logger.warn('[{}:{}] Ignore invalid reply: {}'.format(
                        self.server, self.port, data))

        except Exception as exc:
            self.logger.error('[{}:{}] Error on decode packet: {}'.format(
                self.server, self.port, exc))
Exemple #3
0
def parse_packet(filename):
    with PcapReader(filename) as file_capture:
        global start_parse, end_parse, count, totaltime
        for packet in file_capture:
            try:
                if (
                        len(packet) > 400 and packet.dport == 1813
                ):  # We only need pcakets whose length is greater than 400 bytes
                    # Capturing the RAW data from packet (the index value for raw data is 3)
                    start_parse = time()
                    radius_packet = str(packet[Radius])
                    # Pyrad has a dictionary with the RADIUS attributes defined, It'll help in decoding the RAW Packet
                    pkt = Packet(packet=radius_packet,
                                 dict=Dictionary("dictionary"))
                    attr1 = pkt._DecodeKey(8)
                    value1 = pkt.__getitem__(attr1)
                    attr2 = pkt._DecodeKey(31)
                    value2 = pkt.__getitem__(attr2)
                    end_parse = time()
                    print("Time Taken to parse RADIUS packet: %s seconds" %
                          (end_parse - start_parse))
                    count += 1
                    totaltime += (end_parse - start_parse)
                    print("%d Private IP: %s and MSISDN: %s" %
                          (count, value1, value2))
            except AttributeError:
                print(
                    "Port attribute not available in the packet, skipping the parsing on the packet... "
                )
Exemple #4
0
    def datagram_received(self, data, addr):

        socket = self.transport.get_extra_info('socket') \
            if self.transport else None
        try:

            received_date = datetime.now()
            reply = Packet(packet=data,
                           dict=self.client.dict,
                           creation_date=received_date)

            if reply is not None and reply.id in self.pending_requests:
                req = self.pending_requests[reply.id]
                packet = req['packet']

                reply.secret = packet.secret

                if packet.VerifyReply(reply, data):

                    if reply.message_authenticator and not \
                        reply.verify_message_authenticator(
                            original_authenticator=packet.authenticator):
                        self.logger.warn(
                            '[%s:%d:%d] Received invalid reply for id %d. %s' %
                            (self.server, self.port, socket.getsockname()[1]
                             if socket else '', reply.id,
                             'Invalid Message-Authenticator. Ignoring it.'))
                        self.errors += 1
                    else:

                        req['future'].set_result(reply)
                        # Remove request for map
                        del self.pending_requests[reply.id]
                else:
                    self.logger.warn(
                        '[%s:%d:%d] Received invalid reply for id %d. %s' %
                        (self.server, self.port, socket.getsockname()[1]
                         if socket else '', reply.id, 'Ignoring it.'))
                    self.errors += 1
            else:
                self.logger.warn(
                    '[%s:%d:%d] Received invalid reply with id %d: %s.\nIgnoring it.'
                    % (
                        self.server,
                        self.port,
                        socket.getsockname()[1] if socket else '',
                        (-1, reply.id)[reply is not None],
                        data.hex(),
                    ))
                self.errors += 1

        except Exception as exc:
            self.logger.error(
                '[%s:%d:%d] Error on decode packet: %s.' %
                (self.server, self.port,
                 socket.getsockname()[1] if socket else '', (exc, '\n'.join(
                     traceback.format_exc().splitlines()))[self.client.debug]))
Exemple #5
0
 def setUp(self):
     self.data_session_id = 'some-id-1234'
     self.data_src_ip = '2.3.4.5'
     self.path = os.path.join(sys.modules["tests"].__path__[0], 'data')
     self.dictionary = Dictionary(os.path.join(self.path, 'dictionary'))
     self.pkt = Packet(id=0, secret=b'secret',
                       authenticator=b'01234567890ABCDEF',
                       dict=self.dictionary)
     self.pkt[b'Acct-Status-Type'] = 'Start'
     self.pkt[b'Acct-Session-Id'] = self.data_session_id
     self.pkt[b'User-Name'] = 'SomeUser'
     self.pkt.source = (self.data_src_ip, 5000)
def parse_packet(packet):
    if (packet.haslayer(Radius)):
        radius_packet = str(packet[Radius])
        pkt = Packet(packet=radius_packet, dict=Dictionary("dictionary"))

        for key, value in pkt.iteritems():
            attr = pkt._DecodeKey(key)
            value = pkt.__getitem__(attr)
            #print attr, value
            fout.write("%s %s\n" % (attr, str(value)))
    else:
        #packet.show()
        pass
    def CreatePacket(self, id, **args):
        if not id:
            raise Exception('Missing mandatory packet id')

        return Packet(id=id, dict=self.dict, secret=self.secret, **args)
Exemple #8
0
    def datagram_received(self, data, addr):
        self.logger.debug('[%s:%d] Received %d bytes from %s', self.ip,
                          self.port, len(data), addr)

        receive_date = datetime.utcnow()

        if addr[0] in self.hosts:
            remote_host = self.hosts[addr[0]]
        elif '0.0.0.0' in self.hosts:
            remote_host = self.hosts['0.0.0.0']
        else:
            self.logger.warn('[%s:%d] Drop package from unknown source %s',
                             self.ip, self.port, addr)
            return

        try:
            self.logger.debug('[%s:%d] Received from %s packet: %s', self.ip,
                              self.port, addr, data.hex())
            req = Packet(packet=data, dict=self.server.dict)
        except Exception as exc:
            self.logger.error('[%s:%d] Error on decode packet: %s', self.ip,
                              self.port, exc)
            return

        try:
            if req.code in (AccountingResponse, AccessAccept, AccessReject,
                            CoANAK, CoAACK, DisconnectNAK, DisconnectACK):
                raise ServerPacketError('Invalid response packet %d' %
                                        req.code)

            elif self.server_type == ServerType.Auth:
                if req.code != AccessRequest:
                    raise ServerPacketError(
                        'Received non-auth packet on auth port')
                req = AuthPacket(secret=remote_host.secret,
                                 dict=self.server.dict,
                                 packet=data)
                if self.server.enable_pkt_verify:
                    if req.VerifyAuthRequest():
                        raise PacketError('Packet verification failed')

            elif self.server_type == ServerType.Coa:
                if req.code != DisconnectRequest and req.code != CoARequest:
                    raise ServerPacketError(
                        'Received non-coa packet on coa port')
                req = CoAPacket(secret=remote_host.secret,
                                dict=self.server.dict,
                                packet=data)
                if self.server.enable_pkt_verify:
                    if req.VerifyCoARequest():
                        raise PacketError('Packet verification failed')

            elif self.server_type == ServerType.Acct:

                if req.code != AccountingRequest:
                    raise ServerPacketError(
                        'Received non-acct packet on acct port')
                req = AcctPacket(secret=remote_host.secret,
                                 dict=self.server.dict,
                                 packet=data)
                if self.server.enable_pkt_verify:
                    if req.VerifyAcctRequest():
                        raise PacketError('Packet verification failed')

            # Call request callback
            self.request_callback(self, req, addr)
        except Exception as exc:
            if self.server.debug:
                self.logger.exception('[%s:%d] Error for packet from %s',
                                      self.ip, self.port, addr)
            else:
                self.logger.error('[%s:%d] Error for packet from %s: %s',
                                  self.ip, self.port, addr, exc)

        process_date = datetime.utcnow()
        self.logger.debug('[%s:%d] Request from %s processed in %d ms',
                          self.ip, self.port, addr,
                          (process_date - receive_date).microseconds / 1000)
Exemple #9
0
    def datagram_received(self, data, addr):
        self.logger.debug('[%s:%d] Received %d bytes from %s', self.ip,
                          self.port, len(data), addr)

        receive_date = datetime.utcnow()

        remote_host = self.__get_remote_host__(addr[0])

        if remote_host:

            try:
                if self.server.debug:
                    self.logger.info('[%s:%d] Received from %s packet: %s.' %
                                     (self.ip, self.port, addr, data.hex()))
                req = Packet(packet=data, dict=self.server.dict)

            except Exception as exc:
                self.logger.error(
                    '[%s:%d] Error on decode packet: %s. Ignore it.' %
                    (self.ip, self.port, exc))
                req = None

            if not req:
                return

            try:
                if req.code in (AccountingResponse, AccessAccept, AccessReject,
                                CoANAK, CoAACK, DisconnectNAK, DisconnectACK):
                    raise ServerPacketError('Invalid response packet %d' %
                                            req.code)

                elif self.server_type == ServerType.Auth:

                    if req.code != AccessRequest:
                        raise ServerPacketError(
                            'Received not-authentication packet '
                            'on authentication port')
                    req = AuthPacket(secret=remote_host.secret,
                                     dict=self.server.dict,
                                     packet=data)

                    if self.server.enable_pkt_verify and \
                            req.message_authenticator and \
                        not req.verify_message_authenticator():
                        raise PacketError(
                            'Received invalid Message-Authenticator')

                elif self.server_type == ServerType.Coa:

                    if req.code != DisconnectRequest and \
                            req.code != CoARequest:
                        raise ServerPacketError(
                            'Received not-coa packet on coa port')
                    req = CoAPacket(secret=remote_host.secret,
                                    dict=self.server.dict,
                                    packet=data)
                    if self.server.enable_pkt_verify:
                        if not req.VerifyCoARequest():
                            raise PacketError('Packet verification failed')
                        if req.message_authenticator and \
                            not req.verify_message_authenticator():
                            raise PacketError(
                                'Received invalid Message-Authenticator')

                elif self.server_type == ServerType.Acct:

                    if req.code != AccountingRequest:
                        raise ServerPacketError(
                            'Received not-accounting packet on '
                            'accounting port')
                    req = AcctPacket(secret=remote_host.secret,
                                     dict=self.server.dict,
                                     packet=data)

                    if self.server.enable_pkt_verify:
                        if not req.VerifyAcctRequest():
                            raise PacketError('Packet verification failed')
                        if req.message_authenticator and not \
                            req.verify_message_authenticator():
                            raise PacketError(
                                'Received invalid Message-Authenticator')

                # Call request callback
                self.request_callback(self, req, addr)

                self.requests += 1

            except Exception as e:
                self.logger.error(
                    '[%s:%d] Unexpected error for packet from %s: %s' %
                    (self.ip, self.port, addr,
                     (e, '\n'.join(traceback.format_exc().splitlines())
                      )[self.server.debug]))

        else:
            self.logger.error('[%s:%d] Drop package from unknown source %s',
                              self.ip, self.port, addr)

        process_date = datetime.utcnow()
        self.logger.debug('[%s:%d] Request from %s processed in %d ms',
                          self.ip, self.port, addr,
                          (process_date - receive_date).microseconds / 1000)