示例#1
0
def parse_pcap_file(file_path):
    """pcap parser.

    parse a pcap file to get a list :class:`TcpPacket` objects

    Args:
        file_path (str): address of the Pcap file that is ready to be parsed
    Returns:
        list of :class:TcpPacket of found conversations in the Pcap file
    Raises:
        :class:FileParsingException if either file format were not recognized or file was not found
    """
    conn_dict = OrderedDict()
    all_packets = []
    try:
        with io.open(file_path, "rb") as infile:
            file_format, head = get_file_format(infile)
            if file_format == FileFormat.PCAP:
                pcap_file = pcap.PcapFile(infile, head).read_packet
            elif file_format == FileFormat.PCAP_NG:
                pcap_file = pcapng.PcapngFile(infile, head).read_packet
            else:
                FileParsingException("unknown file format.")
            for tcp_pac in packet_parser.read_tcp_packet(pcap_file):
                key = tcp_pac.gen_key()
                # we already have this conn
                if key in conn_dict:
                    url = conn_dict[key].on_packet(tcp_pac)
                    if url is not None:
                        packet = TcpPacket()
                        packet.request = url
                        splited = str(key).split('-')
                        packet.sourceHost = splited[0].split(':')[0]
                        packet.destinationHost = splited[1].split(':')[0]
                        packet.sourcePort = splited[0].split(':')[1]
                        packet.destinationPort = splited[1].split(':')[1]
                        all_packets.append(packet)
                    # conn closed.
                    if conn_dict[key].closed():
                        conn_dict[key].finish()
                        del conn_dict[key]
                # begin tcp connection.
                elif tcp_pac.syn and not tcp_pac.ack:
                    conn_dict[key] = TcpConnection(tcp_pac)
                elif utils.is_request(tcp_pac.body):
                    # tcp init before capture, we start from a possible http request header.
                    conn_dict[key] = TcpConnection(tcp_pac)
    except (FileNotFoundError, FileParsingException):
        raise FileParsingException("parse_pcap failed to parse " +
                                   str(file_path))
    # finish connection which not close yet
    for conn in conn_dict.values():
        conn.finish()
    return all_packets
示例#2
0
def parse_pcap_file(file_path):
    """pcap parser.

    parse a pcap file to get a list :class:`TcpPacket` objects

    Args:
        file_path (str): address of the Pcap file that is ready to be parsed
    Returns:
        list of :class:TcpPacket of found conversations in the Pcap file
    Raises:
        :class:FileParsingException if either file format were not recognized or file was not found
    """
    conn_dict = OrderedDict()
    all_packets = []
    try:
        with io.open(file_path, "rb") as infile:
            file_format, head = get_file_format(infile)
            if file_format == FileFormat.PCAP:
                pcap_file = pcap.PcapFile(infile, head).read_packet
            elif file_format == FileFormat.PCAP_NG:
                pcap_file = pcapng.PcapngFile(infile, head).read_packet
            else:
                FileParsingException("unknown file format.")
            for tcp_pac in packet_parser.read_tcp_packet(pcap_file):
                key = tcp_pac.gen_key()
                # we already have this conn
                if key in conn_dict:
                    url = conn_dict[key].on_packet(tcp_pac)
                    if url is not None:
                        packet = TcpPacket()
                        packet.request = url
                        splited = str(key).split('-')
                        packet.sourceHost = splited[0].split(':')[0]
                        packet.destinationHost = splited[1].split(':')[0]
                        packet.sourcePort = splited[0].split(':')[1]
                        packet.destinationPort = splited[1].split(':')[1]
                        all_packets.append(packet)
                    # conn closed.
                    if conn_dict[key].closed():
                        conn_dict[key].finish()
                        del conn_dict[key]
                # begin tcp connection.
                elif tcp_pac.syn and not tcp_pac.ack:
                    conn_dict[key] = TcpConnection(tcp_pac)
                elif utils.is_request(tcp_pac.body):
                    # tcp init before capture, we start from a possible http request header.
                    conn_dict[key] = TcpConnection(tcp_pac)
    except (FileNotFoundError, FileParsingException):
        raise FileParsingException("parse_pcap failed to parse " + str(
            file_path))
    # finish connection which not close yet
    for conn in conn_dict.values():
        conn.finish()
    return all_packets
示例#3
0
    def connections(self,
                    source=None,
                    destination=None,
                    simplify=False,
                    show_port=False):
        """parsed connections.

        The ``connections`` function is a list that contains all connections
        from source to any or from any to destination

        Args:
            source (str): Source Address in Network Connections
            destination (str): Destination Address in Network Connections
            simplify (bool): should we simplify the results
            show_port (bool): should we hide port numbers
        Returns:
            a List of :class:`TcpPacket` or an :class:`OrderedDict` containing all the comminucations from src or to the dst
        Raises:
            None

        >>> from aptdetector.network.sniffer import BaseSniffer
        >>> sni = BaseSniffer()
        >>> sni.pcap_file='examples/test.pcap'
        >>> sni.parse()
        >>> sni.connections(destination='173.123.12.1')
        >>> sni.connections(source='182.160.157.199',show_port=True)
        OrderedDict([('182.160.157.199:80', ['192.168.204.136:49174', '192.168.204.136:49178', '192.168.204.136:49178',\
 '192.168.204.136:49178', '192.168.204.136:49178', '192.168.204.136:49178'])])
        >>>
        >>> sni.connections(source='173.244.195.17',show_port=True,simplify=True)
        OrderedDict([('173.244.195.17:80', ['192.168.204.136:49185', '192.168.204.136:49187'])])
        >>>
        >>> sni.connections(destination='192.168.204.136',show_port=True,simplify=True)
        OrderedDict([('192.168.204.136:49174', ['182.160.157.199:80']), ('192.168.204.136:49178', ['182.160.157.199:80']),\
 ('192.168.204.136:49184', ['108.61.196.84:80']), ('192.168.204.136:49185', ['173.244.195.17:80']), ('192.168.204.136:49187',\
 ['173.244.195.17:80'])])
        """
        if source is not None:
            if TcpPacket.valid_ip(source):
                target = source
                target_id = 1
            else:
                print("source is not a correct ip")
                return None
        elif destination is not None:
            if TcpPacket.valid_ip(destination):
                target = destination
                target_id = 2
            else:
                print("destination is not a correct ip")
                return None
        else:
            target = None
        all_packets = OrderedDict()
        if target is None:
            return self.__conversations
        else:
            for pkt in self.__conversations:
                if (pkt.sourceHost != target and target_id == 1) or (
                        pkt.destinationHost != target and target_id == 2):
                    continue
                key = pkt.create_packet(target_id=target_id,
                                        show_port=show_port,
                                        reverse=False)
                reverse_key = pkt.create_packet(target_id=target_id,
                                                show_port=show_port,
                                                reverse=True)
                if key in all_packets.keys():
                    # all_packets have been initialized before
                    if reverse_key in all_packets[key] and simplify is True:
                        # duplicate, no need to append
                        pass
                    else:
                        # new value
                        all_packets[key].append(reverse_key)
                else:
                    # all_packet should be initialized
                    all_packets[key] = [reverse_key]
            if len(all_packets) < 1:
                return None
            return all_packets