Пример #1
0
void reader_libpcap_start() {
    int dlt_to_linktype(int dlt);

    //ALW - Bug: assumes all linktypes are the same
    pcapFileHeader.linktype = dlt_to_linktype(pcap_datalink(pcaps[0])) | pcap_datalink_ext(pcaps[0]);
    pcapFileHeader.snaplen = pcap_snapshot(pcaps[0]);

    pcap_t *dpcap = pcap_open_dead(pcapFileHeader.linktype, pcapFileHeader.snaplen);
    int t;
    for (t = 0; t < MOLOCH_FILTER_MAX; t++) {
        if (config.bpfsNum[t]) {
            int i;
            if (bpf_programs[t]) {
                for (i = 0; i < config.bpfsNum[t]; i++) {
                    pcap_freecode(&bpf_programs[t][i]);
                }
            } else {
                bpf_programs[t] = malloc(config.bpfsNum[t]*sizeof(struct bpf_program));
            }
            for (i = 0; i < config.bpfsNum[t]; i++) {
                if (pcap_compile(dpcap, &bpf_programs[t][i], config.bpfs[t][i], 1, PCAP_NETMASK_UNKNOWN) == -1) {
                    LOG("ERROR - Couldn't compile filter: '%s' with %s", config.bpfs[t][i], pcap_geterr(dpcap));
                    exit(1);
                }
            }
            moloch_reader_should_filter = reader_libpcap_should_filter;
        }
    }

    int i;
    for (i = 0; i < MAX_INTERFACES && config.interface[i]; i++) {
        if (config.bpf) {
            struct bpf_program   bpf;

            if (pcap_compile(pcaps[i], &bpf, config.bpf, 1, PCAP_NETMASK_UNKNOWN) == -1) {
                LOG("ERROR - Couldn't compile filter: '%s' with %s", config.bpf, pcap_geterr(pcaps[i]));
                exit(1);
            }

            if (pcap_setfilter(pcaps[i], &bpf) == -1) {
                LOG("ERROR - Couldn't set filter: '%s' with %s", config.bpf, pcap_geterr(pcaps[i]));
                exit(1);
            }
        }

        char name[100];
        snprintf(name, sizeof(name), "moloch-pcap%d", i);
        g_thread_new(name, &reader_libpcap_thread, (gpointer)pcaps[i]);
    }
}
Пример #2
0
void
process_packet(unsigned char *user, const struct pcap_pkthdr *header,
        const unsigned char *packet)
{
    pcap_t *pcap;
    const struct sll_header *sll;
    const struct ether_header *ether_header;
    const struct ip *ip;
    unsigned short packet_type;

    pcap = (pcap_t *) user;

    // Parse packet
    switch (pcap_datalink(pcap)) {
        
    case DLT_LINUX_SLL:
        sll = (struct sll_header *) packet;
        packet_type = ntohs(sll->sll_protocol);
        ip = (const struct ip *) (packet + sizeof(struct sll_header));
        
        break;
        
    case DLT_EN10MB:
        ether_header = (struct ether_header *) packet;
        packet_type = ntohs(ether_header->ether_type);
        ip = (const struct ip *) (packet + sizeof(struct ether_header));
        
        break;
        
    case DLT_RAW:
        packet_type = ETHERTYPE_IP; //This is raw ip
        ip = (const struct ip *) packet;
        
        break;
        
    default:
        
        return;
        
    }
    
    if (packet_type != ETHERTYPE_IP)
        return;
    
    if (capture_file)
        output_offline_update(header->ts);
    
    process_ip(pcap, ip, header->ts);
    
}
Пример #3
0
int openpcap(struct capture_data *capdata)
{

	/* Assume for now it's a libpcap file */
	p = pcap_open_offline(capdata->pcapfilename, errbuf);
	if (p == NULL) {
		perror("Unable to open capture file");
		return (-1);
	}

	/* Determine link type */
	capdata->pcaptype = pcap_datalink(p);

	/* Determine offset to EAP frame based on link type */
	switch (capdata->pcaptype) {
	case DLT_NULL:
	case DLT_EN10MB:
		/* Standard ethernet header */
		capdata->dot1x_offset = 14;
		capdata->l2type_offset = 12;
		capdata->dstmac_offset = 0;
		capdata->srcmac_offset = 6;
		break;
	case DLT_IEEE802_11:
		/* 24 bytes 802.11 header, 8 for 802.2 header */
		capdata->dot1x_offset = 32;
		capdata->l2type_offset = 30;
		capdata->dstmac_offset = 4;
		capdata->srcmac_offset = 10;
		break;
	case DLT_PRISM_HEADER:
		/* 802.11 frames with AVS header, AVS header is 144 bytes */
		capdata->dot1x_offset = 32 + 144;
		capdata->l2type_offset = 30 + 144;
		capdata->dstmac_offset = 4 + 144;
		capdata->srcmac_offset = 10 + 144;
		break;
	case DLT_IEEE802_11_RADIO:
		capdata->dot1x_offset = 0;
		capdata->l2type_offset = 0;
		capdata->dstmac_offset = 0;
		capdata->srcmac_offset = 0;
		break;
	default:
		/* Unknown/unsupported pcap type */
		return (1);
	}

	return (0);
}
Пример #4
0
int
pcap_list_datalinks(pcap_t *p, int **dlt_buffer)
{
	/*
	 * This platform doesn't support changing the DLT for an
	 * interface.  Return a list of DLTs containing only the
	 * DLT this device supports.
	 */
	*dlt_buffer = (int*)malloc(sizeof(**dlt_buffer));
	if (*dlt_buffer == NULL)
		return (-1);
	**dlt_buffer = pcap_datalink(p);
	return (1);
}
Пример #5
0
PtrPacket BaseSniffer::next_packet() {
    sniff_data data;
    const int iface_type = pcap_datalink(handle_);
    pcap_handler handler = 0;
    if (extract_raw_) {
        handler = &sniff_loop_handler<RawPDU>;
    }
    else if (iface_type == DLT_EN10MB) {
        handler = sniff_loop_eth_handler;
    }
    else if (iface_type == DLT_IEEE802_11_RADIO) {
        #ifdef TINS_HAVE_DOT11
            handler = &sniff_loop_handler<RadioTap>;
        #else
            throw protocol_disabled();
        #endif
    }
    else if (iface_type == DLT_IEEE802_11) {
        #ifdef TINS_HAVE_DOT11
            handler = sniff_loop_dot11_handler;
        #else
            throw protocol_disabled();
        #endif
    }
    #ifdef DLT_PKTAP
    else if (iface_type == DLT_PKTAP) {
        handler = &sniff_loop_handler<PKTAP>;
    }
    #endif // DLT_PKTAP
    else if (iface_type == DLT_NULL) {
        handler = &sniff_loop_handler<Tins::Loopback>;
    }
    else if (iface_type == DLT_LINUX_SLL) {
        handler = &sniff_loop_handler<SLL>;
    }
    else if (iface_type == DLT_PPI) {
        handler = &sniff_loop_handler<PPI>;
    }
    else {
        throw unknown_link_type();
    }
    // keep calling pcap_loop until a well-formed packet is found.
    while (data.pdu == 0 && data.packet_processed) {
        data.packet_processed = false;
        if (pcap_loop(handle_, 1, handler, (u_char*)&data) < 0) {
            return PtrPacket(0, Timestamp());
        }
    }
    return PtrPacket(data.pdu, data.tv);
}
Пример #6
0
pcap_t* snif_init_session( char* interface, const char* expr_filter, char** err_buff )
{
	pcap_t* handle;
	*err_buff = (char*) calloc( PCAP_ERRBUF_SIZE, sizeof(char) );

	if( !interface ) {
		interface = pcap_lookupdev(*err_buff);
		if ( !interface ) {
			return SNIF_RESULT_FAIL;
		}
	}

	handle = pcap_open_live(interface, BUFSIZ, DEVICE_PROMISCUOUS_MODE, DEVICE_READ_TIME_OUT, *err_buff);
	if( !handle ) {
		return SNIF_RESULT_FAIL;
	}

	if( pcap_datalink( handle ) != DLT_EN10MB ) {
		pcap_close(handle);
		sprintf(*err_buff, "Interface \"%s\" doesn't provide Ethernet headers - not supported\n", interface);
		return SNIF_RESULT_FAIL;
	}

	if( expr_filter ) {
		bpf_u_int32 mask;
		bpf_u_int32 net;
		struct bpf_program packet_filter;

		if( pcap_lookupnet(interface, &net, &mask, *err_buff) == -1 ) {
			pcap_close(handle);
			return SNIF_RESULT_FAIL;
		}

		if( pcap_compile(handle, &packet_filter, expr_filter, 0, net) == -1 ) {
			*err_buff = pcap_geterr(handle);
			pcap_close(handle);
			return SNIF_RESULT_FAIL;
		}

		if( pcap_setfilter(handle, &packet_filter) == -1 ) {
			*err_buff = pcap_geterr(handle);
			pcap_close(handle);
			return SNIF_RESULT_FAIL;
		}
	}

	printf("\n\t\tUSING INTERFACE: \"%s\"\n\n", interface);
	free(*err_buff);
	return handle;
}
Пример #7
0
static pcap_t* initialize_pcap(const char* const interface) {
  char errbuf[PCAP_ERRBUF_SIZE];
  pcap_t* const handle = pcap_open_live(interface, BUFSIZ, 0, 1000, errbuf);
  if (!handle) {
    fprintf(stderr, "Couldn't open device %s: %s\n", interface, errbuf);
    return NULL;
  }

  if (pcap_datalink(handle) != DLT_EN10MB) {
    fprintf(stderr, "Must capture on an Ethernet link\n");
    return NULL;
  }
  return handle;
}
Пример #8
0
int main(int argc, char *argv[])
{
	char *dev, errbuf[PCAP_ERRBUF_SIZE];
	pcap_t *handle;
	int selectable_fd;

	if (argc == 2) {
		dev = argv[1];
	} else {
		dev = pcap_lookupdev(errbuf);
	}

	if (dev == NULL) {
		fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
		return (2);
	}

	handle = pcap_open_live(dev, BUFSIZ, 1, 0, errbuf);
	if (handle == NULL) {
		fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
		return (2);
	}

	if (pcap_datalink(handle) != DLT_EN10MB) {
		fprintf(stderr, "Device %s doesn't provide Ethernet headers - "
		                "not supported\n",
		        dev);
		return (2);
	}

	if (pcap_setnonblock(handle, 1, errbuf) != 0) {
		fprintf(stderr, "Non-blocking mode failed: %s\n", errbuf);
		return (2);
	}

	selectable_fd = pcap_get_selectable_fd(handle);
	if (-1 == selectable_fd) {
		fprintf(stderr, "pcap handle not selectable.\n");
		return (2);
	}

	init_curses();
	mvprintw(0, 0, "Device: %s\n", dev);

	grab_packets(selectable_fd, handle);

	/* And close the session */
	pcap_close(handle);
	return 0;
}
int parsePcapFile(struct list *list, pcap_t *offline, int partitionRule,
		  usec_t fixed_deltas) {
  const u_char	*bytes=(u_char *)1;

  while (bytes) {
    struct pcap_pkthdr	h;
    struct packet	*this;
    struct timeval	previous_ts; /* timestamp (non il delta!) del
				      * pacchetto precedente  */
    
    if (NULL == (bytes = pcap_next(offline, &h)))
      break;

    if (NULL == (this = malloc(sizeof(struct packet)))) {
      fprintf(stderr, "stop reading pcap file: not enough memory\n");
      break; 			/* eom */
    }
    if (NULL == (this->data = malloc(h.caplen))) {
      fprintf(stderr, "stop reading pcap file: not enough memory\n");
      free(this);
     break; 			/* eom */
    }
    this->next = NULL;
    this->interface =
      partitionPcapStream(pcap_datalink(offline), bytes, partitionRule);
    this->len = h.caplen;
    memcpy(this->data, bytes, h.caplen);
   
    if (!list->size) {
      list->head = this;
      list->tail = this;
      this->delta = 0;
    } else {
      list->tail->next = this;
      list->tail = this;
      if (!fixed_deltas)
	this->delta = usec_timeval_abs_sub(&h.ts, &previous_ts);
      else
	this->delta = fixed_deltas;
    } 
    previous_ts = h.ts;
    list->size ++;
  } /* end while */

  if ('\0' != *pcap_geterr(offline)) {
    return -1;
  }
  pcap_close(offline);
  return 0;
}
Пример #10
0
/* Calculate offset to add to bypass link-layer headers, so
 * that we can find the IP Packet Header's data structure in
 * memory. This offset is intended to be applied to the 'bytes'
 * pointer that is passed as an argument to a pcap callback routine.*/
