예제 #1
0
    def on_packet(self, packet):
        """
        :type packet: TcpPack
        """
        if self.is_http is None and packet.body:
            self.is_http = is_request(packet.body)

        if self.is_http == False:
            return

        if packet.source_key() == self.client_key:
            send_stream = self.up_stream
            confirm_stream = self.down_stream
            pac_type = HttpType.RESPONSE
        else:
            send_stream = self.down_stream
            confirm_stream = self.up_stream
            pac_type = HttpType.REQUEST

        if len(packet.body) > 0:
            send_stream.append_packet(packet)
        if packet.syn:
            pass
        if packet.ack:
            packets = confirm_stream.retrieve_packet(packet.ack_seq)
            if packets:
                for packet in packets:
                    self.http_parser.send(pac_type, packet.body, packet.micro_second)
        if packet.fin:
            send_stream.status = 1
예제 #2
0
def parse_pcap_file(infile):
    """
    :type infile:file
    """

    conn_dict = OrderedDict()

    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:
        print("unknown file format.", file=sys.stderr)
        sys.exit(1)

    _filter = config.get_filter()
    for tcp_pac in packet_parser.read_tcp_packet(pcap_file):
        # filter
        if not (_filter.by_ip(tcp_pac.source) or _filter.by_ip(tcp_pac.dest)):
            continue
        if not (_filter.by_port(tcp_pac.source_port) or _filter.by_port(tcp_pac.dest_port)):
            continue

        key = tcp_pac.gen_key()
        # we already have this conn
        if key in conn_dict:
            conn_dict[key].on_packet(tcp_pac)
            # conn closed.
            # TODO: The connection should be closed after an expired time
            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.
            # TODO: The packet maybe a http response header
            conn_dict[key] = TcpConnection(tcp_pac)

    # finish connection which not close yet
    for conn in conn_dict.values():
        conn.finish()