static int calc_ip_offset_for_link(pcap_t *pc)
{
        int if_type = pcap_datalink(pc);
    
        switch (if_type) {
	  case DLT_EN10MB:                 /* Ethernets */
	            return 14;
	  case DLT_RAW:                    /* Raw IP capture */
	            return 0;
	  case DLT_LINUX_SLL:              /* Linux 'cooked' capture */
	            return 16;
	}
        return 0;                          /* RAW by default */
}
Пример #11
0
int
capture_offline(const char *infile, const char *outfile)
{
    capture_info_t *capinfo;

    // Error text (in case of file open error)
    char errbuf[PCAP_ERRBUF_SIZE];

    // Set capture mode
    capture_cfg.status = CAPTURE_OFFLINE_LOADING;

    // Create a new structure to handle this capture source
    if (!(capinfo = sng_malloc(sizeof(capture_info_t)))) {
        fprintf(stderr, "Can't allocate memory for capture data!\n");
        return 1;
    }

    // Set capture input file
    capinfo->infile = infile;

    // Open PCAP file
    if ((capinfo->handle = pcap_open_offline(infile, errbuf)) == NULL) {
        fprintf(stderr, "Couldn't open pcap file %s: %s\n", infile, errbuf);
        return 1;
    }

    // Get datalink to parse packets correctly
    capinfo->link = pcap_datalink(capinfo->handle);

    // Check linktypes sngrep knowns before start parsing packets
    if ((capinfo->link_hl = datalink_size(capinfo->link)) == -1) {
        fprintf(stderr, "Unable to handle linktype %d\n", capinfo->link);
        return 3;
    }

    // Add this capture information as packet source
    vector_append(capture_cfg.sources, capinfo);

    // If requested store packets in a dump file
    if (outfile && !capture_cfg.pd) {
        if ((capture_cfg.pd = dump_open(outfile)) == NULL) {
            fprintf(stderr, "Couldn't open output dump file %s: %s\n", outfile,
                    pcap_geterr(capinfo->handle));
            return 2;
        }
    }

    return 0;
}
Пример #12
0
/******************************************************************************
 *  set_cap_dev                                                               *
 *                                                                            *
 *  sniff on appropriate device, set filter, and calculate datalink offset    *
 *  arg1: (char *)   pointer to device name                                   *
 *  arg2: (char *)   pointer to filter string                                 *
 *  ret:  (pcap_t *) pointer to pcap device                                   *
 ******************************************************************************/
pcap_t *set_cap_dev (char *device, char *filter)    {
    unsigned int network, netmask;  /* for filter setting    */
    struct bpf_program prog;        /* store compiled filter */
    struct pcap_pkthdr pcap_h;      /* pcap packet header    */
    pcap_t *capdev;                 /* the capture device    */
    char errbuf[PCAP_ERRBUF_SIZE];  /* pcap error buffer     */

    pcap_lookupnet(device, &network, &netmask, errbuf);

    if ((capdev = pcap_open_live(device, SNAPLEN, PROMISC, 1000, errbuf)) == NULL)    {
        perror("pcap_open_live");
        exit (EXIT_FAILURE);
    }

    /*
     *  we only want to see traffic specified by filter
     *  so compile and set it
     */

    pcap_compile(capdev, &prog, filter, 0, netmask);
    pcap_setfilter(capdev, &prog);

    /*
     *  set datalink offset, EN10MB is all we really need
     */

    switch (pcap_datalink(capdev)) {
        case DLT_EN10MB:
            offset = 14;
            break;
        case DLT_IEEE802:
            offset = 22;
            break;
        case DLT_FDDI:
            offset = 21;
            break;
        case DLT_NULL:
            offset = 4;
            break;
        case DLT_RAW:
            offset = 0;
            break;
        default:
            fprintf(stderr, "\n%s bad datalink type", device);
            exit (EXIT_FAILURE);
            break;
  }
  return capdev;
}
int main(void)
{
    pcap_t *sniffer_handle = NULL;
    char errbuf[PCAP_ERRBUF_SIZE];
    char *device = NULL;
    int counter = 0;
    bpf_u_int32 mask;
    bpf_u_int32 net;
    char *mask_ptr = NULL;
    char *net_ptr = NULL;
    struct in_addr addr;
    struct bpf_program fp;
    char *filter_str = "port 80";
    memset(errbuf, 0, PCAP_ERRBUF_SIZE);

    device = pcap_lookupdev(errbuf);
    if (device == NULL)
        err_die(errbuf);
    sniffer_handle = pcap_open_live(device, BUFSIZ, 1, 512, errbuf);
    if (sniffer_handle == NULL)
        err_die(errbuf);

    // test ethernet device or not
    if (pcap_datalink(sniffer_handle) != DLT_EN10MB)
    {
        printf("Device %s doesn't provide Ethernet headers\n", device);
        return 1;
    }
    if (pcap_lookupnet(device, &net, &mask, errbuf) == -1)
        err_die(errbuf);
    addr.s_addr = net;
    net_ptr = inet_ntoa(addr);
    printf("网络号 : %s\n", net_ptr);
    addr.s_addr = mask;
    mask_ptr = inet_ntoa(addr);
    printf("掩码 : %s\n", mask_ptr);

    /*
    if (pcap_compile(sniffer_handle, &fp, filter_str, 0, net) == -1)
    	err_die("pcap_compile error");
    if (pcap_setfilter(sniffer_handle, &fp) == -1)
    	err_die("pcap_setfilter error");
    */

    pcap_loop(sniffer_handle, -1, process_packet, (u_char *)&counter);


    return 0;
}
Пример #14
0
int 
main(int argc, char* argv[])
{
    char *device; /* Device name to capture on. */
    char errbuf[PCAP_ERRBUF_SIZE]; /* Error buffer */
    pcap_t *handle; /* Packet capture handle */
    int loop_return;

    init(argc, argv);
	
    device = pcap_lookupdev(errbuf);
    if (device == NULL)
    {
        fprintf(stderr, "Could not find default device: %s\n", errbuf);
        exit(EXIT_FAILURE);
    }
	
    handle = get_pcap_handle(device, errbuf);

    if (handle == NULL)
    {
        fprintf(stderr, "Could not open device %s: %s\n", device, errbuf);
        exit(EXIT_FAILURE);
    }


    if (pcap_datalink(handle) != DLT_EN10MB)
    {
        fprintf(stderr, "%s is not an Ethernet device.\n", device);
        exit(EXIT_FAILURE);
    }

    printf("Capturing packets......\n");

    loop_return = pcap_loop(handle, config.packets, handle_packet, NULL);
    DEBUG(printf("Packet capture complete\n"));
    
    if (loop_return == -1)
    {
        printf("An error occurred when capturing %s\n", pcap_geterr(handle));
    }

    cleanup();

    go_interactive();

    pcap_close(handle);
    return 0;
}
Пример #15
0
static PyObject * p_datalink (PyObject *self, PyObject *args)
{
  pcap_t * ppcap;
  if (!PyArg_ParseTuple(args, "l", (long int*)&ppcap)) return NULL;
  int rv = pcap_datalink(ppcap);
  const char * rvs = NULL;
  for (num_name_pair * nn = link_types; nn->name != NULL; nn++)
  {
    if (nn->num == rv)
    {
      rvs = nn->name;
      break;
    }
  }
  return Py_BuildValue("is", rv, rvs);
}
Пример #16
0
/* Returns the supplied pcap capture file data link type */
int get_pcapdatalink(char *filename) {

    pcap_t *p;
    int    datalink = 0;
    char   errbuf[PCAP_ERRBUF_SIZE];

    p = pcap_open_offline(filename, errbuf);

    if (p == NULL) {
	return(-1);
    }

    datalink = pcap_datalink(p);
    pcap_close(p);
    return(datalink);
}
Пример #17
0
    static int
epcap_open(EPCAP_STATE *ep)
{
    char errbuf[PCAP_ERRBUF_SIZE];

    if (ep->file) {
        PCAP_ERRBUF(ep->p = pcap_open_offline(ep->file, errbuf));
    } else {
        if (ep->dev == NULL)
            PCAP_ERRBUF(ep->dev = pcap_lookupdev(errbuf));

#ifdef HAVE_PCAP_CREATE
        PCAP_ERRBUF(ep->p = pcap_create(ep->dev, errbuf));
        (void)pcap_set_snaplen(ep->p, ep->snaplen);
        (void)pcap_set_promisc(ep->p, ep->opt & EPCAP_OPT_PROMISC);
        (void)pcap_set_timeout(ep->p, ep->timeout);
        if (ep->bufsz > 0)
            (void)pcap_set_buffer_size(ep->p, ep->bufsz);
        switch (pcap_activate(ep->p)) {
            case 0:
                break;
            case PCAP_WARNING:
            case PCAP_ERROR:
            case PCAP_WARNING_PROMISC_NOTSUP:
            case PCAP_ERROR_NO_SUCH_DEVICE:
            case PCAP_ERROR_PERM_DENIED:
                pcap_perror(ep->p, "pcap_activate: ");
                exit(EXIT_FAILURE);
            default:
                exit(EXIT_FAILURE);
        }
#else
        PCAP_ERRBUF(ep->p = pcap_open_live(ep->dev, ep->snaplen,
                    ep->opt & EPCAP_OPT_PROMISC, ep->timeout, errbuf));
#endif

        /* monitor mode */
#ifdef PCAP_ERROR_RFMON_NOTSUP
        if (pcap_can_set_rfmon(ep->p) == 1)
            (void)pcap_set_rfmon(ep->p, ep->opt & EPCAP_OPT_RFMON);
#endif
    }

    ep->datalink = pcap_datalink(ep->p);

    return 0;
}
Пример #18
0
void
Mod_fw_start_log_capture(FW_handle_T handle)
{
    struct fw_handle *fwh = handle->fwh;
    struct bpf_program  bpfp;
    char *pflog_if, *net_if;
    char errbuf[PCAP_ERRBUF_SIZE];
    char filter[PCAPFSIZ] = "ip and port 25 and action pass "
        "and tcp[13]&0x12=0x2";

    pflog_if = Config_get_str(handle->config, "pflog_if", "firewall",
                             PFLOG_IF);
    net_if = Config_get_str(handle->config, "net_if", "firewall",
                            NULL);

    if((fwh->pcap_handle = pcap_open_live(pflog_if, PCAPSNAP, 1, PCAPTIMO,
                                          errbuf)) == NULL)
    {
        i_critical("failed to initialize: %s", errbuf);
    }

    if(pcap_datalink(fwh->pcap_handle) != DLT_PFLOG) {
        pcap_close(fwh->pcap_handle);
        fwh->pcap_handle = NULL;
        i_critical("invalid datalink type");
    }

    if(net_if != NULL) {
        sstrncat(filter, " and on ", PCAPFSIZ);
        sstrncat(filter, net_if, PCAPFSIZ);
    }

    if((pcap_compile(fwh->pcap_handle, &bpfp, filter, PCAPOPTZ, 0) == -1)
       || (pcap_setfilter(fwh->pcap_handle, &bpfp) == -1))
    {
        i_critical("%s", pcap_geterr(fwh->pcap_handle));
    }

    pcap_freecode(&bpfp);
#ifdef BIOCLOCK
    if(ioctl(pcap_fileno(fwh->pcap_handle), BIOCLOCK) < 0) {
        i_critical("BIOCLOCK: %s", strerror(errno));
    }
#endif

    fwh->entries = List_create(destroy_log_entry);
}
Пример #19
0
pcap_t *pcap_init()
{
	pcap_t *handle;
	char errbuf[PCAP_ERRBUF_SIZE];
	if (pcap_type == Offline) {
		if(!(handle = pcap_open_offline(pcap_filename, errbuf))) {
			LOG(ERROR, "Could not open pcap file: %s\n", errbuf);
			exit(1);
		}
	}
	else {
		if (!(handle = pcap_open_live(pcap_intf, 96, 1, -1, errbuf))) {
			LOG(ERROR, "Could not open the device: %s\n", errbuf);
			exit(1);
		}
	}

	// set pcap filter
	char pf_buf[2048];
#define pf_fmt "tcp && ((src host %s && src port %d) || (dst host %s && dst port %d))"
	snprintf(pf_buf, sizeof(pf_buf), pf_fmt, server_ip, server_port, server_ip, server_port);
	if (pcap_compile(handle, &fp, pf_buf, 0, 0) == -1) {
	    LOG(ERROR, "Could not parse filter %s: %s.\n", pf_buf, pcap_geterr(handle));
	    exit(1);
	}
	
	if (pcap_setfilter(handle, &fp) == -1) {
	    LOG(ERROR, "Could not apply filter %s: %s.\n", pf_buf, pcap_geterr(handle));
	    exit(1);
	}

	// get pcap link type
	int link_type = pcap_datalink(handle);
	switch (link_type) {
		case LINKTYPE_ETHERNET:
			offset = 12;
			break;
		case LINKTYPE_LINUX_SLL:
			offset = 14;
			break;
		default:
			LOG(WARN, "Unknown link type (%x).\n", link_type);
			exit(1);
	}

	return handle;
}
Пример #20
0
static void
tcpeek_init_pcap(void) {
	char *ifname, errmsg[PCAP_ERRBUF_SIZE], expression[] = "tcp or icmp";
	struct bpf_program bpf;

	if(strisempty(g.option.ifname)) {
		ifname = pcap_lookupdev(errmsg);
		if(!ifname) {
			error_abort("%s", errmsg);
		}
		strncpy(g.option.ifname, ifname, sizeof(g.option.ifname) - 1);
	}
    g.pcap.pcap = pcap_create(g.option.ifname, errmsg);
	if(!g.pcap.pcap) {
		error_abort("%s", errmsg);
	}
    if(pcap_set_buffer_size(g.pcap.pcap, g.option.buffer * 1024 * 1024) != 0) {
        error_abort("%s", "can not set buffer size");
    }
    if(pcap_set_snaplen(g.pcap.pcap, DEFAULT_PCAP_SNAPLEN) != 0) {
        error_abort("%s", "can not set snaplen");
    }
    if(pcap_set_promisc(g.pcap.pcap, g.option.promisc) != 0) {
        error_abort("%s", "can not set promiscuous mode");
    }
    if(pcap_set_timeout(g.pcap.pcap, 1) != 0) {
        error_abort("%s", "can not set timeout");
    }
    if(pcap_activate(g.pcap.pcap) != 0) {
        error_abort("%s", pcap_geterr(g.pcap.pcap));
    }
	if(pcap_compile(g.pcap.pcap, &bpf, expression, 0, 0) == -1) {
		error_abort("%s '%s'", pcap_geterr(g.pcap.pcap), expression);
	}
	if(pcap_setfilter(g.pcap.pcap, &bpf) == -1){
		error_abort("%s", pcap_geterr(g.pcap.pcap));
	}
	pcap_freecode(&bpf);
	g.pcap.snapshot = pcap_snapshot(g.pcap.pcap);
	g.pcap.datalink = pcap_datalink(g.pcap.pcap);
	if(g.pcap.datalink != DLT_EN10MB && g.pcap.datalink != DLT_LINUX_SLL) {
		error_abort("not support datalink %s (%s)",
			pcap_datalink_val_to_name(g.pcap.datalink),
			pcap_datalink_val_to_description(g.pcap.datalink)
		);
	}
}
Пример #21
0
int main(int argc, char** argv) {
  if(argc < 2) {
    std::cerr << "Must pass interface to listen on" << std::endl;
    return 1;
  }

  std::string device = std::string(argv[1]);

  char errbuf[1024];
  pcap_t *handle;

  struct bpf_program fp;

  const std::string filter_expr = "type mgt subtype probe-req";

  handle = pcap_open_live("wlan0mon", 1024, true, 1000, errbuf);
  if(!handle) {
    std::cerr << "Unable to open device " << device << std::endl;
    return 2;
  }

  if(pcap_datalink(handle) != DLT_IEEE802_11_RADIO) {
    std::cerr << "Specified device is not 802.11" << std::endl;
    return 3;
  }

  if(pcap_compile(handle, &fp, filter_expr.c_str(), 0, PCAP_NETMASK_UNKNOWN) < 0) {
    std::cerr << "Error compiling filter to program" << std::endl;
    return 4;
  }

  if(pcap_setfilter(handle, &fp) < 0) {
    std::cerr << "Error creating filter on device" << std::endl;
    return 5;
  }

  std::cerr << "Listening for frames" << std::endl;

  pcap_loop(handle, 0, process_packet, NULL);

  std::cerr << "Shutting down" << std::endl;

  pcap_freecode(&fp);
  pcap_close(handle);

  return 0;
}
Пример #22
0
/* Find and prepare ethernet device for capturing */
pcap_t *prepare_capture(char *interface, int promisc, char *filename, char *capfilter) {
        char errbuf[PCAP_ERRBUF_SIZE];
        pcap_t *pcap_hnd;
        char *dev = NULL;
        bpf_u_int32 net, mask;
        struct bpf_program filter;

        if (!filename) {
                /* Starting live capture, so find and open network device */
                if (!interface) {
                        dev = pcap_lookupdev(errbuf);
                        if (dev == NULL)
                                LOG_DIE("Cannot find a valid capture device: %s", errbuf);
                } else {
                        dev = interface;
                }

                if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) net = 0;

                pcap_hnd = pcap_open_live(dev, BUFSIZ, promisc, 1000, errbuf);

                if (pcap_hnd == NULL)
                        LOG_DIE("Cannot open live capture on '%s': %s", dev, errbuf);
        } else {
                /* Reading from a saved capture, so open file */
                pcap_hnd = pcap_open_offline(filename, errbuf);

                if (pcap_hnd == NULL)
                        LOG_DIE("Cannot open saved capture file: %s", errbuf);
        }

        set_link_offset(pcap_datalink(pcap_hnd));

        /* Compile capture filter and apply to handle */
        if (pcap_compile(pcap_hnd, &filter, capfilter, 0, net) == -1)
                LOG_DIE("Cannot compile capture filter '%s': %s", capfilter, pcap_geterr(pcap_hnd));

        if (pcap_setfilter(pcap_hnd, &filter) == -1)
                LOG_DIE("Cannot apply capture filter: %s", pcap_geterr(pcap_hnd));

        pcap_freecode(&filter);

        if (!filename) LOG_PRINT("Starting capture on %s interface", dev);

        return pcap_hnd;
}
Пример #23
0
static void pcap_duplicate(struct Options *opts)
{
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t *in_pcap;
    pcap_t *out_pcap;
    pcap_dumper_t *dumper;
    int datalink;

    in_pcap = pcap_open_offline(opts->in_file, errbuf);
    if (in_pcap == NULL) {
        printf("Error opening %s: %s\n", opts->in_file, errbuf);
        return;
    }
    datalink = pcap_datalink(in_pcap);
    out_pcap = pcap_open_dead(datalink, pcap_snapshot(in_pcap));
    if (out_pcap == NULL) {
        pcap_close(in_pcap);
        puts("Error calling pcap_open_dead())");
        return;
    }
    dumper = pcap_dump_open(out_pcap, opts->out_file);
    if (dumper == NULL) {
        printf("Error opening output %s: %s\n", opts->out_file, pcap_geterr(out_pcap));
        pcap_close(in_pcap);
        pcap_close(out_pcap);
        return;
    }


    struct pcap_pkthdr hdr; 
    const unsigned char *packet;
    while ((packet = pcap_next(in_pcap, &hdr)) != NULL) {
        int i;
        for (i = 0; i < opts->count_n; i++) {
            if (opts->change_ip && datalink == DLT_EN10MB) { 
                change_ethpacket(&hdr, (unsigned char *)packet); //cast a way const ok.
            }
            pcap_dump((u_char*)dumper, &hdr, packet);
        }
    }


    pcap_dump_close(dumper);
    pcap_close(in_pcap);
    pcap_close(out_pcap);
}
Пример #24
0
struct mif *mi_open(char *iface)
{
    struct mif *mi;
    struct priv_if *pi;
    pcap_t *pkt_in, *pkt_out;
    char errbuf[PCAP_ERRBUF_SIZE];

    /* setup mi struct */
    mi = mi_alloc(sizeof(*pi));
    if (!mi)
        return NULL;

    mi->read  = mi_read;
    mi->write = mi_write;
    mi->close = mi_close;

    // for pkt in
    pkt_in = pcap_open_live(iface, 4096, 1, 10, errbuf);
    if (pkt_in == NULL) {
        printf("Unable to open interface %s in pcap: %s\n", iface, errbuf);
        return NULL;
    }

    if (pcap_datalink(pkt_in) != DLT_IEEE802_11_RADIO) {
        printf("Device %s doesn't provide 80211 radiotap header\n", iface);
        return NULL;
    }

    if (pcap_setnonblock(pkt_in, 1, errbuf) == -1) {
        printf("Device %s doesn't set non-blocking mode\n", iface);
        return NULL;
    }

    // for pkt out
    pkt_out = pcap_open_live(iface, 4096, 1, 10, errbuf);
    if (pkt_out == NULL) {
        printf("Unable to open interface %s in pcap: %s\n", iface, errbuf);
        return NULL;
    }

    pi = mi_priv(mi);
    pi->fd_in = pkt_in;
    pi->fd_out = pkt_out;

    return mi;
}
Пример #25
0
int
capture_online(const char *dev, const char *outfile)
{
    //! Error string
    char errbuf[PCAP_ERRBUF_SIZE];

    // Set capture mode
    capinfo.status = CAPTURE_ONLINE;

    // Try to find capture device information
    if (pcap_lookupnet(dev, &capinfo.net, &capinfo.mask, errbuf) == -1) {
        fprintf(stderr, "Can't get netmask for device %s\n", dev);
        capinfo.net = 0;
        capinfo.mask = 0;
    }

    // Open capture device
    capinfo.handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
    if (capinfo.handle == NULL) {
        fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
        return 2;
    }

    // If requested store packets in a dump file
    if (outfile) {
        if ((capinfo.pd = dump_open(outfile)) == NULL) {
            fprintf(stderr, "Couldn't open output dump file %s: %s\n", outfile,
                    pcap_geterr(capinfo.handle));
            return 2;
        }
    }

    // Get datalink to parse packets correctly
    capinfo.link = pcap_datalink(capinfo.handle);

    // Check linktypes sngrep knowns before start parsing packets
    if ((capinfo.link_hl = datalink_size(capinfo.link)) == -1) {
        fprintf(stderr, "Unable to handle linktype %d\n", capinfo.link);
        return 3;
    }

    // Get Local devices addresses
    pcap_findalldevs(&capinfo.devices, errbuf);

    return 0;
}
int main(int argc, char** argv){
  if(argc != 2){
    fprintf(stderr, "Usage: %s pcap_file\n", argv[0]);
    return -1;
  }
  char* pcap_filename = argv[1];
  char errbuf[PCAP_ERRBUF_SIZE];
  const u_char* packet;
  uint32_t protocols[PFWL_PROTO_L7_NUM];
  struct pcap_pkthdr header;
  memset(protocols, 0, sizeof(protocols));
  uint32_t unknown = 0;

  pcap_t *handle = pcap_open_offline(pcap_filename, errbuf);
  if(handle == NULL){
    fprintf(stderr, "Couldn't open device %s: %s\n", pcap_filename, errbuf);
    return (2);
  }

  pfwl_state_t* state = pfwl_init();
  pfwl_dissection_info_t r;
  pfwl_protocol_l2_t dlt = pfwl_convert_pcap_dlt(pcap_datalink(handle));
  while((packet = pcap_next(handle, &header)) != NULL){
    if(pfwl_dissect_from_L2(state, packet, header.caplen, time(NULL), dlt, &r) >= PFWL_STATUS_OK){
      if(r.l4.protocol == IPPROTO_TCP || r.l4.protocol == IPPROTO_UDP){
        if(r.l7.protocol < PFWL_PROTO_L7_NUM){
          ++protocols[r.l7.protocol];
        }else{
          ++unknown;
        }
      }else{
        ++unknown;
      }
    }
  }
  pfwl_terminate(state);

  if (unknown > 0) printf("Unknown packets: %"PRIu32"\n", unknown);
  for(size_t i = 0; i < PFWL_PROTO_L7_NUM; i++){
    if(protocols[i] > 0){
      printf("%s packets: %"PRIu32"\n", pfwl_get_L7_protocol_name(i), protocols[i]);
    }
  }
  return 0;
}
Пример #27
0
int is_ether(char *iface)
{
   pcap_t *pd;
   char ebuf[PCAP_ERRBUF_SIZE];
   
   if ((pd = pcap_open_live(iface, 1500, PCAP_PROMISC, PCAP_TIMEOUT, ebuf)) == NULL)
      return 0;
  
   if ( pcap_datalink(pd) != DLT_EN10MB) {
      pcap_close(pd);
      return 0;
   }

   /* passed all the test, it is ethernet */
   pcap_close(pd);
   
   return 1;
}
Пример #28
0
static pcap_t	*setup_pcap(char *fname, char *filter, char *errbuf) {
struct bpf_program filter_code;

bpf_u_int32		   netmask;

	/*
	 *  Open the packet capturing file
	 *
	 */
	pcap_handle = pcap_open_offline(fname, errbuf);
	if ( !pcap_handle )
		return NULL;

	netmask = 0;
	/* apply filters if any are requested */
	if ( filter ) {
		if (pcap_compile(pcap_handle, &filter_code, filter, 1, netmask) == -1) {
			/* pcap does not fill in the error code on pcap_compile */
			snprintf(errbuf, PCAP_ERRBUF_SIZE,
					"pcap_compile() failed: %s\n", pcap_geterr(pcap_handle));
			pcap_close(pcap_handle);
			return NULL;
		}
		if (pcap_setfilter(pcap_handle, &filter_code) == -1) {
			/* pcap does not fill in the error code on pcap_compile */
			snprintf(errbuf, PCAP_ERRBUF_SIZE,
					"pcap_setfilter() failed: %s\n", pcap_geterr(pcap_handle));
			pcap_close(pcap_handle);
			return NULL;
		}
	}

	/*
	 *  We need to make sure this is Ethernet.  The DLTEN10MB specifies
	 *  standard 10MB and higher Ethernet.
	 */
	if (pcap_datalink(pcap_handle) != DLT_EN10MB) {
		snprintf(errbuf, PCAP_ERRBUF_SIZE-1, "Snooping not an an ethernet.\n");
	   	pcap_close(pcap_handle);
		return NULL;
	}
	return pcap_handle;

} /* setup_pcap */
Пример #29
0
// Ethernet device list by Pcap API
TOKEN_LIST *GetEthListPcap()
{
	pcap_if_t *alldevs;
	char errbuf[PCAP_ERRBUF_SIZE];
	LIST *o;
	TOKEN_LIST *t;
	int i;

	o = NewListFast(CompareStr);

	if( pcap_findalldevs(&alldevs,errbuf) != -1)
	{
		pcap_if_t *dev = alldevs;
		while(dev != NULL)
		{
			pcap_t *p;
			// Device type will be unknown until open the device?
			p = pcap_open_live(dev->name, 0, false, 0, errbuf);
			if(p != NULL)
			{
				int datalink = pcap_datalink(p);
	//			Debug("type:%s\n",pcap_datalink_val_to_name(datalink));
				pcap_close(p);
				if(datalink == DLT_EN10MB){
					// Enumerate only Ethernet type device
					Add(o, CopyStr(dev->name));
				}
			}
			dev = dev->next;
		}
		pcap_freealldevs(alldevs);
	}
	
	Sort(o);
	t = ZeroMalloc(sizeof(TOKEN_LIST));
	t->NumTokens = LIST_NUM(o);
	t->Token = ZeroMalloc(sizeof(char *) * t->NumTokens);
	for (i = 0;i < LIST_NUM(o);i++)
	{
		t->Token[i] = LIST_DATA(o, i);
	}
	ReleaseList(o);
	return t;
}
Пример #30
0
static void openPcapFileOrDevice(void)
{
  u_int snaplen = 1514;
  int promisc = 1;
  char errbuf[PCAP_ERRBUF_SIZE];
  
  if((_pcap_handle = pcap_open_live(_pcap_file, snaplen, promisc, 500, errbuf)) == NULL) {
    _pcap_handle = pcap_open_offline(_pcap_file, _pcap_error_buffer);
    capture_until = 0;

    if(_pcap_handle == NULL) {
      printf("ERROR: could not open pcap file: %s\n", _pcap_error_buffer);
      exit(-1);
    } else
      printf("Reading packets from pcap file %s...\n", _pcap_file);
  } else
    printf("Capturing live traffic from device %s...\n", _pcap_file);

  _pcap_datalink_type = pcap_datalink(_pcap_handle);

  if(_bpf_filter != NULL) {
    struct bpf_program fcode;

    if(pcap_compile(_pcap_handle, &fcode, _bpf_filter, 1, 0xFFFFFF00) < 0) {
      printf("pcap_compile error: '%s'\n", pcap_geterr(_pcap_handle));
    } else {
      if(pcap_setfilter(_pcap_handle, &fcode) < 0) {
	printf("pcap_setfilter error: '%s'\n", pcap_geterr(_pcap_handle));
      } else
	printf("Succesfully set BPF filter to '%s'\n", _bpf_filter);
    }
  }

  if(capture_until > 0) {
    printf("Capturing traffic up to %u seconds\n", (unsigned int)capture_until);

#ifndef WIN32
    alarm(capture_until);
    signal(SIGALRM, sigproc);
#endif
    capture_until += time(NULL);    
  }
}